llvm_backend.cpp 508 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306
  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(is_type_array(array_type));
  112. GB_ASSERT(1 < swizzle_count && swizzle_count <= 4);
  113. lbAddr v = {lbAddr_Swizzle, addr};
  114. v.swizzle.type = array_type;
  115. v.swizzle.count = swizzle_count;
  116. gb_memmove(v.swizzle.indices, swizzle_indices, swizzle_count);
  117. return v;
  118. }
  119. Type *lb_addr_type(lbAddr const &addr) {
  120. if (addr.addr.value == nullptr) {
  121. return nullptr;
  122. }
  123. if (addr.kind == lbAddr_Map) {
  124. Type *t = base_type(addr.map.type);
  125. GB_ASSERT(is_type_map(t));
  126. return t->Map.value;
  127. }
  128. if (addr.kind == lbAddr_Swizzle) {
  129. return addr.swizzle.type;
  130. }
  131. return type_deref(addr.addr.type);
  132. }
  133. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  134. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  135. }
  136. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  137. if (addr.addr.value == nullptr) {
  138. GB_PANIC("Illegal addr -> nullptr");
  139. return {};
  140. }
  141. switch (addr.kind) {
  142. case lbAddr_Map: {
  143. Type *map_type = base_type(addr.map.type);
  144. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  145. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  146. auto args = array_make<lbValue>(permanent_allocator(), 2);
  147. args[0] = h;
  148. args[1] = key;
  149. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  150. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  151. }
  152. case lbAddr_RelativePointer: {
  153. Type *rel_ptr = base_type(lb_addr_type(addr));
  154. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  155. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  156. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  157. offset = lb_emit_load(p, offset);
  158. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  159. offset = lb_emit_conv(p, offset, t_i64);
  160. }
  161. offset = lb_emit_conv(p, offset, t_uintptr);
  162. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  163. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  164. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  165. // NOTE(bill): nil check
  166. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  167. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  168. return final_ptr;
  169. }
  170. case lbAddr_SoaVariable:
  171. // TODO(bill): FIX THIS HACK
  172. return lb_address_from_load(p, lb_addr_load(p, addr));
  173. case lbAddr_Context:
  174. GB_PANIC("lbAddr_Context should be handled elsewhere");
  175. break;
  176. case lbAddr_Swizzle:
  177. // TOOD(bill): is this good enough logic?
  178. break;
  179. }
  180. return addr.addr;
  181. }
  182. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  183. lbAddr addr = lb_build_addr(p, expr);
  184. return lb_addr_get_ptr(p, addr);
  185. }
  186. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  187. if (build_context.no_bounds_check) {
  188. return;
  189. }
  190. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  191. return;
  192. }
  193. index = lb_emit_conv(p, index, t_int);
  194. len = lb_emit_conv(p, len, t_int);
  195. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  196. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  197. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  198. auto args = array_make<lbValue>(permanent_allocator(), 5);
  199. args[0] = file;
  200. args[1] = line;
  201. args[2] = column;
  202. args[3] = index;
  203. args[4] = len;
  204. lb_emit_runtime_call(p, "bounds_check_error", args);
  205. }
  206. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  207. if (build_context.no_bounds_check) {
  208. return;
  209. }
  210. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  211. return;
  212. }
  213. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  214. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  215. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  216. high = lb_emit_conv(p, high, t_int);
  217. if (!lower_value_used) {
  218. auto args = array_make<lbValue>(permanent_allocator(), 5);
  219. args[0] = file;
  220. args[1] = line;
  221. args[2] = column;
  222. args[3] = high;
  223. args[4] = len;
  224. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  225. } else {
  226. // No need to convert unless used
  227. low = lb_emit_conv(p, low, t_int);
  228. auto args = array_make<lbValue>(permanent_allocator(), 6);
  229. args[0] = file;
  230. args[1] = line;
  231. args[2] = column;
  232. args[3] = low;
  233. args[4] = high;
  234. args[5] = len;
  235. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  236. }
  237. }
  238. bool lb_try_update_alignment(lbValue ptr, unsigned alignment) {
  239. LLVMValueRef addr_ptr = ptr.value;
  240. if (LLVMIsAGlobalValue(addr_ptr) || LLVMIsAAllocaInst(addr_ptr) || LLVMIsALoadInst(addr_ptr)) {
  241. if (LLVMGetAlignment(addr_ptr) < alignment) {
  242. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  243. LLVMSetAlignment(addr_ptr, alignment);
  244. }
  245. }
  246. return LLVMGetAlignment(addr_ptr) >= alignment;
  247. }
  248. return false;
  249. }
  250. bool lb_try_vector_cast(lbModule *m, lbValue ptr, LLVMTypeRef *vector_type_) {
  251. Type *array_type = base_type(type_deref(ptr.type));
  252. GB_ASSERT(is_type_array_like(array_type));
  253. i64 count = get_array_type_count(array_type);
  254. Type *elem_type = base_array_type(array_type);
  255. // TODO(bill): Determine what is the correct limit for doing vector arithmetic
  256. if (type_size_of(array_type) <= build_context.max_align &&
  257. is_type_valid_vector_elem(elem_type)) {
  258. // Try to treat it like a vector if possible
  259. bool possible = false;
  260. LLVMTypeRef vector_type = LLVMVectorType(lb_type(m, elem_type), cast(unsigned)count);
  261. unsigned vector_alignment = cast(unsigned)lb_alignof(vector_type);
  262. LLVMValueRef addr_ptr = ptr.value;
  263. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  264. unsigned alignment = LLVMGetAlignment(addr_ptr);
  265. alignment = gb_max(alignment, vector_alignment);
  266. possible = true;
  267. LLVMSetAlignment(addr_ptr, alignment);
  268. } else if (LLVMIsALoadInst(addr_ptr)) {
  269. unsigned alignment = LLVMGetAlignment(addr_ptr);
  270. possible = alignment >= vector_alignment;
  271. }
  272. // NOTE: Due to alignment requirements, if the pointer is not correctly aligned
  273. // then it cannot be treated as a vector
  274. if (possible) {
  275. if (vector_type_) *vector_type_ =vector_type;
  276. return true;
  277. }
  278. }
  279. return false;
  280. }
  281. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  282. if (addr.addr.value == nullptr) {
  283. return;
  284. }
  285. GB_ASSERT(value.type != nullptr);
  286. if (is_type_untyped_undef(value.type)) {
  287. Type *t = lb_addr_type(addr);
  288. value.type = t;
  289. value.value = LLVMGetUndef(lb_type(p->module, t));
  290. } else if (is_type_untyped_nil(value.type)) {
  291. Type *t = lb_addr_type(addr);
  292. value.type = t;
  293. value.value = LLVMConstNull(lb_type(p->module, t));
  294. }
  295. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  296. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  297. }
  298. if (addr.kind == lbAddr_RelativePointer) {
  299. Type *rel_ptr = base_type(lb_addr_type(addr));
  300. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  301. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  302. GB_ASSERT(is_type_pointer(addr.addr.type));
  303. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  304. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  305. lbValue offset = {};
  306. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  307. offset.type = t_uintptr;
  308. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  309. offset = lb_emit_conv(p, offset, t_i64);
  310. }
  311. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  312. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  313. offset = lb_emit_select(p,
  314. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  315. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  316. offset
  317. );
  318. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  319. return;
  320. } else if (addr.kind == lbAddr_RelativeSlice) {
  321. Type *rel_ptr = base_type(lb_addr_type(addr));
  322. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  323. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  324. GB_ASSERT(is_type_pointer(addr.addr.type));
  325. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  326. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  327. lbValue offset = {};
  328. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  329. offset.type = t_uintptr;
  330. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  331. offset = lb_emit_conv(p, offset, t_i64);
  332. }
  333. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  334. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  335. offset = lb_emit_select(p,
  336. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  337. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  338. offset
  339. );
  340. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  341. lbValue len = lb_slice_len(p, value);
  342. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  343. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  344. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  345. return;
  346. } else if (addr.kind == lbAddr_Map) {
  347. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  348. return;
  349. } else if (addr.kind == lbAddr_Context) {
  350. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  351. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  352. // This has to be done manually since the optimizer cannot determine when this is possible
  353. bool create_new = true;
  354. for_array(i, p->context_stack) {
  355. lbContextData *ctx_data = &p->context_stack[i];
  356. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  357. if (ctx_data->uses > 0) {
  358. create_new = true;
  359. } else if (p->scope_index > ctx_data->scope_index) {
  360. create_new = true;
  361. } else {
  362. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  363. create_new = false;
  364. }
  365. break;
  366. }
  367. }
  368. lbValue next = {};
  369. if (create_new) {
  370. lbValue old = lb_addr_load(p, old_addr);
  371. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  372. lb_addr_store(p, next_addr, old);
  373. lb_push_context_onto_stack(p, next_addr);
  374. next = next_addr.addr;
  375. } else {
  376. next = old_addr.addr;
  377. }
  378. if (addr.ctx.sel.index.count > 0) {
  379. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  380. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  381. lb_emit_store(p, lhs, rhs);
  382. } else {
  383. lbValue lhs = next;
  384. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  385. lb_emit_store(p, lhs, rhs);
  386. }
  387. return;
  388. } else if (addr.kind == lbAddr_SoaVariable) {
  389. Type *t = type_deref(addr.addr.type);
  390. t = base_type(t);
  391. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  392. Type *elem_type = t->Struct.soa_elem;
  393. value = lb_emit_conv(p, value, elem_type);
  394. elem_type = base_type(elem_type);
  395. lbValue index = addr.soa.index;
  396. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  397. Type *t = base_type(type_deref(addr.addr.type));
  398. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  399. lbValue len = lb_soa_struct_len(p, addr.addr);
  400. if (addr.soa.index_expr != nullptr) {
  401. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  402. }
  403. }
  404. isize field_count = 0;
  405. switch (elem_type->kind) {
  406. case Type_Struct:
  407. field_count = elem_type->Struct.fields.count;
  408. break;
  409. case Type_Array:
  410. field_count = elem_type->Array.count;
  411. break;
  412. }
  413. for (isize i = 0; i < field_count; i++) {
  414. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  415. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  416. if (t->Struct.soa_kind == StructSoa_Fixed) {
  417. dst = lb_emit_array_ep(p, dst, index);
  418. lb_emit_store(p, dst, src);
  419. } else {
  420. lbValue field = lb_emit_load(p, dst);
  421. dst = lb_emit_ptr_offset(p, field, index);
  422. lb_emit_store(p, dst, src);
  423. }
  424. }
  425. return;
  426. } else if (addr.kind == lbAddr_Swizzle) {
  427. GB_ASSERT(addr.swizzle.count <= 4);
  428. GB_ASSERT(value.value != nullptr);
  429. value = lb_emit_conv(p, value, lb_addr_type(addr));
  430. lbValue dst = lb_addr_get_ptr(p, addr);
  431. lbValue src = lb_address_from_load_or_generate_local(p, value);
  432. {
  433. lbValue src_ptrs[4] = {};
  434. lbValue src_loads[4] = {};
  435. lbValue dst_ptrs[4] = {};
  436. for (u8 i = 0; i < addr.swizzle.count; i++) {
  437. src_ptrs[i] = lb_emit_array_epi(p, src, i);
  438. }
  439. for (u8 i = 0; i < addr.swizzle.count; i++) {
  440. dst_ptrs[i] = lb_emit_array_epi(p, dst, addr.swizzle.indices[i]);
  441. }
  442. for (u8 i = 0; i < addr.swizzle.count; i++) {
  443. src_loads[i] = lb_emit_load(p, src_ptrs[i]);
  444. }
  445. for (u8 i = 0; i < addr.swizzle.count; i++) {
  446. lb_emit_store(p, dst_ptrs[i], src_loads[i]);
  447. }
  448. }
  449. return;
  450. }
  451. GB_ASSERT(value.value != nullptr);
  452. value = lb_emit_conv(p, value, lb_addr_type(addr));
  453. // if (lb_is_const_or_global(value)) {
  454. // // NOTE(bill): Just bypass the actual storage and set the initializer
  455. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  456. // LLVMValueRef dst = addr.addr.value;
  457. // LLVMValueRef src = value.value;
  458. // LLVMSetInitializer(dst, src);
  459. // return;
  460. // }
  461. // }
  462. lb_emit_store(p, addr.addr, value);
  463. }
  464. void lb_const_store(lbValue ptr, lbValue value) {
  465. GB_ASSERT(lb_is_const(ptr));
  466. GB_ASSERT(lb_is_const(value));
  467. GB_ASSERT(is_type_pointer(ptr.type));
  468. LLVMSetInitializer(ptr.value, value.value);
  469. }
  470. bool lb_is_type_proc_recursive(Type *t) {
  471. for (;;) {
  472. if (t == nullptr) {
  473. return false;
  474. }
  475. switch (t->kind) {
  476. case Type_Named:
  477. t = t->Named.base;
  478. break;
  479. case Type_Pointer:
  480. t = t->Pointer.elem;
  481. break;
  482. case Type_Array:
  483. t = t->Array.elem;
  484. break;
  485. case Type_EnumeratedArray:
  486. t = t->EnumeratedArray.elem;
  487. break;
  488. case Type_Slice:
  489. t = t->Slice.elem;
  490. break;
  491. case Type_DynamicArray:
  492. t = t->DynamicArray.elem;
  493. break;
  494. case Type_Proc:
  495. return true;
  496. default:
  497. return false;
  498. }
  499. }
  500. }
  501. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  502. GB_ASSERT(value.value != nullptr);
  503. Type *a = type_deref(ptr.type);
  504. if (is_type_boolean(a)) {
  505. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  506. value = lb_emit_conv(p, value, a);
  507. }
  508. Type *ca = core_type(a);
  509. if (ca->kind == Type_Basic) {
  510. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  511. }
  512. if (lb_is_type_proc_recursive(a)) {
  513. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  514. // stored as regular pointer with no procedure information
  515. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  516. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  517. LLVMBuildStore(p->builder, v, ptr.value);
  518. } else {
  519. Type *ca = core_type(a);
  520. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  521. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  522. } else {
  523. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  524. }
  525. LLVMBuildStore(p->builder, value.value, ptr.value);
  526. }
  527. }
  528. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  529. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  530. }
  531. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  532. lbModule *m = p->module;
  533. GB_ASSERT(value.value != nullptr);
  534. GB_ASSERT(is_type_pointer(value.type));
  535. Type *t = type_deref(value.type);
  536. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  537. return lbValue{v, t};
  538. }
  539. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  540. GB_ASSERT(addr.addr.value != nullptr);
  541. if (addr.kind == lbAddr_RelativePointer) {
  542. Type *rel_ptr = base_type(lb_addr_type(addr));
  543. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  544. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  545. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  546. offset = lb_emit_load(p, offset);
  547. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  548. offset = lb_emit_conv(p, offset, t_i64);
  549. }
  550. offset = lb_emit_conv(p, offset, t_uintptr);
  551. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  552. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  553. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  554. // NOTE(bill): nil check
  555. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  556. lbValue final_ptr = {};
  557. final_ptr.type = absolute_ptr.type;
  558. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  559. return lb_emit_load(p, final_ptr);
  560. } else if (addr.kind == lbAddr_RelativeSlice) {
  561. Type *rel_ptr = base_type(lb_addr_type(addr));
  562. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  563. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  564. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  565. lbValue offset = lb_emit_load(p, offset_ptr);
  566. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  567. offset = lb_emit_conv(p, offset, t_i64);
  568. }
  569. offset = lb_emit_conv(p, offset, t_uintptr);
  570. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  571. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  572. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  573. Type *slice_elem = slice_type->Slice.elem;
  574. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  575. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  576. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  577. // NOTE(bill): nil check
  578. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  579. lbValue data = {};
  580. data.type = absolute_ptr.type;
  581. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  582. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  583. len = lb_emit_conv(p, len, t_int);
  584. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  585. lb_fill_slice(p, slice, data, len);
  586. return lb_addr_load(p, slice);
  587. } else if (addr.kind == lbAddr_Map) {
  588. Type *map_type = base_type(addr.map.type);
  589. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  590. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  591. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  592. auto args = array_make<lbValue>(permanent_allocator(), 2);
  593. args[0] = h;
  594. args[1] = key;
  595. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  596. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  597. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  598. lbBlock *then = lb_create_block(p, "map.get.then");
  599. lbBlock *done = lb_create_block(p, "map.get.done");
  600. lb_emit_if(p, ok, then, done);
  601. lb_start_block(p, then);
  602. {
  603. // TODO(bill): mem copy it instead?
  604. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  605. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  606. lb_emit_store(p, gep0, lb_emit_load(p, value));
  607. }
  608. lb_emit_jump(p, done);
  609. lb_start_block(p, done);
  610. if (is_type_tuple(addr.map.result)) {
  611. return lb_addr_load(p, v);
  612. } else {
  613. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  614. return lb_emit_load(p, single);
  615. }
  616. } else if (addr.kind == lbAddr_Context) {
  617. lbValue a = addr.addr;
  618. for_array(i, p->context_stack) {
  619. lbContextData *ctx_data = &p->context_stack[i];
  620. if (ctx_data->ctx.addr.value == a.value) {
  621. ctx_data->uses += 1;
  622. break;
  623. }
  624. }
  625. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  626. if (addr.ctx.sel.index.count > 0) {
  627. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  628. return lb_emit_load(p, b);
  629. } else {
  630. return lb_emit_load(p, a);
  631. }
  632. } else if (addr.kind == lbAddr_SoaVariable) {
  633. Type *t = type_deref(addr.addr.type);
  634. t = base_type(t);
  635. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  636. Type *elem = t->Struct.soa_elem;
  637. lbValue len = {};
  638. if (t->Struct.soa_kind == StructSoa_Fixed) {
  639. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  640. } else {
  641. lbValue v = lb_emit_load(p, addr.addr);
  642. len = lb_soa_struct_len(p, v);
  643. }
  644. lbAddr res = lb_add_local_generated(p, elem, true);
  645. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  646. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  647. }
  648. if (t->Struct.soa_kind == StructSoa_Fixed) {
  649. for_array(i, t->Struct.fields) {
  650. Entity *field = t->Struct.fields[i];
  651. Type *base_type = field->type;
  652. GB_ASSERT(base_type->kind == Type_Array);
  653. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  654. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  655. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  656. lbValue src = lb_emit_load(p, src_ptr);
  657. lb_emit_store(p, dst, src);
  658. }
  659. } else {
  660. isize field_count = t->Struct.fields.count;
  661. if (t->Struct.soa_kind == StructSoa_Slice) {
  662. field_count -= 1;
  663. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  664. field_count -= 3;
  665. }
  666. for (isize i = 0; i < field_count; i++) {
  667. Entity *field = t->Struct.fields[i];
  668. Type *base_type = field->type;
  669. GB_ASSERT(base_type->kind == Type_Pointer);
  670. Type *elem = base_type->Pointer.elem;
  671. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  672. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  673. lbValue src = lb_emit_load(p, src_ptr);
  674. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  675. src = lb_emit_load(p, src);
  676. lb_emit_store(p, dst, src);
  677. }
  678. }
  679. return lb_addr_load(p, res);
  680. } else if (addr.kind == lbAddr_Swizzle) {
  681. Type *array_type = base_type(addr.swizzle.type);
  682. GB_ASSERT(array_type->kind == Type_Array);
  683. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle.type);
  684. static u8 const ordered_indices[4] = {0, 1, 2, 3};
  685. if (gb_memcompare(ordered_indices, addr.swizzle.indices, addr.swizzle.count) == 0) {
  686. if (lb_try_update_alignment(addr.addr, res_align)) {
  687. Type *pt = alloc_type_pointer(addr.swizzle.type);
  688. lbValue res = {};
  689. res.value = LLVMBuildPointerCast(p->builder, addr.addr.value, lb_type(p->module, pt), "");
  690. res.type = pt;
  691. return lb_emit_load(p, res);
  692. }
  693. }
  694. Type *elem_type = base_type(array_type->Array.elem);
  695. lbAddr res = lb_add_local_generated(p, addr.swizzle.type, false);
  696. lbValue ptr = lb_addr_get_ptr(p, res);
  697. GB_ASSERT(is_type_pointer(ptr.type));
  698. LLVMTypeRef vector_type = nullptr;
  699. if (lb_try_vector_cast(p->module, addr.addr, &vector_type)) {
  700. LLVMSetAlignment(res.addr.value, cast(unsigned)lb_alignof(vector_type));
  701. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, addr.addr.value, LLVMPointerType(vector_type, 0), "");
  702. LLVMValueRef v = LLVMBuildLoad2(p->builder, vector_type, vp, "");
  703. LLVMValueRef scalars[4] = {};
  704. for (u8 i = 0; i < addr.swizzle.count; i++) {
  705. scalars[i] = LLVMConstInt(lb_type(p->module, t_u32), addr.swizzle.indices[i], false);
  706. }
  707. LLVMValueRef mask = LLVMConstVector(scalars, addr.swizzle.count);
  708. LLVMValueRef sv = LLVMBuildShuffleVector(p->builder, v, LLVMGetUndef(vector_type), mask, "");
  709. LLVMValueRef dst = LLVMBuildPointerCast(p->builder, ptr.value, LLVMPointerType(LLVMTypeOf(sv), 0), "");
  710. LLVMBuildStore(p->builder, sv, dst);
  711. } else {
  712. for (u8 i = 0; i < addr.swizzle.count; i++) {
  713. u8 index = addr.swizzle.indices[i];
  714. lbValue dst = lb_emit_array_epi(p, ptr, i);
  715. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  716. lb_emit_store(p, dst, lb_emit_load(p, src));
  717. }
  718. }
  719. return lb_addr_load(p, res);
  720. }
  721. if (is_type_proc(addr.addr.type)) {
  722. return addr.addr;
  723. }
  724. return lb_emit_load(p, addr.addr);
  725. }
  726. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  727. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  728. }
  729. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  730. Type *t = u.type;
  731. GB_ASSERT_MSG(is_type_pointer(t) &&
  732. is_type_union(type_deref(t)), "%s", type_to_string(t));
  733. Type *ut = type_deref(t);
  734. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  735. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  736. GB_ASSERT(type_size_of(ut) > 0);
  737. Type *tag_type = union_tag_type(ut);
  738. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  739. unsigned element_count = LLVMCountStructElementTypes(uvt);
  740. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  741. lbValue tag_ptr = {};
  742. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  743. tag_ptr.type = alloc_type_pointer(tag_type);
  744. return tag_ptr;
  745. }
  746. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  747. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  748. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  749. return lb_emit_load(p, tag_ptr);
  750. }
  751. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  752. Type *t = type_deref(parent.type);
  753. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  754. // No tag needed!
  755. } else {
  756. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  757. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  758. }
  759. }
  760. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  761. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  762. lb_emit_store(p, underlying, variant);
  763. lb_emit_store_union_variant_tag(p, parent, variant_type);
  764. }
  765. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  766. unsigned field_count = LLVMCountStructElementTypes(src);
  767. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  768. LLVMGetStructElementTypes(src, fields);
  769. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  770. }
  771. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  772. switch (alignment) {
  773. case 1:
  774. return LLVMArrayType(lb_type(m, t_u8), 0);
  775. case 2:
  776. return LLVMArrayType(lb_type(m, t_u16), 0);
  777. case 4:
  778. return LLVMArrayType(lb_type(m, t_u32), 0);
  779. case 8:
  780. return LLVMArrayType(lb_type(m, t_u64), 0);
  781. case 16:
  782. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  783. default:
  784. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  785. break;
  786. }
  787. return nullptr;
  788. }
  789. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  790. if (!elem_type_can_be_constant(elem_type)) {
  791. return false;
  792. }
  793. if (elem->kind == Ast_FieldValue) {
  794. elem = elem->FieldValue.value;
  795. }
  796. TypeAndValue tav = type_and_value_of_expr(elem);
  797. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  798. return tav.value.kind != ExactValue_Invalid;
  799. }
  800. String lb_mangle_name(lbModule *m, Entity *e) {
  801. String name = e->token.string;
  802. AstPackage *pkg = e->pkg;
  803. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  804. String pkgn = pkg->name;
  805. GB_ASSERT(!rune_is_digit(pkgn[0]));
  806. if (pkgn == "llvm") {
  807. pkgn = str_lit("llvm$");
  808. }
  809. isize max_len = pkgn.len + 1 + name.len + 1;
  810. bool require_suffix_id = is_type_polymorphic(e->type, true);
  811. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  812. require_suffix_id = true;
  813. } else if (is_blank_ident(e->token)) {
  814. require_suffix_id = true;
  815. }if (e->flags & EntityFlag_NotExported) {
  816. require_suffix_id = true;
  817. }
  818. if (require_suffix_id) {
  819. max_len += 21;
  820. }
  821. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  822. isize new_name_len = gb_snprintf(
  823. new_name, max_len,
  824. "%.*s.%.*s", LIT(pkgn), LIT(name)
  825. );
  826. if (require_suffix_id) {
  827. char *str = new_name + new_name_len-1;
  828. isize len = max_len-new_name_len;
  829. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  830. new_name_len += extra-1;
  831. }
  832. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  833. return mangled_name;
  834. }
  835. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  836. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  837. // and as a result, the declaration does not have time to determine what it should be
  838. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  839. if (e->TypeName.ir_mangled_name.len != 0) {
  840. return e->TypeName.ir_mangled_name;
  841. }
  842. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  843. if (p == nullptr) {
  844. Entity *proc = nullptr;
  845. if (e->parent_proc_decl != nullptr) {
  846. proc = e->parent_proc_decl->entity;
  847. } else {
  848. Scope *scope = e->scope;
  849. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  850. scope = scope->parent;
  851. }
  852. GB_ASSERT(scope != nullptr);
  853. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  854. proc = scope->procedure_entity;
  855. }
  856. GB_ASSERT(proc->kind == Entity_Procedure);
  857. if (proc->code_gen_procedure != nullptr) {
  858. p = proc->code_gen_procedure;
  859. }
  860. }
  861. // NOTE(bill): Generate a new name
  862. // parent_proc.name-guid
  863. String ts_name = e->token.string;
  864. if (p != nullptr) {
  865. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  866. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  867. u32 guid = ++p->module->nested_type_name_guid;
  868. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  869. String name = make_string(cast(u8 *)name_text, name_len-1);
  870. e->TypeName.ir_mangled_name = name;
  871. return name;
  872. } else {
  873. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  874. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  875. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  876. static u32 guid = 0;
  877. guid += 1;
  878. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  879. String name = make_string(cast(u8 *)name_text, name_len-1);
  880. e->TypeName.ir_mangled_name = name;
  881. return name;
  882. }
  883. }
  884. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  885. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  886. return e->TypeName.ir_mangled_name;
  887. }
  888. GB_ASSERT(e != nullptr);
  889. if (e->pkg == nullptr) {
  890. return e->token.string;
  891. }
  892. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  893. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  894. }
  895. String name = {};
  896. bool no_name_mangle = false;
  897. if (e->kind == Entity_Variable) {
  898. bool is_foreign = e->Variable.is_foreign;
  899. bool is_export = e->Variable.is_export;
  900. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  901. if (e->Variable.link_name.len > 0) {
  902. return e->Variable.link_name;
  903. }
  904. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  905. return e->Procedure.link_name;
  906. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  907. no_name_mangle = true;
  908. }
  909. if (!no_name_mangle) {
  910. name = lb_mangle_name(m, e);
  911. }
  912. if (name.len == 0) {
  913. name = e->token.string;
  914. }
  915. if (e->kind == Entity_TypeName) {
  916. e->TypeName.ir_mangled_name = name;
  917. } else if (e->kind == Entity_Procedure) {
  918. e->Procedure.link_name = name;
  919. }
  920. return name;
  921. }
  922. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  923. Type *original_type = type;
  924. LLVMContextRef ctx = m->ctx;
  925. i64 size = type_size_of(type); // Check size
  926. GB_ASSERT(type != t_invalid);
  927. switch (type->kind) {
  928. case Type_Basic:
  929. switch (type->Basic.kind) {
  930. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  931. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  932. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  933. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  934. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  935. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  936. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  937. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  938. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  939. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  940. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  941. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  942. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  943. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  944. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  945. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  946. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  947. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  948. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  949. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  950. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  951. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  952. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  953. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  954. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  955. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  956. case Basic_complex32:
  957. {
  958. char const *name = "..complex32";
  959. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  960. if (type != nullptr) {
  961. return type;
  962. }
  963. type = LLVMStructCreateNamed(ctx, name);
  964. LLVMTypeRef fields[2] = {
  965. lb_type(m, t_f16),
  966. lb_type(m, t_f16),
  967. };
  968. LLVMStructSetBody(type, fields, 2, false);
  969. return type;
  970. }
  971. case Basic_complex64:
  972. {
  973. char const *name = "..complex64";
  974. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  975. if (type != nullptr) {
  976. return type;
  977. }
  978. type = LLVMStructCreateNamed(ctx, name);
  979. LLVMTypeRef fields[2] = {
  980. lb_type(m, t_f32),
  981. lb_type(m, t_f32),
  982. };
  983. LLVMStructSetBody(type, fields, 2, false);
  984. return type;
  985. }
  986. case Basic_complex128:
  987. {
  988. char const *name = "..complex128";
  989. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  990. if (type != nullptr) {
  991. return type;
  992. }
  993. type = LLVMStructCreateNamed(ctx, name);
  994. LLVMTypeRef fields[2] = {
  995. lb_type(m, t_f64),
  996. lb_type(m, t_f64),
  997. };
  998. LLVMStructSetBody(type, fields, 2, false);
  999. return type;
  1000. }
  1001. case Basic_quaternion64:
  1002. {
  1003. char const *name = "..quaternion64";
  1004. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1005. if (type != nullptr) {
  1006. return type;
  1007. }
  1008. type = LLVMStructCreateNamed(ctx, name);
  1009. LLVMTypeRef fields[4] = {
  1010. lb_type(m, t_f16),
  1011. lb_type(m, t_f16),
  1012. lb_type(m, t_f16),
  1013. lb_type(m, t_f16),
  1014. };
  1015. LLVMStructSetBody(type, fields, 4, false);
  1016. return type;
  1017. }
  1018. case Basic_quaternion128:
  1019. {
  1020. char const *name = "..quaternion128";
  1021. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1022. if (type != nullptr) {
  1023. return type;
  1024. }
  1025. type = LLVMStructCreateNamed(ctx, name);
  1026. LLVMTypeRef fields[4] = {
  1027. lb_type(m, t_f32),
  1028. lb_type(m, t_f32),
  1029. lb_type(m, t_f32),
  1030. lb_type(m, t_f32),
  1031. };
  1032. LLVMStructSetBody(type, fields, 4, false);
  1033. return type;
  1034. }
  1035. case Basic_quaternion256:
  1036. {
  1037. char const *name = "..quaternion256";
  1038. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1039. if (type != nullptr) {
  1040. return type;
  1041. }
  1042. type = LLVMStructCreateNamed(ctx, name);
  1043. LLVMTypeRef fields[4] = {
  1044. lb_type(m, t_f64),
  1045. lb_type(m, t_f64),
  1046. lb_type(m, t_f64),
  1047. lb_type(m, t_f64),
  1048. };
  1049. LLVMStructSetBody(type, fields, 4, false);
  1050. return type;
  1051. }
  1052. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1053. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1054. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1055. case Basic_rawptr: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1056. case Basic_string:
  1057. {
  1058. char const *name = "..string";
  1059. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1060. if (type != nullptr) {
  1061. return type;
  1062. }
  1063. type = LLVMStructCreateNamed(ctx, name);
  1064. LLVMTypeRef fields[2] = {
  1065. LLVMPointerType(lb_type(m, t_u8), 0),
  1066. lb_type(m, t_int),
  1067. };
  1068. LLVMStructSetBody(type, fields, 2, false);
  1069. return type;
  1070. }
  1071. case Basic_cstring: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1072. case Basic_any:
  1073. {
  1074. char const *name = "..any";
  1075. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1076. if (type != nullptr) {
  1077. return type;
  1078. }
  1079. type = LLVMStructCreateNamed(ctx, name);
  1080. LLVMTypeRef fields[2] = {
  1081. lb_type(m, t_rawptr),
  1082. lb_type(m, t_typeid),
  1083. };
  1084. LLVMStructSetBody(type, fields, 2, false);
  1085. return type;
  1086. }
  1087. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  1088. // Endian Specific Types
  1089. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  1090. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  1091. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  1092. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  1093. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  1094. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  1095. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  1096. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  1097. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  1098. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  1099. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  1100. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  1101. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  1102. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  1103. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  1104. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  1105. // Untyped types
  1106. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1107. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1108. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1109. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1110. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1111. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1112. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1113. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1114. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1115. }
  1116. break;
  1117. case Type_Named:
  1118. {
  1119. Type *base = base_type(type->Named.base);
  1120. switch (base->kind) {
  1121. case Type_Basic:
  1122. return lb_type_internal(m, base);
  1123. case Type_Named:
  1124. case Type_Generic:
  1125. GB_PANIC("INVALID TYPE");
  1126. break;
  1127. case Type_Pointer:
  1128. case Type_Array:
  1129. case Type_EnumeratedArray:
  1130. case Type_Slice:
  1131. case Type_DynamicArray:
  1132. case Type_Map:
  1133. case Type_Enum:
  1134. case Type_BitSet:
  1135. case Type_SimdVector:
  1136. return lb_type_internal(m, base);
  1137. // TODO(bill): Deal with this correctly. Can this be named?
  1138. case Type_Proc:
  1139. return lb_type_internal(m, base);
  1140. case Type_Tuple:
  1141. return lb_type_internal(m, base);
  1142. }
  1143. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1144. if (found) {
  1145. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1146. if (kind == LLVMStructTypeKind) {
  1147. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1148. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1149. if (llvm_type != nullptr) {
  1150. return llvm_type;
  1151. }
  1152. llvm_type = LLVMStructCreateNamed(ctx, name);
  1153. map_set(&m->types, hash_type(type), llvm_type);
  1154. lb_clone_struct_type(llvm_type, *found);
  1155. return llvm_type;
  1156. }
  1157. }
  1158. switch (base->kind) {
  1159. case Type_Struct:
  1160. case Type_Union:
  1161. {
  1162. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1163. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1164. if (llvm_type != nullptr) {
  1165. return llvm_type;
  1166. }
  1167. llvm_type = LLVMStructCreateNamed(ctx, name);
  1168. map_set(&m->types, hash_type(type), llvm_type);
  1169. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1170. return llvm_type;
  1171. }
  1172. }
  1173. return lb_type_internal(m, base);
  1174. }
  1175. case Type_Pointer:
  1176. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1177. case Type_Array: {
  1178. m->internal_type_level -= 1;
  1179. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1180. m->internal_type_level += 1;
  1181. return t;
  1182. }
  1183. case Type_EnumeratedArray: {
  1184. m->internal_type_level -= 1;
  1185. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1186. m->internal_type_level += 1;
  1187. return t;
  1188. }
  1189. case Type_Slice:
  1190. {
  1191. LLVMTypeRef fields[2] = {
  1192. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1193. lb_type(m, t_int), // len
  1194. };
  1195. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1196. }
  1197. break;
  1198. case Type_DynamicArray:
  1199. {
  1200. LLVMTypeRef fields[4] = {
  1201. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1202. lb_type(m, t_int), // len
  1203. lb_type(m, t_int), // cap
  1204. lb_type(m, t_allocator), // allocator
  1205. };
  1206. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1207. }
  1208. break;
  1209. case Type_Map:
  1210. return lb_type(m, type->Map.internal_type);
  1211. case Type_Struct:
  1212. {
  1213. if (type->Struct.is_raw_union) {
  1214. unsigned field_count = 2;
  1215. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1216. i64 alignment = type_align_of(type);
  1217. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1218. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1219. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1220. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1221. }
  1222. isize offset = 0;
  1223. if (type->Struct.custom_align > 0) {
  1224. offset = 1;
  1225. }
  1226. m->internal_type_level += 1;
  1227. defer (m->internal_type_level -= 1);
  1228. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1229. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1230. for_array(i, type->Struct.fields) {
  1231. Entity *field = type->Struct.fields[i];
  1232. fields[i+offset] = lb_type(m, field->type);
  1233. }
  1234. if (type->Struct.custom_align > 0) {
  1235. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1236. }
  1237. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1238. }
  1239. break;
  1240. case Type_Union:
  1241. if (type->Union.variants.count == 0) {
  1242. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1243. } else {
  1244. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1245. // LLVM takes the first element's alignment as the entire alignment (like C)
  1246. i64 align = type_align_of(type);
  1247. i64 size = type_size_of(type);
  1248. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1249. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1250. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1251. }
  1252. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1253. LLVMTypeRef fields[3] = {};
  1254. unsigned field_count = 1;
  1255. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1256. if (is_type_union_maybe_pointer(type)) {
  1257. field_count += 1;
  1258. fields[1] = lb_type(m, type->Union.variants[0]);
  1259. } else {
  1260. field_count += 2;
  1261. if (block_size == align) {
  1262. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1263. } else {
  1264. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1265. }
  1266. fields[2] = lb_type(m, union_tag_type(type));
  1267. }
  1268. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1269. }
  1270. break;
  1271. case Type_Enum:
  1272. return lb_type(m, base_enum_type(type));
  1273. case Type_Tuple:
  1274. if (type->Tuple.variables.count == 1) {
  1275. return lb_type(m, type->Tuple.variables[0]->type);
  1276. } else {
  1277. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1278. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1279. for_array(i, type->Tuple.variables) {
  1280. Entity *field = type->Tuple.variables[i];
  1281. LLVMTypeRef param_type = nullptr;
  1282. param_type = lb_type(m, field->type);
  1283. fields[i] = param_type;
  1284. }
  1285. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1286. }
  1287. case Type_Proc:
  1288. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1289. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1290. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1291. } else {
  1292. unsigned param_count = 0;
  1293. if (type->Proc.calling_convention == ProcCC_Odin) {
  1294. param_count += 1;
  1295. }
  1296. if (type->Proc.param_count != 0) {
  1297. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1298. for_array(i, type->Proc.params->Tuple.variables) {
  1299. Entity *e = type->Proc.params->Tuple.variables[i];
  1300. if (e->kind != Entity_Variable) {
  1301. continue;
  1302. }
  1303. if (e->flags & EntityFlag_CVarArg) {
  1304. continue;
  1305. }
  1306. param_count += 1;
  1307. }
  1308. }
  1309. m->internal_type_level += 1;
  1310. defer (m->internal_type_level -= 1);
  1311. LLVMTypeRef ret = nullptr;
  1312. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1313. if (type->Proc.result_count != 0) {
  1314. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1315. ret = lb_type(m, single_ret);
  1316. if (ret != nullptr) {
  1317. if (is_type_boolean(single_ret) &&
  1318. is_calling_convention_none(type->Proc.calling_convention) &&
  1319. type_size_of(single_ret) <= 1) {
  1320. ret = LLVMInt1TypeInContext(m->ctx);
  1321. }
  1322. }
  1323. }
  1324. isize param_index = 0;
  1325. if (type->Proc.param_count != 0) {
  1326. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1327. for_array(i, type->Proc.params->Tuple.variables) {
  1328. Entity *e = type->Proc.params->Tuple.variables[i];
  1329. if (e->kind != Entity_Variable) {
  1330. continue;
  1331. }
  1332. if (e->flags & EntityFlag_CVarArg) {
  1333. continue;
  1334. }
  1335. Type *e_type = reduce_tuple_to_single_type(e->type);
  1336. LLVMTypeRef param_type = nullptr;
  1337. if (is_type_boolean(e_type) &&
  1338. type_size_of(e_type) <= 1) {
  1339. param_type = LLVMInt1TypeInContext(m->ctx);
  1340. } else {
  1341. if (is_type_proc(e_type)) {
  1342. param_type = lb_type(m, t_rawptr);
  1343. } else {
  1344. param_type = lb_type(m, e_type);
  1345. }
  1346. }
  1347. params[param_index++] = param_type;
  1348. }
  1349. }
  1350. if (param_index < param_count) {
  1351. params[param_index++] = lb_type(m, t_rawptr);
  1352. }
  1353. GB_ASSERT(param_index == param_count);
  1354. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1355. {
  1356. for_array(j, ft->args) {
  1357. auto arg = ft->args[j];
  1358. GB_ASSERT_MSG(LLVMGetTypeContext(arg.type) == ft->ctx,
  1359. "\n\t%s %td/%td"
  1360. "\n\tArgTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1361. LLVMPrintTypeToString(arg.type),
  1362. j, ft->args.count,
  1363. LLVMGetTypeContext(arg.type), ft->ctx, LLVMGetGlobalContext());
  1364. }
  1365. GB_ASSERT_MSG(LLVMGetTypeContext(ft->ret.type) == ft->ctx,
  1366. "\n\t%s"
  1367. "\n\tRetTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1368. LLVMPrintTypeToString(ft->ret.type),
  1369. LLVMGetTypeContext(ft->ret.type), ft->ctx, LLVMGetGlobalContext());
  1370. }
  1371. map_set(&m->function_type_map, hash_type(type), ft);
  1372. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1373. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1374. GB_ASSERT_MSG(LLVMGetTypeContext(new_abi_fn_type) == m->ctx,
  1375. "\n\tFuncTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1376. LLVMGetTypeContext(new_abi_fn_type), m->ctx, LLVMGetGlobalContext());
  1377. return new_abi_fn_ptr_type;
  1378. }
  1379. break;
  1380. case Type_BitSet:
  1381. {
  1382. Type *ut = bit_set_to_int(type);
  1383. return lb_type(m, ut);
  1384. }
  1385. case Type_SimdVector:
  1386. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1387. case Type_RelativePointer:
  1388. return lb_type_internal(m, type->RelativePointer.base_integer);
  1389. case Type_RelativeSlice:
  1390. {
  1391. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1392. unsigned field_count = 2;
  1393. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1394. fields[0] = base_integer;
  1395. fields[1] = base_integer;
  1396. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1397. }
  1398. }
  1399. GB_PANIC("Invalid type %s", type_to_string(type));
  1400. return LLVMInt32TypeInContext(ctx);
  1401. }
  1402. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1403. type = default_type(type);
  1404. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1405. if (found) {
  1406. return *found;
  1407. }
  1408. LLVMTypeRef llvm_type = nullptr;
  1409. m->internal_type_level += 1;
  1410. llvm_type = lb_type_internal(m, type);
  1411. m->internal_type_level -= 1;
  1412. if (m->internal_type_level == 0) {
  1413. map_set(&m->types, hash_type(type), llvm_type);
  1414. if (is_type_named(type)) {
  1415. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1416. }
  1417. }
  1418. return llvm_type;
  1419. }
  1420. lbFunctionType *lb_get_function_type(lbModule *m, lbProcedure *p, Type *pt) {
  1421. lbFunctionType **ft_found = nullptr;
  1422. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1423. if (!ft_found) {
  1424. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  1425. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1426. }
  1427. GB_ASSERT(ft_found != nullptr);
  1428. return *ft_found;
  1429. }
  1430. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1431. if (key == nullptr) {
  1432. return nullptr;
  1433. }
  1434. auto found = map_get(&m->debug_values, hash_pointer(key));
  1435. if (found) {
  1436. return *found;
  1437. }
  1438. return nullptr;
  1439. }
  1440. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1441. if (key != nullptr) {
  1442. map_set(&m->debug_values, hash_pointer(key), value);
  1443. }
  1444. }
  1445. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1446. if (node == nullptr) {
  1447. return nullptr;
  1448. }
  1449. return lb_get_llvm_metadata(m, node->file);
  1450. }
  1451. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1452. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1453. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1454. Scope *s = p->scope_stack[i];
  1455. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1456. if (md) {
  1457. return md;
  1458. }
  1459. }
  1460. return p->debug_info;
  1461. }
  1462. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1463. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1464. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1465. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1466. }
  1467. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1468. GB_ASSERT(node != nullptr);
  1469. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1470. }
  1471. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1472. Type *original_type = type;
  1473. LLVMContextRef ctx = m->ctx;
  1474. i64 size = type_size_of(type); // Check size
  1475. GB_ASSERT(type != t_invalid);
  1476. unsigned const word_size = cast(unsigned)build_context.word_size;
  1477. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1478. GB_ASSERT(type->kind == Type_Proc);
  1479. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1480. unsigned parameter_count = 1;
  1481. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1482. Entity *e = type->Proc.params->Tuple.variables[i];
  1483. if (e->kind == Entity_Variable) {
  1484. parameter_count += 1;
  1485. }
  1486. }
  1487. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1488. unsigned param_index = 0;
  1489. if (type->Proc.result_count == 0) {
  1490. parameters[param_index++] = nullptr;
  1491. } else {
  1492. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1493. }
  1494. LLVMMetadataRef parent_scope = nullptr;
  1495. LLVMMetadataRef scope = nullptr;
  1496. LLVMMetadataRef file = nullptr;
  1497. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1498. Entity *e = type->Proc.params->Tuple.variables[i];
  1499. if (e->kind != Entity_Variable) {
  1500. continue;
  1501. }
  1502. parameters[param_index] = lb_debug_type(m, e->type);
  1503. param_index += 1;
  1504. }
  1505. LLVMDIFlags flags = LLVMDIFlagZero;
  1506. if (type->Proc.diverging) {
  1507. flags = LLVMDIFlagNoReturn;
  1508. }
  1509. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1510. }
  1511. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1512. unsigned field_line = 1;
  1513. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1514. AstPackage *pkg = m->info->runtime_package;
  1515. GB_ASSERT(pkg->files.count != 0);
  1516. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1517. LLVMMetadataRef scope = file;
  1518. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1519. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1520. field_flags, lb_debug_type(m, type)
  1521. );
  1522. }
  1523. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1524. AstPackage *pkg = m->info->runtime_package;
  1525. GB_ASSERT(pkg->files.count != 0);
  1526. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1527. LLVMMetadataRef scope = file;
  1528. 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);
  1529. }
  1530. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1531. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1532. #if 1
  1533. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1534. return final_decl;
  1535. #else
  1536. return basic_type;
  1537. #endif
  1538. }
  1539. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1540. Type *original_type = type;
  1541. LLVMContextRef ctx = m->ctx;
  1542. i64 size = type_size_of(type); // Check size
  1543. GB_ASSERT(type != t_invalid);
  1544. unsigned const word_size = cast(unsigned)build_context.word_size;
  1545. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1546. switch (type->kind) {
  1547. case Type_Basic:
  1548. switch (type->Basic.kind) {
  1549. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1550. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1551. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1552. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1553. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1554. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1555. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1556. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1557. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1558. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1559. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1560. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1561. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1562. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1563. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1564. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1565. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1566. case Basic_f16: return lb_debug_type_basic_type(m, str_lit("f16"), 16, LLVMDWARFTypeEncoding_Float);
  1567. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1568. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1569. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1570. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1571. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1572. case Basic_typeid:
  1573. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1574. // Endian Specific Types
  1575. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1576. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1577. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1578. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1579. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1580. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1581. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1582. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1583. case Basic_f16le: return lb_debug_type_basic_type(m, str_lit("f16le"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1584. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1585. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1586. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1587. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1588. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1589. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1590. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1591. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1592. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1593. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1594. case Basic_f16be: return lb_debug_type_basic_type(m, str_lit("f16be"), 16, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1595. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1596. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1597. case Basic_complex32:
  1598. {
  1599. LLVMMetadataRef elements[2] = {};
  1600. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f16, 0);
  1601. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 4);
  1602. return lb_debug_basic_struct(m, str_lit("complex32"), 64, 32, elements, gb_count_of(elements));
  1603. }
  1604. case Basic_complex64:
  1605. {
  1606. LLVMMetadataRef elements[2] = {};
  1607. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1608. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1609. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1610. }
  1611. case Basic_complex128:
  1612. {
  1613. LLVMMetadataRef elements[2] = {};
  1614. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1615. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1616. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1617. }
  1618. case Basic_quaternion64:
  1619. {
  1620. LLVMMetadataRef elements[4] = {};
  1621. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f16, 0);
  1622. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f16, 4);
  1623. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f16, 8);
  1624. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f16, 12);
  1625. return lb_debug_basic_struct(m, str_lit("quaternion64"), 128, 32, elements, gb_count_of(elements));
  1626. }
  1627. case Basic_quaternion128:
  1628. {
  1629. LLVMMetadataRef elements[4] = {};
  1630. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1631. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1632. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1633. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1634. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1635. }
  1636. case Basic_quaternion256:
  1637. {
  1638. LLVMMetadataRef elements[4] = {};
  1639. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1640. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1641. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1642. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1643. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1644. }
  1645. case Basic_rawptr:
  1646. {
  1647. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1648. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1649. }
  1650. case Basic_string:
  1651. {
  1652. LLVMMetadataRef elements[2] = {};
  1653. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1654. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1655. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1656. }
  1657. case Basic_cstring:
  1658. {
  1659. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1660. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1661. }
  1662. case Basic_any:
  1663. {
  1664. LLVMMetadataRef elements[2] = {};
  1665. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1666. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1667. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1668. }
  1669. // Untyped types
  1670. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1671. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1672. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1673. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1674. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1675. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1676. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1677. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1678. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1679. default: GB_PANIC("Basic Unhandled"); break;
  1680. }
  1681. break;
  1682. case Type_Named:
  1683. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1684. case Type_Pointer:
  1685. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1686. case Type_Array: {
  1687. LLVMMetadataRef subscripts[1] = {};
  1688. subscripts[0] = LLVMDIBuilderGetOrCreateSubrange(m->debug_builder,
  1689. 0ll,
  1690. type->Array.count
  1691. );
  1692. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1693. 8*cast(uint64_t)type_size_of(type),
  1694. 8*cast(unsigned)type_align_of(type),
  1695. lb_debug_type(m, type->Array.elem),
  1696. subscripts, gb_count_of(subscripts));
  1697. }
  1698. case Type_EnumeratedArray: {
  1699. LLVMMetadataRef subscripts[1] = {};
  1700. subscripts[0] = LLVMDIBuilderGetOrCreateSubrange(m->debug_builder,
  1701. 0ll,
  1702. type->EnumeratedArray.count
  1703. );
  1704. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1705. 8*cast(uint64_t)type_size_of(type),
  1706. 8*cast(unsigned)type_align_of(type),
  1707. lb_debug_type(m, type->EnumeratedArray.elem),
  1708. subscripts, gb_count_of(subscripts));
  1709. gbString name = type_to_string(type, temporary_allocator());
  1710. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1711. }
  1712. case Type_Struct:
  1713. case Type_Union:
  1714. case Type_Slice:
  1715. case Type_DynamicArray:
  1716. case Type_Map:
  1717. case Type_BitSet:
  1718. {
  1719. unsigned tag = DW_TAG_structure_type;
  1720. if (is_type_raw_union(type) || is_type_union(type)) {
  1721. tag = DW_TAG_union_type;
  1722. }
  1723. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1724. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1725. LLVMDIFlags flags = LLVMDIFlagZero;
  1726. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1727. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1728. );
  1729. lbIncompleteDebugType idt = {};
  1730. idt.type = type;
  1731. idt.metadata = temp_forward_decl;
  1732. array_add(&m->debug_incomplete_types, idt);
  1733. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1734. return temp_forward_decl;
  1735. }
  1736. case Type_Enum:
  1737. {
  1738. LLVMMetadataRef scope = nullptr;
  1739. LLVMMetadataRef file = nullptr;
  1740. unsigned line = 0;
  1741. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1742. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1743. Type *bt = base_enum_type(type);
  1744. LLVMBool is_unsigned = is_type_unsigned(bt);
  1745. for (unsigned i = 0; i < element_count; i++) {
  1746. Entity *f = type->Enum.fields[i];
  1747. GB_ASSERT(f->kind == Entity_Constant);
  1748. String name = f->token.string;
  1749. i64 value = exact_value_to_i64(f->Constant.value);
  1750. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1751. }
  1752. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1753. 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);
  1754. }
  1755. case Type_Tuple:
  1756. if (type->Tuple.variables.count == 1) {
  1757. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1758. } else {
  1759. type_set_offsets(type);
  1760. LLVMMetadataRef parent_scope = nullptr;
  1761. LLVMMetadataRef scope = nullptr;
  1762. LLVMMetadataRef file = nullptr;
  1763. unsigned line = 0;
  1764. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1765. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1766. LLVMDIFlags flags = LLVMDIFlagZero;
  1767. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1768. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1769. for (unsigned i = 0; i < element_count; i++) {
  1770. Entity *f = type->Tuple.variables[i];
  1771. GB_ASSERT(f->kind == Entity_Variable);
  1772. String name = f->token.string;
  1773. unsigned field_line = 0;
  1774. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1775. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1776. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1777. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1778. field_flags, lb_debug_type(m, f->type)
  1779. );
  1780. }
  1781. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1782. size_in_bits, align_in_bits, flags,
  1783. nullptr, elements, element_count, 0, nullptr,
  1784. "", 0
  1785. );
  1786. }
  1787. case Type_Proc:
  1788. {
  1789. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1790. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1791. gbString name = type_to_string(type, temporary_allocator());
  1792. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1793. }
  1794. break;
  1795. case Type_SimdVector:
  1796. 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);
  1797. case Type_RelativePointer: {
  1798. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1799. gbString name = type_to_string(type, temporary_allocator());
  1800. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1801. }
  1802. case Type_RelativeSlice:
  1803. {
  1804. unsigned element_count = 0;
  1805. LLVMMetadataRef elements[2] = {};
  1806. Type *base_integer = type->RelativeSlice.base_integer;
  1807. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1808. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1809. gbString name = type_to_string(type, temporary_allocator());
  1810. 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);
  1811. }
  1812. }
  1813. GB_PANIC("Invalid type %s", type_to_string(type));
  1814. return nullptr;
  1815. }
  1816. LLVMMetadataRef lb_get_base_scope_metadata(lbModule *m, Scope *scope) {
  1817. LLVMMetadataRef found = nullptr;
  1818. for (;;) {
  1819. if (scope == nullptr) {
  1820. return nullptr;
  1821. }
  1822. if (scope->flags & ScopeFlag_Proc) {
  1823. found = lb_get_llvm_metadata(m, scope->procedure_entity);
  1824. if (found) {
  1825. return found;
  1826. }
  1827. }
  1828. if (scope->flags & ScopeFlag_File) {
  1829. found = lb_get_llvm_metadata(m, scope->file);
  1830. if (found) {
  1831. return found;
  1832. }
  1833. }
  1834. scope = scope->parent;
  1835. }
  1836. }
  1837. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1838. GB_ASSERT(type != nullptr);
  1839. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1840. if (found != nullptr) {
  1841. return found;
  1842. }
  1843. if (type->kind == Type_Named) {
  1844. LLVMMetadataRef file = nullptr;
  1845. unsigned line = 0;
  1846. LLVMMetadataRef scope = nullptr;
  1847. if (type->Named.type_name != nullptr) {
  1848. Entity *e = type->Named.type_name;
  1849. scope = lb_get_base_scope_metadata(m, e->scope);
  1850. if (scope != nullptr) {
  1851. file = LLVMDIScopeGetFile(scope);
  1852. }
  1853. line = cast(unsigned)e->token.pos.line;
  1854. }
  1855. // TODO(bill): location data for Type_Named
  1856. u64 size_in_bits = 8*type_size_of(type);
  1857. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1858. String name = type->Named.name;
  1859. char const *name_text = cast(char const *)name.text;
  1860. size_t name_len = cast(size_t)name.len;
  1861. unsigned tag = DW_TAG_structure_type;
  1862. if (is_type_raw_union(type) || is_type_union(type)) {
  1863. tag = DW_TAG_union_type;
  1864. }
  1865. LLVMDIFlags flags = LLVMDIFlagZero;
  1866. Type *bt = base_type(type->Named.base);
  1867. lbIncompleteDebugType idt = {};
  1868. idt.type = type;
  1869. switch (bt->kind) {
  1870. case Type_Enum:
  1871. {
  1872. unsigned line = 0;
  1873. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1874. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1875. Type *ct = base_enum_type(type);
  1876. LLVMBool is_unsigned = is_type_unsigned(ct);
  1877. for (unsigned i = 0; i < element_count; i++) {
  1878. Entity *f = bt->Enum.fields[i];
  1879. GB_ASSERT(f->kind == Entity_Constant);
  1880. String name = f->token.string;
  1881. i64 value = exact_value_to_i64(f->Constant.value);
  1882. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1883. }
  1884. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1885. 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);
  1886. }
  1887. case Type_Basic:
  1888. case Type_Pointer:
  1889. case Type_Array:
  1890. case Type_EnumeratedArray:
  1891. case Type_Tuple:
  1892. case Type_Proc:
  1893. case Type_SimdVector:
  1894. case Type_RelativePointer:
  1895. case Type_RelativeSlice:
  1896. {
  1897. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1898. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1899. lb_set_llvm_metadata(m, type, final_decl);
  1900. return final_decl;
  1901. }
  1902. case Type_Slice:
  1903. case Type_DynamicArray:
  1904. case Type_Map:
  1905. case Type_Struct:
  1906. case Type_Union:
  1907. case Type_BitSet:
  1908. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1909. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1910. );
  1911. idt.metadata = temp_forward_decl;
  1912. array_add(&m->debug_incomplete_types, idt);
  1913. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1914. return temp_forward_decl;
  1915. }
  1916. }
  1917. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1918. lb_set_llvm_metadata(m, type, dt);
  1919. return dt;
  1920. }
  1921. void lb_debug_complete_types(lbModule *m) {
  1922. unsigned const word_size = cast(unsigned)build_context.word_size;
  1923. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1924. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1925. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1926. GB_ASSERT(idt.type != nullptr);
  1927. GB_ASSERT(idt.metadata != nullptr);
  1928. Type *t = idt.type;
  1929. Type *bt = base_type(t);
  1930. LLVMMetadataRef parent_scope = nullptr;
  1931. LLVMMetadataRef file = nullptr;
  1932. unsigned line_number = 0;
  1933. u64 size_in_bits = 8*type_size_of(t);
  1934. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1935. LLVMDIFlags flags = LLVMDIFlagZero;
  1936. LLVMMetadataRef derived_from = nullptr;
  1937. LLVMMetadataRef *elements = nullptr;
  1938. unsigned element_count = 0;
  1939. unsigned runtime_lang = 0; // Objective-C runtime version
  1940. char const *unique_id = "";
  1941. LLVMMetadataRef vtable_holder = nullptr;
  1942. size_t unique_id_len = 0;
  1943. LLVMMetadataRef record_scope = nullptr;
  1944. switch (bt->kind) {
  1945. case Type_Slice:
  1946. case Type_DynamicArray:
  1947. case Type_Map:
  1948. case Type_Struct:
  1949. case Type_Union:
  1950. case Type_BitSet: {
  1951. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1952. String name = str_lit("<anonymous-struct>");
  1953. if (t->kind == Type_Named) {
  1954. name = t->Named.name;
  1955. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1956. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1957. }
  1958. LLVMMetadataRef file = nullptr;
  1959. unsigned line = 0;
  1960. LLVMMetadataRef file_scope = nullptr;
  1961. if (t->Named.type_name != nullptr) {
  1962. Entity *e = t->Named.type_name;
  1963. file_scope = lb_get_llvm_metadata(m, e->scope);
  1964. if (file_scope != nullptr) {
  1965. file = LLVMDIScopeGetFile(file_scope);
  1966. }
  1967. line = cast(unsigned)e->token.pos.line;
  1968. }
  1969. // TODO(bill): location data for Type_Named
  1970. } else {
  1971. name = make_string_c(type_to_string(t, temporary_allocator()));
  1972. }
  1973. switch (bt->kind) {
  1974. case Type_Slice:
  1975. element_count = 2;
  1976. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1977. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1978. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1979. break;
  1980. case Type_DynamicArray:
  1981. element_count = 4;
  1982. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1983. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1984. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1985. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1986. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1987. break;
  1988. case Type_Map:
  1989. bt = bt->Map.internal_type;
  1990. /*fallthrough*/
  1991. case Type_Struct:
  1992. if (file == nullptr) {
  1993. if (bt->Struct.node) {
  1994. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1995. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1996. }
  1997. }
  1998. type_set_offsets(bt);
  1999. {
  2000. isize element_offset = 0;
  2001. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  2002. switch (bt->Struct.soa_kind) {
  2003. case StructSoa_Slice: element_offset = 1; break;
  2004. case StructSoa_Dynamic: element_offset = 3; break;
  2005. }
  2006. element_count = cast(unsigned)(bt->Struct.fields.count + element_offset);
  2007. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2008. switch (bt->Struct.soa_kind) {
  2009. case StructSoa_Slice:
  2010. elements[0] = LLVMDIBuilderCreateMemberType(
  2011. m->debug_builder, record_scope,
  2012. ".len", 4,
  2013. file, 0,
  2014. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  2015. 8*type_size_of(bt)-word_bits,
  2016. LLVMDIFlagZero, lb_debug_type(m, t_int)
  2017. );
  2018. break;
  2019. case StructSoa_Dynamic:
  2020. elements[0] = LLVMDIBuilderCreateMemberType(
  2021. m->debug_builder, record_scope,
  2022. ".len", 4,
  2023. file, 0,
  2024. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  2025. 8*type_size_of(bt)-word_bits + 0*word_bits,
  2026. LLVMDIFlagZero, lb_debug_type(m, t_int)
  2027. );
  2028. elements[1] = LLVMDIBuilderCreateMemberType(
  2029. m->debug_builder, record_scope,
  2030. ".cap", 4,
  2031. file, 0,
  2032. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  2033. 8*type_size_of(bt)-word_bits + 1*word_bits,
  2034. LLVMDIFlagZero, lb_debug_type(m, t_int)
  2035. );
  2036. elements[2] = LLVMDIBuilderCreateMemberType(
  2037. m->debug_builder, record_scope,
  2038. ".allocator", 12,
  2039. file, 0,
  2040. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  2041. 8*type_size_of(bt)-word_bits + 2*word_bits,
  2042. LLVMDIFlagZero, lb_debug_type(m, t_allocator)
  2043. );
  2044. break;
  2045. }
  2046. for_array(j, bt->Struct.fields) {
  2047. Entity *f = bt->Struct.fields[j];
  2048. String fname = f->token.string;
  2049. unsigned field_line = 0;
  2050. LLVMDIFlags field_flags = LLVMDIFlagZero;
  2051. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  2052. elements[element_offset+j] = LLVMDIBuilderCreateMemberType(
  2053. m->debug_builder, record_scope,
  2054. cast(char const *)fname.text, cast(size_t)fname.len,
  2055. file, field_line,
  2056. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  2057. offset_in_bits,
  2058. field_flags, lb_debug_type(m, f->type)
  2059. );
  2060. }
  2061. }
  2062. break;
  2063. case Type_Union:
  2064. {
  2065. if (file == nullptr) {
  2066. GB_ASSERT(bt->Union.node != nullptr);
  2067. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  2068. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  2069. }
  2070. isize index_offset = 1;
  2071. if (is_type_union_maybe_pointer(bt)) {
  2072. index_offset = 0;
  2073. }
  2074. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  2075. element_count = cast(unsigned)bt->Union.variants.count;
  2076. if (index_offset > 0) {
  2077. element_count += 1;
  2078. }
  2079. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2080. if (index_offset > 0) {
  2081. Type *tag_type = union_tag_type(bt);
  2082. unsigned field_line = 0;
  2083. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  2084. LLVMDIFlags field_flags = LLVMDIFlagZero;
  2085. elements[0] = LLVMDIBuilderCreateMemberType(
  2086. m->debug_builder, record_scope,
  2087. "tag", 3,
  2088. file, field_line,
  2089. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  2090. offset_in_bits,
  2091. field_flags, lb_debug_type(m, tag_type)
  2092. );
  2093. }
  2094. for_array(j, bt->Union.variants) {
  2095. Type *variant = bt->Union.variants[j];
  2096. unsigned field_index = cast(unsigned)(index_offset+j);
  2097. char name[16] = {};
  2098. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  2099. isize name_len = gb_strlen(name);
  2100. unsigned field_line = 0;
  2101. LLVMDIFlags field_flags = LLVMDIFlagZero;
  2102. u64 offset_in_bits = 0;
  2103. elements[field_index] = LLVMDIBuilderCreateMemberType(
  2104. m->debug_builder, record_scope,
  2105. name, name_len,
  2106. file, field_line,
  2107. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  2108. offset_in_bits,
  2109. field_flags, lb_debug_type(m, variant)
  2110. );
  2111. }
  2112. }
  2113. break;
  2114. case Type_BitSet:
  2115. {
  2116. if (file == nullptr) {
  2117. GB_ASSERT(bt->BitSet.node != nullptr);
  2118. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  2119. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  2120. }
  2121. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  2122. LLVMMetadataRef scope = file;
  2123. Type *elem = base_type(bt->BitSet.elem);
  2124. if (elem->kind == Type_Enum) {
  2125. element_count = cast(unsigned)elem->Enum.fields.count;
  2126. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2127. for_array(i, elem->Enum.fields) {
  2128. Entity *f = elem->Enum.fields[i];
  2129. GB_ASSERT(f->kind == Entity_Constant);
  2130. i64 val = exact_value_to_i64(f->Constant.value);
  2131. String name = f->token.string;
  2132. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  2133. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  2134. m->debug_builder,
  2135. scope,
  2136. cast(char const *)name.text, name.len,
  2137. file, line_number,
  2138. 1,
  2139. offset_in_bits,
  2140. 0,
  2141. LLVMDIFlagZero,
  2142. bit_set_field_type
  2143. );
  2144. }
  2145. } else {
  2146. char name[32] = {};
  2147. GB_ASSERT(is_type_integer(elem));
  2148. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  2149. GB_ASSERT(0 <= count);
  2150. element_count = cast(unsigned)count;
  2151. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  2152. for (unsigned i = 0; i < element_count; i++) {
  2153. u64 offset_in_bits = i;
  2154. i64 val = bt->BitSet.lower + cast(i64)i;
  2155. gb_snprintf(name, gb_count_of(name), "%lld", cast(long long)val);
  2156. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  2157. m->debug_builder,
  2158. scope,
  2159. name, gb_strlen(name),
  2160. file, line_number,
  2161. 1,
  2162. offset_in_bits,
  2163. 0,
  2164. LLVMDIFlagZero,
  2165. bit_set_field_type
  2166. );
  2167. }
  2168. }
  2169. }
  2170. }
  2171. LLVMMetadataRef final_metadata = nullptr;
  2172. if (is_union) {
  2173. final_metadata = LLVMDIBuilderCreateUnionType(
  2174. m->debug_builder,
  2175. parent_scope,
  2176. cast(char const *)name.text, cast(size_t)name.len,
  2177. file, line_number,
  2178. size_in_bits, align_in_bits,
  2179. flags,
  2180. elements, element_count,
  2181. runtime_lang,
  2182. unique_id, unique_id_len
  2183. );
  2184. } else {
  2185. final_metadata = LLVMDIBuilderCreateStructType(
  2186. m->debug_builder,
  2187. parent_scope,
  2188. cast(char const *)name.text, cast(size_t)name.len,
  2189. file, line_number,
  2190. size_in_bits, align_in_bits,
  2191. flags,
  2192. derived_from,
  2193. elements, element_count,
  2194. runtime_lang,
  2195. vtable_holder,
  2196. unique_id, unique_id_len
  2197. );
  2198. }
  2199. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  2200. lb_set_llvm_metadata(m, idt.type, final_metadata);
  2201. } break;
  2202. default:
  2203. GB_PANIC("invalid incomplete debug type");
  2204. break;
  2205. }
  2206. }
  2207. array_clear(&m->debug_incomplete_types);
  2208. }
  2209. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  2210. if (e != nullptr) {
  2211. map_set(&m->values, hash_entity(e), val);
  2212. }
  2213. }
  2214. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  2215. if (name.len > 0) {
  2216. string_map_set(&m->members, name, val);
  2217. }
  2218. }
  2219. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  2220. string_map_set(&m->members, key, val);
  2221. }
  2222. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  2223. if (p->entity != nullptr) {
  2224. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  2225. }
  2226. string_map_set(&m->procedures, p->name, p);
  2227. }
  2228. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  2229. LLVMTypeRef src = LLVMTypeOf(val);
  2230. if (src == dst) {
  2231. return val;
  2232. }
  2233. if (LLVMIsNull(val)) {
  2234. return LLVMConstNull(dst);
  2235. }
  2236. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  2237. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  2238. switch (kind) {
  2239. case LLVMPointerTypeKind:
  2240. return LLVMConstPointerCast(val, dst);
  2241. case LLVMStructTypeKind:
  2242. return LLVMConstBitCast(val, dst);
  2243. default:
  2244. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  2245. }
  2246. return val;
  2247. }
  2248. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  2249. unsigned value_count = cast(unsigned)value_count_;
  2250. unsigned elem_count = LLVMCountStructElementTypes(t);
  2251. GB_ASSERT(value_count == elem_count);
  2252. for (unsigned i = 0; i < elem_count; i++) {
  2253. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  2254. values[i] = llvm_const_cast(values[i], elem_type);
  2255. }
  2256. return LLVMConstNamedStruct(t, values, value_count);
  2257. }
  2258. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  2259. unsigned value_count = cast(unsigned)value_count_;
  2260. for (unsigned i = 0; i < value_count; i++) {
  2261. values[i] = llvm_const_cast(values[i], elem_type);
  2262. }
  2263. return LLVMConstArray(elem_type, values, value_count);
  2264. }
  2265. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  2266. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  2267. LLVMValueRef values[2] = {
  2268. str_elem.value,
  2269. str_len.value,
  2270. };
  2271. lbValue res = {};
  2272. res.type = t_string;
  2273. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  2274. return res;
  2275. } else {
  2276. lbAddr res = lb_add_local_generated(p, t_string, false);
  2277. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  2278. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  2279. return lb_addr_load(p, res);
  2280. }
  2281. }
  2282. LLVMAttributeRef lb_create_enum_attribute_with_type(LLVMContextRef ctx, char const *name, LLVMTypeRef type) {
  2283. String s = make_string_c(name);
  2284. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2285. // and the current LLVM C API does not expose this functionality yet.
  2286. // It is better to ignore the attributes for the time being
  2287. if (s == "byval") {
  2288. // return nullptr;
  2289. } else if (s == "byref") {
  2290. return nullptr;
  2291. } else if (s == "preallocated") {
  2292. return nullptr;
  2293. } else if (s == "sret") {
  2294. // return nullptr;
  2295. }
  2296. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2297. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2298. return LLVMCreateEnumAttribute(ctx, kind, 0);
  2299. }
  2300. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2301. String s = make_string_c(name);
  2302. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2303. // and the current LLVM C API does not expose this functionality yet.
  2304. // It is better to ignore the attributes for the time being
  2305. if (s == "byval") {
  2306. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2307. } else if (s == "byref") {
  2308. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2309. } else if (s == "preallocated") {
  2310. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2311. } else if (s == "sret") {
  2312. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  2313. }
  2314. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2315. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2316. return LLVMCreateEnumAttribute(ctx, kind, value);
  2317. }
  2318. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2319. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2320. GB_ASSERT(attr != nullptr);
  2321. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2322. }
  2323. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2324. lb_add_proc_attribute_at_index(p, index, name, 0);
  2325. }
  2326. void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  2327. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  2328. }
  2329. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2330. if (p->abi_function_type != nullptr) {
  2331. return;
  2332. }
  2333. auto hash = hash_type(p->type);
  2334. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2335. if (ft_found == nullptr) {
  2336. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2337. ft_found = map_get(&m->function_type_map, hash);
  2338. }
  2339. GB_ASSERT(ft_found != nullptr);
  2340. p->abi_function_type = *ft_found;
  2341. GB_ASSERT(p->abi_function_type != nullptr);
  2342. }
  2343. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  2344. GB_ASSERT(entity != nullptr);
  2345. GB_ASSERT(entity->kind == Entity_Procedure);
  2346. String link_name = {};
  2347. if (ignore_body) {
  2348. lbModule *other_module = lb_pkg_module(m->gen, entity->pkg);
  2349. link_name = lb_get_entity_name(other_module, entity);
  2350. } else {
  2351. link_name = lb_get_entity_name(m, entity);
  2352. }
  2353. {
  2354. StringHashKey key = string_hash_string(link_name);
  2355. lbValue *found = string_map_get(&m->members, key);
  2356. if (found) {
  2357. lb_add_entity(m, entity, *found);
  2358. lbProcedure **p_found = string_map_get(&m->procedures, key);
  2359. GB_ASSERT(p_found != nullptr);
  2360. return *p_found;
  2361. }
  2362. }
  2363. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2364. p->module = m;
  2365. entity->code_gen_module = m;
  2366. entity->code_gen_procedure = p;
  2367. p->entity = entity;
  2368. p->name = link_name;
  2369. DeclInfo *decl = entity->decl_info;
  2370. ast_node(pl, ProcLit, decl->proc_lit);
  2371. Type *pt = base_type(entity->type);
  2372. GB_ASSERT(pt->kind == Type_Proc);
  2373. p->type = entity->type;
  2374. p->type_expr = decl->type_expr;
  2375. p->body = pl->body;
  2376. p->inlining = pl->inlining;
  2377. p->is_foreign = entity->Procedure.is_foreign;
  2378. p->is_export = entity->Procedure.is_export;
  2379. p->is_entry_point = false;
  2380. gbAllocator a = heap_allocator();
  2381. p->children.allocator = a;
  2382. p->params.allocator = a;
  2383. p->defer_stmts.allocator = a;
  2384. p->blocks.allocator = a;
  2385. p->branch_blocks.allocator = a;
  2386. p->context_stack.allocator = a;
  2387. p->scope_stack.allocator = a;
  2388. if (p->is_foreign) {
  2389. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2390. }
  2391. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2392. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2393. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2394. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2395. lb_ensure_abi_function_type(m, p);
  2396. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2397. if (false) {
  2398. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2399. // TODO(bill): Clean up this logic
  2400. if (!is_arch_wasm()) {
  2401. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2402. }
  2403. LLVMSetFunctionCallConv(p->value, cc_kind);
  2404. }
  2405. if (pt->Proc.diverging) {
  2406. lb_add_attribute_to_proc(m, p->value, "noreturn");
  2407. }
  2408. if (pt->Proc.calling_convention == ProcCC_Naked) {
  2409. lb_add_attribute_to_proc(m, p->value, "naked");
  2410. }
  2411. switch (p->inlining) {
  2412. case ProcInlining_inline:
  2413. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  2414. break;
  2415. case ProcInlining_no_inline:
  2416. lb_add_attribute_to_proc(m, p->value, "noinline");
  2417. break;
  2418. }
  2419. if (entity->flags & EntityFlag_Cold) {
  2420. lb_add_attribute_to_proc(m, p->value, "cold");
  2421. }
  2422. switch (entity->Procedure.optimization_mode) {
  2423. case ProcedureOptimizationMode_None:
  2424. lb_add_attribute_to_proc(m, p->value, "optnone");
  2425. break;
  2426. case ProcedureOptimizationMode_Minimal:
  2427. lb_add_attribute_to_proc(m, p->value, "optnone");
  2428. break;
  2429. case ProcedureOptimizationMode_Size:
  2430. lb_add_attribute_to_proc(m, p->value, "optsize");
  2431. break;
  2432. case ProcedureOptimizationMode_Speed:
  2433. // TODO(bill): handle this correctly
  2434. lb_add_attribute_to_proc(m, p->value, "optsize");
  2435. break;
  2436. }
  2437. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2438. // // TODO(bill): Clean up this logic
  2439. // if (build_context.metrics.os != TargetOs_js) {
  2440. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2441. // }
  2442. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2443. lbValue proc_value = {p->value, p->type};
  2444. lb_add_entity(m, entity, proc_value);
  2445. lb_add_member(m, p->name, proc_value);
  2446. lb_add_procedure_value(m, p);
  2447. if (p->is_export) {
  2448. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2449. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2450. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2451. if (is_arch_wasm()) {
  2452. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2453. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2454. }
  2455. } else if (!p->is_foreign) {
  2456. if (!USE_SEPARTE_MODULES) {
  2457. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  2458. // NOTE(bill): if a procedure is defined in package runtime and uses a custom link name,
  2459. // then it is very likely it is required by LLVM and thus cannot have internal linkage
  2460. if (entity->pkg != nullptr && entity->pkg->kind == Package_Runtime && p->body != nullptr) {
  2461. GB_ASSERT(entity->kind == Entity_Procedure);
  2462. if (entity->Procedure.link_name != "") {
  2463. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  2464. }
  2465. }
  2466. }
  2467. }
  2468. if (p->is_foreign) {
  2469. if (is_arch_wasm()) {
  2470. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2471. char const *module_name = "env";
  2472. if (entity->Procedure.foreign_library != nullptr) {
  2473. Entity *foreign_library = entity->Procedure.foreign_library;
  2474. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2475. if (foreign_library->LibraryName.paths.count > 0) {
  2476. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2477. }
  2478. }
  2479. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2480. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2481. }
  2482. }
  2483. // NOTE(bill): offset==0 is the return value
  2484. isize offset = 1;
  2485. if (pt->Proc.return_by_pointer) {
  2486. offset = 2;
  2487. }
  2488. isize parameter_index = 0;
  2489. if (pt->Proc.param_count) {
  2490. TypeTuple *params = &pt->Proc.params->Tuple;
  2491. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2492. Entity *e = params->variables[i];
  2493. Type *original_type = e->type;
  2494. if (e->kind != Entity_Variable) continue;
  2495. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2496. continue;
  2497. }
  2498. if (e->flags&EntityFlag_NoAlias) {
  2499. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2500. }
  2501. parameter_index += 1;
  2502. }
  2503. }
  2504. if (ignore_body) {
  2505. p->body = nullptr;
  2506. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  2507. }
  2508. if (m->debug_builder) { // Debug Information
  2509. Type *bt = base_type(p->type);
  2510. unsigned line = cast(unsigned)entity->token.pos.line;
  2511. LLVMMetadataRef scope = nullptr;
  2512. LLVMMetadataRef file = nullptr;
  2513. LLVMMetadataRef type = nullptr;
  2514. scope = p->module->debug_compile_unit;
  2515. type = lb_debug_type_internal_proc(m, bt);
  2516. if (entity->file != nullptr) {
  2517. file = lb_get_llvm_metadata(m, entity->file);
  2518. scope = file;
  2519. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2520. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2521. scope = file;
  2522. } else if (entity->scope != nullptr) {
  2523. file = lb_get_llvm_metadata(m, entity->scope->file);
  2524. scope = file;
  2525. }
  2526. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2527. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2528. LLVMBool is_local_to_unit = false;
  2529. LLVMBool is_definition = p->body != nullptr;
  2530. unsigned scope_line = line;
  2531. u32 flags = LLVMDIFlagStaticMember;
  2532. LLVMBool is_optimized = false;
  2533. if (bt->Proc.diverging) {
  2534. flags |= LLVMDIFlagNoReturn;
  2535. }
  2536. if (p->body == nullptr) {
  2537. flags |= LLVMDIFlagPrototyped;
  2538. is_optimized = false;
  2539. }
  2540. if (p->body != nullptr) {
  2541. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2542. cast(char const *)entity->token.string.text, entity->token.string.len,
  2543. cast(char const *)p->name.text, p->name.len,
  2544. file, line, type,
  2545. is_local_to_unit, is_definition,
  2546. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2547. );
  2548. GB_ASSERT(p->debug_info != nullptr);
  2549. LLVMSetSubprogram(p->value, p->debug_info);
  2550. lb_set_llvm_metadata(m, p, p->debug_info);
  2551. }
  2552. }
  2553. return p;
  2554. }
  2555. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2556. {
  2557. lbValue *found = string_map_get(&m->members, link_name);
  2558. GB_ASSERT(found == nullptr);
  2559. }
  2560. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2561. p->module = m;
  2562. p->name = link_name;
  2563. p->type = type;
  2564. p->type_expr = nullptr;
  2565. p->body = nullptr;
  2566. p->tags = 0;
  2567. p->inlining = ProcInlining_none;
  2568. p->is_foreign = false;
  2569. p->is_export = false;
  2570. p->is_entry_point = false;
  2571. gbAllocator a = permanent_allocator();
  2572. p->children.allocator = a;
  2573. p->params.allocator = a;
  2574. p->defer_stmts.allocator = a;
  2575. p->blocks.allocator = a;
  2576. p->branch_blocks.allocator = a;
  2577. p->context_stack.allocator = a;
  2578. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2579. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2580. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2581. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2582. Type *pt = p->type;
  2583. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2584. // TODO(bill): Clean up this logic
  2585. if (!is_arch_wasm()) {
  2586. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2587. }
  2588. LLVMSetFunctionCallConv(p->value, cc_kind);
  2589. lbValue proc_value = {p->value, p->type};
  2590. lb_add_member(m, p->name, proc_value);
  2591. lb_add_procedure_value(m, p);
  2592. // NOTE(bill): offset==0 is the return value
  2593. isize offset = 1;
  2594. if (pt->Proc.return_by_pointer) {
  2595. lb_add_proc_attribute_at_index(p, 1, "sret");
  2596. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2597. offset = 2;
  2598. }
  2599. isize parameter_index = 0;
  2600. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2601. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2602. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2603. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2604. }
  2605. return p;
  2606. }
  2607. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2608. lbParamPasskind kind = lbParamPass_Value;
  2609. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2610. if (is_type_pointer(abi_type)) {
  2611. GB_ASSERT(e->kind == Entity_Variable);
  2612. Type *av = core_type(type_deref(abi_type));
  2613. if (are_types_identical(av, core_type(e->type))) {
  2614. kind = lbParamPass_Pointer;
  2615. if (e->flags&EntityFlag_Value) {
  2616. kind = lbParamPass_ConstRef;
  2617. }
  2618. } else {
  2619. kind = lbParamPass_BitCast;
  2620. }
  2621. } else if (is_type_integer(abi_type)) {
  2622. kind = lbParamPass_Integer;
  2623. } else if (abi_type == t_llvm_bool) {
  2624. kind = lbParamPass_Value;
  2625. } else if (is_type_boolean(abi_type)) {
  2626. kind = lbParamPass_Integer;
  2627. } else if (is_type_simd_vector(abi_type)) {
  2628. kind = lbParamPass_BitCast;
  2629. } else if (is_type_float(abi_type)) {
  2630. kind = lbParamPass_BitCast;
  2631. } else if (is_type_tuple(abi_type)) {
  2632. kind = lbParamPass_Tuple;
  2633. } else if (is_type_proc(abi_type)) {
  2634. kind = lbParamPass_Value;
  2635. } else {
  2636. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2637. }
  2638. }
  2639. if (kind_) *kind_ = kind;
  2640. lbValue res = {};
  2641. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2642. res.type = abi_type;
  2643. return res;
  2644. }
  2645. Type *struct_type_from_systemv_distribute_struct_fields(Type *abi_type) {
  2646. GB_ASSERT(is_type_tuple(abi_type));
  2647. Type *final_type = alloc_type_struct();
  2648. final_type->Struct.fields = abi_type->Tuple.variables;
  2649. return final_type;
  2650. }
  2651. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2652. GB_ASSERT(b != nullptr);
  2653. if (!b->appended) {
  2654. b->appended = true;
  2655. LLVMAppendExistingBasicBlock(p->value, b->block);
  2656. }
  2657. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2658. p->curr_block = b;
  2659. }
  2660. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2661. LLVMContextRef ctx = p->module->ctx;
  2662. LLVMTypeRef src_type = LLVMTypeOf(val);
  2663. if (src_type == dst_type) {
  2664. return val;
  2665. }
  2666. i64 src_size = lb_sizeof(src_type);
  2667. i64 dst_size = lb_sizeof(dst_type);
  2668. i64 src_align = lb_alignof(src_type);
  2669. i64 dst_align = lb_alignof(dst_type);
  2670. if (LLVMIsALoadInst(val)) {
  2671. src_align = gb_min(src_align, LLVMGetAlignment(val));
  2672. }
  2673. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2674. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2675. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2676. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2677. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2678. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2679. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2680. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2681. }
  2682. if (src_size != dst_size) {
  2683. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2684. // Okay
  2685. } else {
  2686. goto general_end;
  2687. }
  2688. }
  2689. if (src_kind == dst_kind) {
  2690. if (src_kind == LLVMPointerTypeKind) {
  2691. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2692. } else if (src_kind == LLVMArrayTypeKind) {
  2693. // ignore
  2694. } else if (src_kind != LLVMStructTypeKind) {
  2695. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2696. }
  2697. } else {
  2698. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2699. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2700. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2701. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2702. }
  2703. }
  2704. general_end:;
  2705. // make the alignment big if necessary
  2706. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  2707. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2708. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  2709. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  2710. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  2711. }
  2712. }
  2713. src_size = align_formula(src_size, src_align);
  2714. dst_size = align_formula(dst_size, dst_align);
  2715. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  2716. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2717. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2718. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  2719. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2720. return loaded_val;
  2721. } else {
  2722. GB_ASSERT(p->decl_block != p->curr_block);
  2723. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2724. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2725. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2726. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2727. max_align = gb_max(max_align, 4);
  2728. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2729. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2730. LLVMBuildStore(p->builder, val, nptr);
  2731. return LLVMBuildLoad(p->builder, ptr, "");
  2732. }
  2733. }
  2734. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2735. if (p->debug_info == nullptr) {
  2736. return;
  2737. }
  2738. if (type == nullptr) {
  2739. return;
  2740. }
  2741. if (type == t_invalid) {
  2742. return;
  2743. }
  2744. if (p->body == nullptr) {
  2745. return;
  2746. }
  2747. lbModule *m = p->module;
  2748. String const &name = token.string;
  2749. if (name == "" || name == "_") {
  2750. return;
  2751. }
  2752. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2753. // Already been set
  2754. return;
  2755. }
  2756. AstFile *file = p->body->file;
  2757. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2758. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2759. GB_ASSERT(llvm_scope != nullptr);
  2760. if (llvm_file == nullptr) {
  2761. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2762. }
  2763. if (llvm_file == nullptr) {
  2764. return;
  2765. }
  2766. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2767. LLVMDIFlags flags = LLVMDIFlagZero;
  2768. LLVMBool always_preserve = build_context.optimization_level == 0;
  2769. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2770. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2771. m->debug_builder, llvm_scope,
  2772. cast(char const *)name.text, cast(size_t)name.len,
  2773. llvm_file, token.pos.line,
  2774. debug_type,
  2775. always_preserve, flags, alignment_in_bits
  2776. );
  2777. LLVMValueRef storage = ptr;
  2778. LLVMValueRef instr = ptr;
  2779. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2780. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2781. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2782. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2783. }
  2784. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2785. if (!p->debug_info || !p->body) {
  2786. return;
  2787. }
  2788. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2789. if (!loc) {
  2790. return;
  2791. }
  2792. TokenPos pos = {};
  2793. pos.file_id = p->body->file ? p->body->file->id : 0;
  2794. pos.line = LLVMDILocationGetLine(loc);
  2795. pos.column = LLVMDILocationGetColumn(loc);
  2796. Token token = {};
  2797. token.kind = Token_context;
  2798. token.string = str_lit("context");
  2799. token.pos = pos;
  2800. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2801. }
  2802. void lb_begin_procedure_body(lbProcedure *p) {
  2803. DeclInfo *decl = decl_info_of_entity(p->entity);
  2804. if (decl != nullptr) {
  2805. for_array(i, decl->labels) {
  2806. BlockLabel bl = decl->labels[i];
  2807. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2808. array_add(&p->branch_blocks, bb);
  2809. }
  2810. }
  2811. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  2812. p->decl_block = lb_create_block(p, "decls", true);
  2813. p->entry_block = lb_create_block(p, "entry", true);
  2814. lb_start_block(p, p->entry_block);
  2815. GB_ASSERT(p->type != nullptr);
  2816. lb_ensure_abi_function_type(p->module, p);
  2817. {
  2818. lbFunctionType *ft = p->abi_function_type;
  2819. unsigned param_offset = 0;
  2820. lbValue return_ptr_value = {};
  2821. if (ft->ret.kind == lbArg_Indirect) {
  2822. // NOTE(bill): this must be parameter 0
  2823. String name = str_lit("agg.result");
  2824. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2825. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  2826. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2827. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2828. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  2829. return_ptr_value.type = ptr_type;
  2830. p->return_ptr = lb_addr(return_ptr_value);
  2831. lb_add_entity(p->module, e, return_ptr_value);
  2832. param_offset += 1;
  2833. }
  2834. if (p->type->Proc.params != nullptr) {
  2835. TypeTuple *params = &p->type->Proc.params->Tuple;
  2836. unsigned param_index = 0;
  2837. for_array(i, params->variables) {
  2838. Entity *e = params->variables[i];
  2839. if (e->kind != Entity_Variable) {
  2840. continue;
  2841. }
  2842. lbArgType *arg_type = &ft->args[param_index];
  2843. if (arg_type->kind == lbArg_Ignore) {
  2844. continue;
  2845. } else if (arg_type->kind == lbArg_Direct) {
  2846. lbParamPasskind kind = lbParamPass_Value;
  2847. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2848. if (param_type != arg_type->type) {
  2849. kind = lbParamPass_BitCast;
  2850. }
  2851. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2852. value = OdinLLVMBuildTransmute(p, value, param_type);
  2853. lbValue param = {};
  2854. param.value = value;
  2855. param.type = e->type;
  2856. array_add(&p->params, param);
  2857. if (e->token.string.len != 0) {
  2858. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2859. lb_addr_store(p, l, param);
  2860. }
  2861. param_index += 1;
  2862. } else if (arg_type->kind == lbArg_Indirect) {
  2863. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2864. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2865. lbValue param = {};
  2866. param.value = value;
  2867. param.type = e->type;
  2868. array_add(&p->params, param);
  2869. lbValue ptr = {};
  2870. ptr.value = value_ptr;
  2871. ptr.type = alloc_type_pointer(e->type);
  2872. lb_add_entity(p->module, e, ptr);
  2873. param_index += 1;
  2874. }
  2875. }
  2876. }
  2877. if (p->type->Proc.has_named_results) {
  2878. GB_ASSERT(p->type->Proc.result_count > 0);
  2879. TypeTuple *results = &p->type->Proc.results->Tuple;
  2880. for_array(i, results->variables) {
  2881. Entity *e = results->variables[i];
  2882. GB_ASSERT(e->kind == Entity_Variable);
  2883. if (e->token.string != "") {
  2884. GB_ASSERT(!is_blank_ident(e->token));
  2885. lbAddr res = {};
  2886. if (return_ptr_value.value) {
  2887. lbValue ptr = return_ptr_value;
  2888. if (results->variables.count != 1) {
  2889. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2890. }
  2891. res = lb_addr(ptr);
  2892. lb_add_entity(p->module, e, ptr);
  2893. } else {
  2894. res = lb_add_local(p, e->type, e);
  2895. }
  2896. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2897. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2898. lb_addr_store(p, res, c);
  2899. }
  2900. }
  2901. }
  2902. }
  2903. }
  2904. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2905. lb_push_context_onto_stack_from_implicit_parameter(p);
  2906. }
  2907. lb_start_block(p, p->entry_block);
  2908. if (p->debug_info != nullptr) {
  2909. TokenPos pos = {};
  2910. if (p->body != nullptr) {
  2911. pos = ast_token(p->body).pos;
  2912. } else if (p->type_expr != nullptr) {
  2913. pos = ast_token(p->type_expr).pos;
  2914. } else if (p->entity != nullptr) {
  2915. pos = p->entity->token.pos;
  2916. }
  2917. if (pos.file_id != 0) {
  2918. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2919. }
  2920. if (p->context_stack.count != 0) {
  2921. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2922. }
  2923. }
  2924. }
  2925. void lb_end_procedure_body(lbProcedure *p) {
  2926. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2927. LLVMBuildBr(p->builder, p->entry_block->block);
  2928. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2929. LLVMValueRef instr = nullptr;
  2930. // Make sure there is a "ret void" at the end of a procedure with no return type
  2931. if (p->type->Proc.result_count == 0) {
  2932. instr = LLVMGetLastInstruction(p->curr_block->block);
  2933. if (!lb_is_instr_terminating(instr)) {
  2934. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2935. LLVMBuildRetVoid(p->builder);
  2936. }
  2937. }
  2938. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2939. LLVMBasicBlockRef block = nullptr;
  2940. // Make sure every block terminates, and if not, make it unreachable
  2941. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2942. instr = LLVMGetLastInstruction(block);
  2943. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  2944. LLVMPositionBuilderAtEnd(p->builder, block);
  2945. LLVMBuildUnreachable(p->builder);
  2946. }
  2947. }
  2948. p->curr_block = nullptr;
  2949. p->state_flags = 0;
  2950. }
  2951. void lb_end_procedure(lbProcedure *p) {
  2952. LLVMDisposeBuilder(p->builder);
  2953. }
  2954. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2955. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2956. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2957. array_add(&from->succs, to);
  2958. array_add(&to->preds, from);
  2959. }
  2960. }
  2961. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2962. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2963. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2964. b->appended = false;
  2965. if (append) {
  2966. b->appended = true;
  2967. LLVMAppendExistingBasicBlock(p->value, b->block);
  2968. }
  2969. b->scope = p->curr_scope;
  2970. b->scope_index = p->scope_index;
  2971. b->preds.allocator = heap_allocator();
  2972. b->succs.allocator = heap_allocator();
  2973. array_add(&p->blocks, b);
  2974. return b;
  2975. }
  2976. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2977. if (p->curr_block == nullptr) {
  2978. return;
  2979. }
  2980. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2981. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2982. return;
  2983. }
  2984. lb_add_edge(p->curr_block, target_block);
  2985. LLVMBuildBr(p->builder, target_block->block);
  2986. p->curr_block = nullptr;
  2987. }
  2988. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2989. lbBlock *b = p->curr_block;
  2990. if (b == nullptr) {
  2991. return;
  2992. }
  2993. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2994. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2995. return;
  2996. }
  2997. lb_add_edge(b, true_block);
  2998. lb_add_edge(b, false_block);
  2999. LLVMValueRef cv = cond.value;
  3000. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  3001. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  3002. }
  3003. bool lb_is_expr_untyped_const(Ast *expr) {
  3004. auto const &tv = type_and_value_of_expr(expr);
  3005. if (is_type_untyped(tv.type)) {
  3006. return tv.value.kind != ExactValue_Invalid;
  3007. }
  3008. return false;
  3009. }
  3010. lbValue lb_expr_untyped_const_to_typed(lbModule *m, Ast *expr, Type *t) {
  3011. GB_ASSERT(is_type_typed(t));
  3012. auto const &tv = type_and_value_of_expr(expr);
  3013. return lb_const_value(m, t, tv.value);
  3014. }
  3015. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  3016. GB_ASSERT(cond != nullptr);
  3017. GB_ASSERT(true_block != nullptr);
  3018. GB_ASSERT(false_block != nullptr);
  3019. switch (cond->kind) {
  3020. case_ast_node(pe, ParenExpr, cond);
  3021. return lb_build_cond(p, pe->expr, true_block, false_block);
  3022. case_end;
  3023. case_ast_node(ue, UnaryExpr, cond);
  3024. if (ue->op.kind == Token_Not) {
  3025. return lb_build_cond(p, ue->expr, false_block, true_block);
  3026. }
  3027. case_end;
  3028. case_ast_node(be, BinaryExpr, cond);
  3029. if (be->op.kind == Token_CmpAnd) {
  3030. lbBlock *block = lb_create_block(p, "cmp.and");
  3031. lb_build_cond(p, be->left, block, false_block);
  3032. lb_start_block(p, block);
  3033. return lb_build_cond(p, be->right, true_block, false_block);
  3034. } else if (be->op.kind == Token_CmpOr) {
  3035. lbBlock *block = lb_create_block(p, "cmp.or");
  3036. lb_build_cond(p, be->left, true_block, block);
  3037. lb_start_block(p, block);
  3038. return lb_build_cond(p, be->right, true_block, false_block);
  3039. }
  3040. case_end;
  3041. }
  3042. lbValue v = {};
  3043. if (lb_is_expr_untyped_const(cond)) {
  3044. v = lb_expr_untyped_const_to_typed(p->module, cond, t_llvm_bool);
  3045. } else {
  3046. v = lb_build_expr(p, cond);
  3047. }
  3048. v = lb_emit_conv(p, v, t_llvm_bool);
  3049. lb_emit_if(p, v, true_block, false_block);
  3050. return v;
  3051. }
  3052. void lb_mem_zero_ptr_internal(lbProcedure *p, LLVMValueRef ptr, LLVMValueRef len, unsigned alignment) {
  3053. bool is_inlinable = false;
  3054. i64 const_len = 0;
  3055. if (LLVMIsConstant(len)) {
  3056. const_len = cast(i64)LLVMConstIntGetSExtValue(len);
  3057. // TODO(bill): Determine when it is better to do the `*.inline` versions
  3058. if (const_len <= 4*build_context.word_size) {
  3059. is_inlinable = true;
  3060. }
  3061. }
  3062. char const *name = "llvm.memset";
  3063. if (is_inlinable) {
  3064. name = "llvm.memset.inline";
  3065. }
  3066. LLVMTypeRef types[2] = {
  3067. lb_type(p->module, t_rawptr),
  3068. lb_type(p->module, t_int)
  3069. };
  3070. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  3071. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]));
  3072. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  3073. LLVMValueRef args[4] = {};
  3074. args[0] = LLVMBuildPointerCast(p->builder, ptr, types[0], "");
  3075. args[1] = LLVMConstInt(LLVMInt8TypeInContext(p->module->ctx), 0, false);
  3076. args[2] = LLVMBuildIntCast2(p->builder, len, types[1], /*signed*/false, "");
  3077. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, false); // is_volatile parameter
  3078. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  3079. }
  3080. void lb_mem_zero_ptr(lbProcedure *p, LLVMValueRef ptr, Type *type, unsigned alignment) {
  3081. LLVMTypeRef llvm_type = lb_type(p->module, type);
  3082. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  3083. switch (kind) {
  3084. case LLVMStructTypeKind:
  3085. case LLVMArrayTypeKind:
  3086. {
  3087. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  3088. i32 sz = cast(i32)type_size_of(type);
  3089. lb_mem_zero_ptr_internal(p, ptr, lb_const_int(p->module, t_int, sz).value, alignment);
  3090. }
  3091. break;
  3092. default:
  3093. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  3094. break;
  3095. }
  3096. }
  3097. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index, bool force_no_init) {
  3098. GB_ASSERT(p->decl_block != p->curr_block);
  3099. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  3100. char const *name = "";
  3101. if (e != nullptr) {
  3102. // name = alloc_cstring(permanent_allocator(), e->token.string);
  3103. }
  3104. LLVMTypeRef llvm_type = lb_type(p->module, type);
  3105. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  3106. // unsigned alignment = 16; // TODO(bill): Make this configurable
  3107. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  3108. LLVMSetAlignment(ptr, alignment);
  3109. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  3110. if (!zero_init && !force_no_init) {
  3111. // If there is any padding of any kind, just zero init regardless of zero_init parameter
  3112. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  3113. if (kind == LLVMStructTypeKind) {
  3114. i64 sz = type_size_of(type);
  3115. if (type_size_of_struct_pretend_is_packed(type) != sz) {
  3116. zero_init = true;
  3117. }
  3118. } else if (kind == LLVMArrayTypeKind) {
  3119. zero_init = true;
  3120. }
  3121. }
  3122. if (zero_init) {
  3123. lb_mem_zero_ptr(p, ptr, type, alignment);
  3124. }
  3125. lbValue val = {};
  3126. val.value = ptr;
  3127. val.type = alloc_type_pointer(type);
  3128. if (e != nullptr) {
  3129. lb_add_entity(p->module, e, val);
  3130. lb_add_debug_local_variable(p, ptr, type, e->token);
  3131. }
  3132. return lb_addr(val);
  3133. }
  3134. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  3135. return lb_add_local(p, type, nullptr, zero_init);
  3136. }
  3137. lbAddr lb_add_local_generated_temp(lbProcedure *p, Type *type, i64 min_alignment) {
  3138. lbAddr res = lb_add_local(p, type, nullptr, false, 0, true);
  3139. lb_try_update_alignment(res.addr, cast(unsigned)min_alignment);
  3140. return res;
  3141. }
  3142. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  3143. GB_ASSERT(pd->body != nullptr);
  3144. lbModule *m = p->module;
  3145. auto *min_dep_set = &m->info->minimum_dependency_set;
  3146. if (ptr_set_exists(min_dep_set, e) == false) {
  3147. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  3148. return;
  3149. }
  3150. // NOTE(bill): Generate a new name
  3151. // parent.name-guid
  3152. String original_name = e->token.string;
  3153. String pd_name = original_name;
  3154. if (e->Procedure.link_name.len > 0) {
  3155. pd_name = e->Procedure.link_name;
  3156. }
  3157. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  3158. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  3159. i32 guid = cast(i32)p->children.count;
  3160. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  3161. String name = make_string(cast(u8 *)name_text, name_len-1);
  3162. e->Procedure.link_name = name;
  3163. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3164. e->code_gen_procedure = nested_proc;
  3165. lbValue value = {};
  3166. value.value = nested_proc->value;
  3167. value.type = nested_proc->type;
  3168. lb_add_entity(m, e, value);
  3169. array_add(&p->children, nested_proc);
  3170. array_add(&m->procedures_to_generate, nested_proc);
  3171. }
  3172. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  3173. if (e == nullptr) {
  3174. return;
  3175. }
  3176. GB_ASSERT(e->kind == Entity_LibraryName);
  3177. GB_ASSERT(e->flags & EntityFlag_Used);
  3178. for_array(i, e->LibraryName.paths) {
  3179. String library_path = e->LibraryName.paths[i];
  3180. if (library_path.len == 0) {
  3181. continue;
  3182. }
  3183. bool ok = true;
  3184. for_array(path_index, m->foreign_library_paths) {
  3185. String path = m->foreign_library_paths[path_index];
  3186. #if defined(GB_SYSTEM_WINDOWS)
  3187. if (str_eq_ignore_case(path, library_path)) {
  3188. #else
  3189. if (str_eq(path, library_path)) {
  3190. #endif
  3191. ok = false;
  3192. break;
  3193. }
  3194. }
  3195. if (ok) {
  3196. array_add(&m->foreign_library_paths, library_path);
  3197. }
  3198. }
  3199. }
  3200. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  3201. if (vd == nullptr || vd->is_mutable) {
  3202. return;
  3203. }
  3204. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  3205. static i32 global_guid = 0;
  3206. for_array(i, vd->names) {
  3207. Ast *ident = vd->names[i];
  3208. GB_ASSERT(ident->kind == Ast_Ident);
  3209. Entity *e = entity_of_node(ident);
  3210. GB_ASSERT(e != nullptr);
  3211. if (e->kind != Entity_TypeName) {
  3212. continue;
  3213. }
  3214. bool polymorphic_struct = false;
  3215. if (e->type != nullptr && e->kind == Entity_TypeName) {
  3216. Type *bt = base_type(e->type);
  3217. if (bt->kind == Type_Struct) {
  3218. polymorphic_struct = bt->Struct.is_polymorphic;
  3219. }
  3220. }
  3221. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  3222. continue;
  3223. }
  3224. if (e->TypeName.ir_mangled_name.len != 0) {
  3225. // NOTE(bill): Already set
  3226. continue;
  3227. }
  3228. lb_set_nested_type_name_ir_mangled_name(e, p);
  3229. }
  3230. for_array(i, vd->names) {
  3231. Ast *ident = vd->names[i];
  3232. GB_ASSERT(ident->kind == Ast_Ident);
  3233. Entity *e = entity_of_node(ident);
  3234. GB_ASSERT(e != nullptr);
  3235. if (e->kind != Entity_Procedure) {
  3236. continue;
  3237. }
  3238. GB_ASSERT (vd->values[i] != nullptr);
  3239. Ast *value = unparen_expr(vd->values[i]);
  3240. if (value->kind != Ast_ProcLit) {
  3241. continue; // It's an alias
  3242. }
  3243. CheckerInfo *info = p->module->info;
  3244. DeclInfo *decl = decl_info_of_entity(e);
  3245. ast_node(pl, ProcLit, decl->proc_lit);
  3246. if (pl->body != nullptr) {
  3247. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  3248. if (found) {
  3249. auto procs = *found;
  3250. for_array(i, procs) {
  3251. Entity *e = procs[i];
  3252. if (!ptr_set_exists(min_dep_set, e)) {
  3253. continue;
  3254. }
  3255. DeclInfo *d = decl_info_of_entity(e);
  3256. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  3257. }
  3258. } else {
  3259. lb_build_nested_proc(p, pl, e);
  3260. }
  3261. } else {
  3262. // FFI - Foreign function interace
  3263. String original_name = e->token.string;
  3264. String name = original_name;
  3265. if (e->Procedure.is_foreign) {
  3266. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  3267. }
  3268. if (e->Procedure.link_name.len > 0) {
  3269. name = e->Procedure.link_name;
  3270. }
  3271. lbValue *prev_value = string_map_get(&p->module->members, name);
  3272. if (prev_value != nullptr) {
  3273. // NOTE(bill): Don't do mutliple declarations in the IR
  3274. return;
  3275. }
  3276. e->Procedure.link_name = name;
  3277. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  3278. lbValue value = {};
  3279. value.value = nested_proc->value;
  3280. value.type = nested_proc->type;
  3281. array_add(&p->module->procedures_to_generate, nested_proc);
  3282. array_add(&p->children, nested_proc);
  3283. string_map_set(&p->module->members, name, value);
  3284. }
  3285. }
  3286. }
  3287. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  3288. for_array(i, stmts) {
  3289. Ast *stmt = stmts[i];
  3290. switch (stmt->kind) {
  3291. case_ast_node(vd, ValueDecl, stmt);
  3292. lb_build_constant_value_decl(p, vd);
  3293. case_end;
  3294. case_ast_node(fb, ForeignBlockDecl, stmt);
  3295. ast_node(block, BlockStmt, fb->body);
  3296. lb_build_stmt_list(p, block->stmts);
  3297. case_end;
  3298. }
  3299. }
  3300. for_array(i, stmts) {
  3301. lb_build_stmt(p, stmts[i]);
  3302. }
  3303. }
  3304. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  3305. GB_ASSERT(ident->kind == Ast_Ident);
  3306. Entity *e = entity_of_node(ident);
  3307. GB_ASSERT(e->kind == Entity_Label);
  3308. for_array(i, p->branch_blocks) {
  3309. lbBranchBlocks *b = &p->branch_blocks[i];
  3310. if (b->label == e->Label.node) {
  3311. return *b;
  3312. }
  3313. }
  3314. GB_PANIC("Unreachable");
  3315. lbBranchBlocks empty = {};
  3316. return empty;
  3317. }
  3318. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  3319. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  3320. tl->prev = p->target_list;
  3321. tl->break_ = break_;
  3322. tl->continue_ = continue_;
  3323. tl->fallthrough_ = fallthrough_;
  3324. p->target_list = tl;
  3325. if (label != nullptr) { // Set label blocks
  3326. GB_ASSERT(label->kind == Ast_Label);
  3327. for_array(i, p->branch_blocks) {
  3328. lbBranchBlocks *b = &p->branch_blocks[i];
  3329. GB_ASSERT(b->label != nullptr && label != nullptr);
  3330. GB_ASSERT(b->label->kind == Ast_Label);
  3331. if (b->label == label) {
  3332. b->break_ = break_;
  3333. b->continue_ = continue_;
  3334. return tl;
  3335. }
  3336. }
  3337. GB_PANIC("Unreachable");
  3338. }
  3339. return tl;
  3340. }
  3341. void lb_pop_target_list(lbProcedure *p) {
  3342. p->target_list = p->target_list->prev;
  3343. }
  3344. void lb_open_scope(lbProcedure *p, Scope *s) {
  3345. lbModule *m = p->module;
  3346. if (m->debug_builder) {
  3347. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  3348. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  3349. Token token = ast_token(s->node);
  3350. unsigned line = cast(unsigned)token.pos.line;
  3351. unsigned column = cast(unsigned)token.pos.column;
  3352. LLVMMetadataRef file = nullptr;
  3353. if (s->node->file != nullptr) {
  3354. file = lb_get_llvm_metadata(m, s->node->file);
  3355. }
  3356. LLVMMetadataRef scope = nullptr;
  3357. if (p->scope_stack.count > 0) {
  3358. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  3359. }
  3360. if (scope == nullptr) {
  3361. scope = lb_get_llvm_metadata(m, p);
  3362. }
  3363. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  3364. if (m->debug_builder) {
  3365. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  3366. file, line, column
  3367. );
  3368. lb_set_llvm_metadata(m, s, res);
  3369. }
  3370. }
  3371. }
  3372. p->scope_index += 1;
  3373. array_add(&p->scope_stack, s);
  3374. }
  3375. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  3376. lb_emit_defer_stmts(p, kind, block);
  3377. GB_ASSERT(p->scope_index > 0);
  3378. // NOTE(bill): Remove `context`s made in that scope
  3379. while (p->context_stack.count > 0) {
  3380. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  3381. if (ctx->scope_index >= p->scope_index) {
  3382. array_pop(&p->context_stack);
  3383. } else {
  3384. break;
  3385. }
  3386. }
  3387. p->scope_index -= 1;
  3388. array_pop(&p->scope_stack);
  3389. }
  3390. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  3391. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  3392. GB_ASSERT(is_type_boolean(tv.type));
  3393. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  3394. if (tv.value.value_bool) {
  3395. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3396. } else if (ws->else_stmt) {
  3397. switch (ws->else_stmt->kind) {
  3398. case Ast_BlockStmt:
  3399. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3400. break;
  3401. case Ast_WhenStmt:
  3402. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3403. break;
  3404. default:
  3405. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3406. break;
  3407. }
  3408. }
  3409. }
  3410. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3411. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3412. lbModule *m = p->module;
  3413. lbValue count = {};
  3414. Type *expr_type = base_type(type_deref(expr.type));
  3415. switch (expr_type->kind) {
  3416. case Type_Array:
  3417. count = lb_const_int(m, t_int, expr_type->Array.count);
  3418. break;
  3419. }
  3420. lbValue val = {};
  3421. lbValue idx = {};
  3422. lbBlock *loop = nullptr;
  3423. lbBlock *done = nullptr;
  3424. lbBlock *body = nullptr;
  3425. lbAddr index = lb_add_local_generated(p, t_int, false);
  3426. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3427. loop = lb_create_block(p, "for.index.loop");
  3428. lb_emit_jump(p, loop);
  3429. lb_start_block(p, loop);
  3430. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3431. lb_addr_store(p, index, incr);
  3432. body = lb_create_block(p, "for.index.body");
  3433. done = lb_create_block(p, "for.index.done");
  3434. if (count.value == nullptr) {
  3435. GB_ASSERT(count_ptr.value != nullptr);
  3436. count = lb_emit_load(p, count_ptr);
  3437. }
  3438. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3439. lb_emit_if(p, cond, body, done);
  3440. lb_start_block(p, body);
  3441. idx = lb_addr_load(p, index);
  3442. switch (expr_type->kind) {
  3443. case Type_Array: {
  3444. if (val_type != nullptr) {
  3445. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3446. }
  3447. break;
  3448. }
  3449. case Type_EnumeratedArray: {
  3450. if (val_type != nullptr) {
  3451. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3452. // NOTE(bill): Override the idx value for the enumeration
  3453. Type *index_type = expr_type->EnumeratedArray.index;
  3454. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3455. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3456. }
  3457. }
  3458. break;
  3459. }
  3460. case Type_Slice: {
  3461. if (val_type != nullptr) {
  3462. lbValue elem = lb_slice_elem(p, expr);
  3463. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3464. }
  3465. break;
  3466. }
  3467. case Type_DynamicArray: {
  3468. if (val_type != nullptr) {
  3469. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3470. elem = lb_emit_load(p, elem);
  3471. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3472. }
  3473. break;
  3474. }
  3475. case Type_Map: {
  3476. lbValue entries = lb_map_entries_ptr(p, expr);
  3477. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3478. elem = lb_emit_load(p, elem);
  3479. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3480. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3481. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3482. break;
  3483. }
  3484. case Type_Struct: {
  3485. GB_ASSERT(is_type_soa_struct(expr_type));
  3486. break;
  3487. }
  3488. default:
  3489. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3490. break;
  3491. }
  3492. if (val_) *val_ = val;
  3493. if (idx_) *idx_ = idx;
  3494. if (loop_) *loop_ = loop;
  3495. if (done_) *done_ = done;
  3496. }
  3497. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3498. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3499. lbModule *m = p->module;
  3500. lbValue count = lb_const_int(m, t_int, 0);
  3501. Type *expr_type = base_type(expr.type);
  3502. switch (expr_type->kind) {
  3503. case Type_Basic:
  3504. count = lb_string_len(p, expr);
  3505. break;
  3506. default:
  3507. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3508. break;
  3509. }
  3510. lbValue val = {};
  3511. lbValue idx = {};
  3512. lbBlock *loop = nullptr;
  3513. lbBlock *done = nullptr;
  3514. lbBlock *body = nullptr;
  3515. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3516. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3517. loop = lb_create_block(p, "for.string.loop");
  3518. lb_emit_jump(p, loop);
  3519. lb_start_block(p, loop);
  3520. body = lb_create_block(p, "for.string.body");
  3521. done = lb_create_block(p, "for.string.done");
  3522. lbValue offset = lb_addr_load(p, offset_);
  3523. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3524. lb_emit_if(p, cond, body, done);
  3525. lb_start_block(p, body);
  3526. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3527. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3528. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3529. args[0] = lb_emit_string(p, str_elem, str_len);
  3530. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3531. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3532. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3533. idx = offset;
  3534. if (val_type != nullptr) {
  3535. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3536. }
  3537. if (val_) *val_ = val;
  3538. if (idx_) *idx_ = idx;
  3539. if (loop_) *loop_ = loop;
  3540. if (done_) *done_ = done;
  3541. }
  3542. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node,
  3543. AstRangeStmt *rs, Scope *scope) {
  3544. bool ADD_EXTRA_WRAPPING_CHECK = true;
  3545. lbModule *m = p->module;
  3546. lb_open_scope(p, scope);
  3547. Type *val0_type = nullptr;
  3548. Type *val1_type = nullptr;
  3549. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3550. val0_type = type_of_expr(rs->vals[0]);
  3551. }
  3552. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3553. val1_type = type_of_expr(rs->vals[1]);
  3554. }
  3555. if (val0_type != nullptr) {
  3556. Entity *e = entity_of_node(rs->vals[0]);
  3557. lb_add_local(p, e->type, e, true);
  3558. }
  3559. if (val1_type != nullptr) {
  3560. Entity *e = entity_of_node(rs->vals[1]);
  3561. lb_add_local(p, e->type, e, true);
  3562. }
  3563. TokenKind op = Token_Lt;
  3564. switch (node->op.kind) {
  3565. case Token_Ellipsis: op = Token_LtEq; break;
  3566. case Token_RangeFull: op = Token_LtEq; break;
  3567. case Token_RangeHalf: op = Token_Lt; break;
  3568. default: GB_PANIC("Invalid interval operator"); break;
  3569. }
  3570. lbValue lower = lb_build_expr(p, node->left);
  3571. lbValue upper = {}; // initialized each time in the loop
  3572. lbAddr value = lb_add_local_generated(p, val0_type ? val0_type : lower.type, false);
  3573. lb_addr_store(p, value, lower);
  3574. lbAddr index = lb_add_local_generated(p, t_int, false);
  3575. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3576. lbBlock *loop = lb_create_block(p, "for.interval.loop");
  3577. lbBlock *body = lb_create_block(p, "for.interval.body");
  3578. lbBlock *done = lb_create_block(p, "for.interval.done");
  3579. lb_emit_jump(p, loop);
  3580. lb_start_block(p, loop);
  3581. upper = lb_build_expr(p, node->right);
  3582. lbValue curr_value = lb_addr_load(p, value);
  3583. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3584. lb_emit_if(p, cond, body, done);
  3585. lb_start_block(p, body);
  3586. lbValue val = lb_addr_load(p, value);
  3587. lbValue idx = lb_addr_load(p, index);
  3588. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3589. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], idx);
  3590. {
  3591. // NOTE: this check block will most likely be optimized out, and is here
  3592. // to make this code easier to read
  3593. lbBlock *check = nullptr;
  3594. lbBlock *post = lb_create_block(p, "for.interval.post");
  3595. lbBlock *continue_block = post;
  3596. if (ADD_EXTRA_WRAPPING_CHECK &&
  3597. op == Token_LtEq) {
  3598. check = lb_create_block(p, "for.interval.check");
  3599. continue_block = check;
  3600. }
  3601. lb_push_target_list(p, rs->label, done, continue_block, nullptr);
  3602. lb_build_stmt(p, rs->body);
  3603. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3604. lb_pop_target_list(p);
  3605. if (check != nullptr) {
  3606. lb_emit_jump(p, check);
  3607. lb_start_block(p, check);
  3608. lbValue check_cond = lb_emit_comp(p, Token_NotEq, curr_value, upper);
  3609. lb_emit_if(p, check_cond, post, done);
  3610. } else {
  3611. lb_emit_jump(p, post);
  3612. }
  3613. lb_start_block(p, post);
  3614. lb_emit_increment(p, value.addr);
  3615. lb_emit_increment(p, index.addr);
  3616. lb_emit_jump(p, loop);
  3617. }
  3618. lb_start_block(p, done);
  3619. }
  3620. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3621. lbModule *m = p->module;
  3622. Type *t = enum_type;
  3623. GB_ASSERT(is_type_enum(t));
  3624. Type *enum_ptr = alloc_type_pointer(t);
  3625. t = base_type(t);
  3626. Type *core_elem = core_type(t);
  3627. GB_ASSERT(t->kind == Type_Enum);
  3628. i64 enum_count = t->Enum.fields.count;
  3629. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3630. lbValue ti = lb_type_info(m, t);
  3631. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3632. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3633. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3634. lbValue values_data = lb_slice_elem(p, values);
  3635. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3636. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3637. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3638. lb_emit_jump(p, loop);
  3639. lb_start_block(p, loop);
  3640. lbBlock *body = lb_create_block(p, "for.enum.body");
  3641. lbBlock *done = lb_create_block(p, "for.enum.done");
  3642. lbValue offset = lb_addr_load(p, offset_);
  3643. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3644. lb_emit_if(p, cond, body, done);
  3645. lb_start_block(p, body);
  3646. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3647. lb_emit_increment(p, offset_.addr);
  3648. lbValue val = {};
  3649. if (val_type != nullptr) {
  3650. GB_ASSERT(are_types_identical(enum_type, val_type));
  3651. if (is_type_integer(core_elem)) {
  3652. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3653. val = lb_emit_conv(p, i, t);
  3654. } else {
  3655. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3656. }
  3657. }
  3658. if (val_) *val_ = val;
  3659. if (idx_) *idx_ = offset;
  3660. if (loop_) *loop_ = loop;
  3661. if (done_) *done_ = done;
  3662. }
  3663. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3664. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3665. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3666. lb_emit_jump(p, loop);
  3667. lb_start_block(p, loop);
  3668. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3669. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3670. lbValue tuple_value = lb_build_expr(p, expr);
  3671. Type *tuple = tuple_value.type;
  3672. GB_ASSERT(tuple->kind == Type_Tuple);
  3673. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3674. i32 cond_index = tuple_count-1;
  3675. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3676. lb_emit_if(p, cond, body, done);
  3677. lb_start_block(p, body);
  3678. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3679. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3680. if (loop_) *loop_ = loop;
  3681. if (done_) *done_ = done;
  3682. }
  3683. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3684. Ast *expr = unparen_expr(rs->expr);
  3685. TypeAndValue tav = type_and_value_of_expr(expr);
  3686. lbBlock *loop = nullptr;
  3687. lbBlock *body = nullptr;
  3688. lbBlock *done = nullptr;
  3689. lb_open_scope(p, scope);
  3690. Type *val_types[2] = {};
  3691. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3692. val_types[0] = type_of_expr(rs->vals[0]);
  3693. }
  3694. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3695. val_types[1] = type_of_expr(rs->vals[1]);
  3696. }
  3697. lbAddr array = lb_build_addr(p, expr);
  3698. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3699. array = lb_addr(lb_addr_load(p, array));
  3700. }
  3701. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3702. lbAddr index = lb_add_local_generated(p, t_int, false);
  3703. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3704. loop = lb_create_block(p, "for.soa.loop");
  3705. lb_emit_jump(p, loop);
  3706. lb_start_block(p, loop);
  3707. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3708. lb_addr_store(p, index, incr);
  3709. body = lb_create_block(p, "for.soa.body");
  3710. done = lb_create_block(p, "for.soa.done");
  3711. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3712. lb_emit_if(p, cond, body, done);
  3713. lb_start_block(p, body);
  3714. if (val_types[0]) {
  3715. Entity *e = entity_of_node(rs->vals[0]);
  3716. if (e != nullptr) {
  3717. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3718. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3719. }
  3720. }
  3721. if (val_types[1]) {
  3722. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3723. }
  3724. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3725. lb_build_stmt(p, rs->body);
  3726. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3727. lb_pop_target_list(p);
  3728. lb_emit_jump(p, loop);
  3729. lb_start_block(p, done);
  3730. }
  3731. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3732. Ast *expr = unparen_expr(rs->expr);
  3733. if (is_ast_range(expr)) {
  3734. lb_build_range_interval(p, &expr->BinaryExpr, rs, scope);
  3735. return;
  3736. }
  3737. Type *expr_type = type_of_expr(expr);
  3738. if (expr_type != nullptr) {
  3739. Type *et = base_type(type_deref(expr_type));
  3740. if (is_type_soa_struct(et)) {
  3741. lb_build_range_stmt_struct_soa(p, rs, scope);
  3742. return;
  3743. }
  3744. }
  3745. lb_open_scope(p, scope);
  3746. Type *val0_type = nullptr;
  3747. Type *val1_type = nullptr;
  3748. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3749. val0_type = type_of_expr(rs->vals[0]);
  3750. }
  3751. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3752. val1_type = type_of_expr(rs->vals[1]);
  3753. }
  3754. if (val0_type != nullptr) {
  3755. Entity *e = entity_of_node(rs->vals[0]);
  3756. lb_add_local(p, e->type, e, true);
  3757. }
  3758. if (val1_type != nullptr) {
  3759. Entity *e = entity_of_node(rs->vals[1]);
  3760. lb_add_local(p, e->type, e, true);
  3761. }
  3762. lbValue val = {};
  3763. lbValue key = {};
  3764. lbBlock *loop = nullptr;
  3765. lbBlock *done = nullptr;
  3766. bool is_map = false;
  3767. TypeAndValue tav = type_and_value_of_expr(expr);
  3768. if (tav.mode == Addressing_Type) {
  3769. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3770. } else {
  3771. Type *expr_type = type_of_expr(expr);
  3772. Type *et = base_type(type_deref(expr_type));
  3773. switch (et->kind) {
  3774. case Type_Map: {
  3775. is_map = true;
  3776. lbValue map = lb_build_addr_ptr(p, expr);
  3777. if (is_type_pointer(type_deref(map.type))) {
  3778. map = lb_emit_load(p, map);
  3779. }
  3780. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3781. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3782. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3783. break;
  3784. }
  3785. case Type_Array: {
  3786. lbValue array = lb_build_addr_ptr(p, expr);
  3787. if (is_type_pointer(type_deref(array.type))) {
  3788. array = lb_emit_load(p, array);
  3789. }
  3790. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3791. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3792. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3793. break;
  3794. }
  3795. case Type_EnumeratedArray: {
  3796. lbValue array = lb_build_addr_ptr(p, expr);
  3797. if (is_type_pointer(type_deref(array.type))) {
  3798. array = lb_emit_load(p, array);
  3799. }
  3800. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3801. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3802. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3803. break;
  3804. }
  3805. case Type_DynamicArray: {
  3806. lbValue count_ptr = {};
  3807. lbValue array = lb_build_addr_ptr(p, expr);
  3808. if (is_type_pointer(type_deref(array.type))) {
  3809. array = lb_emit_load(p, array);
  3810. }
  3811. count_ptr = lb_emit_struct_ep(p, array, 1);
  3812. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3813. break;
  3814. }
  3815. case Type_Slice: {
  3816. lbValue count_ptr = {};
  3817. lbValue slice = lb_build_expr(p, expr);
  3818. if (is_type_pointer(slice.type)) {
  3819. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3820. slice = lb_emit_load(p, slice);
  3821. } else {
  3822. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3823. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3824. }
  3825. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3826. break;
  3827. }
  3828. case Type_Basic: {
  3829. lbValue string = lb_build_expr(p, expr);
  3830. if (is_type_pointer(string.type)) {
  3831. string = lb_emit_load(p, string);
  3832. }
  3833. if (is_type_untyped(expr_type)) {
  3834. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3835. lb_addr_store(p, s, string);
  3836. string = lb_addr_load(p, s);
  3837. }
  3838. Type *t = base_type(string.type);
  3839. GB_ASSERT(!is_type_cstring(t));
  3840. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3841. break;
  3842. }
  3843. case Type_Tuple:
  3844. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3845. break;
  3846. default:
  3847. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3848. break;
  3849. }
  3850. }
  3851. if (is_map) {
  3852. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3853. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3854. } else {
  3855. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3856. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3857. }
  3858. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3859. lb_build_stmt(p, rs->body);
  3860. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3861. lb_pop_target_list(p);
  3862. lb_emit_jump(p, loop);
  3863. lb_start_block(p, done);
  3864. }
  3865. void lb_build_unroll_range_stmt(lbProcedure *p, AstUnrollRangeStmt *rs, Scope *scope) {
  3866. lbModule *m = p->module;
  3867. lb_open_scope(p, scope); // Open scope here
  3868. Type *val0_type = nullptr;
  3869. Type *val1_type = nullptr;
  3870. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3871. val0_type = type_of_expr(rs->val0);
  3872. }
  3873. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3874. val1_type = type_of_expr(rs->val1);
  3875. }
  3876. if (val0_type != nullptr) {
  3877. Entity *e = entity_of_node(rs->val0);
  3878. lb_add_local(p, e->type, e, true);
  3879. }
  3880. if (val1_type != nullptr) {
  3881. Entity *e = entity_of_node(rs->val1);
  3882. lb_add_local(p, e->type, e, true);
  3883. }
  3884. lbValue val = {};
  3885. lbValue key = {};
  3886. lbBlock *loop = nullptr;
  3887. lbBlock *done = nullptr;
  3888. Ast *expr = unparen_expr(rs->expr);
  3889. TypeAndValue tav = type_and_value_of_expr(expr);
  3890. if (is_ast_range(expr)) {
  3891. lbAddr val0_addr = {};
  3892. lbAddr val1_addr = {};
  3893. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3894. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3895. TokenKind op = expr->BinaryExpr.op.kind;
  3896. Ast *start_expr = expr->BinaryExpr.left;
  3897. Ast *end_expr = expr->BinaryExpr.right;
  3898. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3899. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3900. ExactValue start = start_expr->tav.value;
  3901. ExactValue end = end_expr->tav.value;
  3902. if (op != Token_RangeHalf) { // .. [start, end] (or ..=)
  3903. ExactValue index = exact_value_i64(0);
  3904. for (ExactValue val = start;
  3905. compare_exact_values(Token_LtEq, val, end);
  3906. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3907. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3908. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3909. lb_build_stmt(p, rs->body);
  3910. }
  3911. } else { // ..< [start, end)
  3912. ExactValue index = exact_value_i64(0);
  3913. for (ExactValue val = start;
  3914. compare_exact_values(Token_Lt, val, end);
  3915. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3916. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3917. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3918. lb_build_stmt(p, rs->body);
  3919. }
  3920. }
  3921. } else if (tav.mode == Addressing_Type) {
  3922. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3923. Type *et = type_deref(tav.type);
  3924. Type *bet = base_type(et);
  3925. lbAddr val0_addr = {};
  3926. lbAddr val1_addr = {};
  3927. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3928. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3929. for_array(i, bet->Enum.fields) {
  3930. Entity *field = bet->Enum.fields[i];
  3931. GB_ASSERT(field->kind == Entity_Constant);
  3932. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3933. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3934. lb_build_stmt(p, rs->body);
  3935. }
  3936. } else {
  3937. lbAddr val0_addr = {};
  3938. lbAddr val1_addr = {};
  3939. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3940. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3941. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3942. Type *t = base_type(expr->tav.type);
  3943. switch (t->kind) {
  3944. case Type_Basic:
  3945. GB_ASSERT(is_type_string(t));
  3946. {
  3947. ExactValue value = expr->tav.value;
  3948. GB_ASSERT(value.kind == ExactValue_String);
  3949. String str = value.value_string;
  3950. Rune codepoint = 0;
  3951. isize offset = 0;
  3952. do {
  3953. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3954. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3955. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3956. lb_build_stmt(p, rs->body);
  3957. offset += width;
  3958. } while (offset < str.len);
  3959. }
  3960. break;
  3961. case Type_Array:
  3962. if (t->Array.count > 0) {
  3963. lbValue val = lb_build_expr(p, expr);
  3964. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3965. for (i64 i = 0; i < t->Array.count; i++) {
  3966. if (val0_type) {
  3967. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3968. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3969. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3970. }
  3971. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3972. lb_build_stmt(p, rs->body);
  3973. }
  3974. }
  3975. break;
  3976. case Type_EnumeratedArray:
  3977. if (t->EnumeratedArray.count > 0) {
  3978. lbValue val = lb_build_expr(p, expr);
  3979. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3980. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3981. if (val0_type) {
  3982. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3983. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3984. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3985. }
  3986. if (val1_type) {
  3987. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3988. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3989. }
  3990. lb_build_stmt(p, rs->body);
  3991. }
  3992. }
  3993. break;
  3994. default:
  3995. GB_PANIC("Invalid '#unroll for' type");
  3996. break;
  3997. }
  3998. }
  3999. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4000. }
  4001. bool lb_switch_stmt_can_be_trivial_jump_table(AstSwitchStmt *ss, bool *default_found_) {
  4002. if (ss->tag == nullptr) {
  4003. return false;
  4004. }
  4005. bool is_typeid = false;
  4006. TypeAndValue tv = type_and_value_of_expr(ss->tag);
  4007. if (is_type_integer(core_type(tv.type))) {
  4008. // okay
  4009. } else if (is_type_typeid(tv.type)) {
  4010. // okay
  4011. is_typeid = true;
  4012. } else {
  4013. return false;
  4014. }
  4015. ast_node(body, BlockStmt, ss->body);
  4016. for_array(i, body->stmts) {
  4017. Ast *clause = body->stmts[i];
  4018. ast_node(cc, CaseClause, clause);
  4019. if (cc->list.count == 0) {
  4020. if (default_found_) *default_found_ = true;
  4021. continue;
  4022. }
  4023. for_array(j, cc->list) {
  4024. Ast *expr = unparen_expr(cc->list[j]);
  4025. if (is_ast_range(expr)) {
  4026. return false;
  4027. }
  4028. if (expr->tav.mode == Addressing_Type) {
  4029. GB_ASSERT(is_typeid);
  4030. continue;
  4031. }
  4032. tv = type_and_value_of_expr(expr);
  4033. if (tv.mode != Addressing_Constant) {
  4034. return false;
  4035. }
  4036. if (!is_type_integer(core_type(tv.type))) {
  4037. return false;
  4038. }
  4039. }
  4040. }
  4041. return true;
  4042. }
  4043. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  4044. lb_open_scope(p, scope);
  4045. if (ss->init != nullptr) {
  4046. lb_build_stmt(p, ss->init);
  4047. }
  4048. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  4049. if (ss->tag != nullptr) {
  4050. tag = lb_build_expr(p, ss->tag);
  4051. }
  4052. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  4053. ast_node(body, BlockStmt, ss->body);
  4054. isize case_count = body->stmts.count;
  4055. Slice<Ast *> default_stmts = {};
  4056. lbBlock *default_fall = nullptr;
  4057. lbBlock *default_block = nullptr;
  4058. lbBlock *fall = nullptr;
  4059. bool default_found = false;
  4060. bool is_trivial = lb_switch_stmt_can_be_trivial_jump_table(ss, &default_found);
  4061. auto body_blocks = slice_make<lbBlock *>(permanent_allocator(), body->stmts.count);
  4062. for_array(i, body->stmts) {
  4063. Ast *clause = body->stmts[i];
  4064. ast_node(cc, CaseClause, clause);
  4065. body_blocks[i] = lb_create_block(p, cc->list.count == 0 ? "switch.default.body" : "switch.case.body");
  4066. if (cc->list.count == 0) {
  4067. default_block = body_blocks[i];
  4068. }
  4069. }
  4070. LLVMValueRef switch_instr = nullptr;
  4071. if (is_trivial) {
  4072. isize num_cases = 0;
  4073. for_array(i, body->stmts) {
  4074. Ast *clause = body->stmts[i];
  4075. ast_node(cc, CaseClause, clause);
  4076. num_cases += cc->list.count;
  4077. }
  4078. LLVMBasicBlockRef end_block = done->block;
  4079. if (default_block) {
  4080. end_block = default_block->block;
  4081. }
  4082. switch_instr = LLVMBuildSwitch(p->builder, tag.value, end_block, cast(unsigned)num_cases);
  4083. }
  4084. for_array(i, body->stmts) {
  4085. Ast *clause = body->stmts[i];
  4086. ast_node(cc, CaseClause, clause);
  4087. lbBlock *body = body_blocks[i];
  4088. fall = done;
  4089. if (i+1 < case_count) {
  4090. fall = body_blocks[i+1];
  4091. }
  4092. if (cc->list.count == 0) {
  4093. // default case
  4094. default_stmts = cc->stmts;
  4095. default_fall = fall;
  4096. if (switch_instr == nullptr) {
  4097. default_block = body;
  4098. } else {
  4099. GB_ASSERT(default_block != nullptr);
  4100. }
  4101. continue;
  4102. }
  4103. lbBlock *next_cond = nullptr;
  4104. for_array(j, cc->list) {
  4105. Ast *expr = unparen_expr(cc->list[j]);
  4106. if (switch_instr != nullptr) {
  4107. lbValue on_val = {};
  4108. if (expr->tav.mode == Addressing_Type) {
  4109. GB_ASSERT(is_type_typeid(tag.type));
  4110. lbValue e = lb_typeid(p->module, expr->tav.type);
  4111. on_val = lb_emit_conv(p, e, tag.type);
  4112. } else {
  4113. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  4114. GB_ASSERT(!is_ast_range(expr));
  4115. on_val = lb_build_expr(p, expr);
  4116. }
  4117. GB_ASSERT(LLVMIsConstant(on_val.value));
  4118. LLVMAddCase(switch_instr, on_val.value, body->block);
  4119. continue;
  4120. }
  4121. next_cond = lb_create_block(p, "switch.case.next");
  4122. lbValue cond = {};
  4123. if (is_ast_range(expr)) {
  4124. ast_node(ie, BinaryExpr, expr);
  4125. TokenKind op = Token_Invalid;
  4126. switch (ie->op.kind) {
  4127. case Token_Ellipsis: op = Token_LtEq; break;
  4128. case Token_RangeFull: op = Token_LtEq; break;
  4129. case Token_RangeHalf: op = Token_Lt; break;
  4130. default: GB_PANIC("Invalid interval operator"); break;
  4131. }
  4132. lbValue lhs = lb_build_expr(p, ie->left);
  4133. lbValue rhs = lb_build_expr(p, ie->right);
  4134. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  4135. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  4136. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  4137. } else {
  4138. if (expr->tav.mode == Addressing_Type) {
  4139. GB_ASSERT(is_type_typeid(tag.type));
  4140. lbValue e = lb_typeid(p->module, expr->tav.type);
  4141. e = lb_emit_conv(p, e, tag.type);
  4142. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  4143. } else {
  4144. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  4145. }
  4146. }
  4147. lb_emit_if(p, cond, body, next_cond);
  4148. lb_start_block(p, next_cond);
  4149. }
  4150. lb_start_block(p, body);
  4151. lb_push_target_list(p, ss->label, done, nullptr, fall);
  4152. lb_open_scope(p, body->scope);
  4153. lb_build_stmt_list(p, cc->stmts);
  4154. lb_close_scope(p, lbDeferExit_Default, body);
  4155. lb_pop_target_list(p);
  4156. lb_emit_jump(p, done);
  4157. if (switch_instr == nullptr) {
  4158. lb_start_block(p, next_cond);
  4159. }
  4160. }
  4161. if (default_block != nullptr) {
  4162. if (switch_instr == nullptr) {
  4163. lb_emit_jump(p, default_block);
  4164. }
  4165. lb_start_block(p, default_block);
  4166. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  4167. lb_open_scope(p, default_block->scope);
  4168. lb_build_stmt_list(p, default_stmts);
  4169. lb_close_scope(p, lbDeferExit_Default, default_block);
  4170. lb_pop_target_list(p);
  4171. }
  4172. lb_emit_jump(p, done);
  4173. lb_close_scope(p, lbDeferExit_Default, done);
  4174. lb_start_block(p, done);
  4175. }
  4176. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  4177. Entity *e = implicit_entity_of_node(clause);
  4178. GB_ASSERT(e != nullptr);
  4179. if (e->flags & EntityFlag_Value) {
  4180. // by value
  4181. GB_ASSERT(are_types_identical(e->type, value.type));
  4182. lbAddr x = lb_add_local(p, e->type, e, false);
  4183. lb_addr_store(p, x, value);
  4184. } else {
  4185. // by reference
  4186. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  4187. lb_add_entity(p->module, e, value);
  4188. }
  4189. }
  4190. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  4191. Entity *e = entity_of_node(stmt_val);
  4192. if (e == nullptr) {
  4193. return {};
  4194. }
  4195. if ((e->flags & EntityFlag_Value) == 0) {
  4196. if (LLVMIsALoadInst(value.value)) {
  4197. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  4198. lb_add_entity(p->module, e, ptr);
  4199. return lb_addr(ptr);
  4200. }
  4201. }
  4202. // by value
  4203. lbAddr addr = lb_add_local(p, e->type, e, false);
  4204. lb_addr_store(p, addr, value);
  4205. return addr;
  4206. }
  4207. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  4208. ast_node(cc, CaseClause, clause);
  4209. lb_push_target_list(p, label, done, nullptr, nullptr);
  4210. lb_open_scope(p, body->scope);
  4211. lb_build_stmt_list(p, cc->stmts);
  4212. lb_close_scope(p, lbDeferExit_Default, body);
  4213. lb_pop_target_list(p);
  4214. lb_emit_jump(p, done);
  4215. }
  4216. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  4217. lbModule *m = p->module;
  4218. ast_node(as, AssignStmt, ss->tag);
  4219. GB_ASSERT(as->lhs.count == 1);
  4220. GB_ASSERT(as->rhs.count == 1);
  4221. lbValue parent = lb_build_expr(p, as->rhs[0]);
  4222. bool is_parent_ptr = is_type_pointer(parent.type);
  4223. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  4224. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  4225. lbValue parent_value = parent;
  4226. lbValue parent_ptr = parent;
  4227. if (!is_parent_ptr) {
  4228. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  4229. }
  4230. lbValue tag = {};
  4231. lbValue union_data = {};
  4232. if (switch_kind == TypeSwitch_Union) {
  4233. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  4234. if (is_type_union_maybe_pointer(type_deref(parent_ptr.type))) {
  4235. tag = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, union_data), t_int);
  4236. } else {
  4237. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  4238. tag = lb_emit_load(p, tag_ptr);
  4239. }
  4240. } else if (switch_kind == TypeSwitch_Any) {
  4241. tag = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  4242. } else {
  4243. GB_PANIC("Unknown switch kind");
  4244. }
  4245. ast_node(body, BlockStmt, ss->body);
  4246. lbBlock *done = lb_create_block(p, "typeswitch.done");
  4247. lbBlock *else_block = done;
  4248. lbBlock *default_block = nullptr;
  4249. isize num_cases = 0;
  4250. for_array(i, body->stmts) {
  4251. Ast *clause = body->stmts[i];
  4252. ast_node(cc, CaseClause, clause);
  4253. num_cases += cc->list.count;
  4254. if (cc->list.count == 0) {
  4255. GB_ASSERT(default_block == nullptr);
  4256. default_block = lb_create_block(p, "typeswitch.default.body");
  4257. else_block = default_block;
  4258. }
  4259. }
  4260. GB_ASSERT(tag.value != nullptr);
  4261. LLVMValueRef switch_instr = LLVMBuildSwitch(p->builder, tag.value, else_block->block, cast(unsigned)num_cases);
  4262. for_array(i, body->stmts) {
  4263. Ast *clause = body->stmts[i];
  4264. ast_node(cc, CaseClause, clause);
  4265. if (cc->list.count == 0) {
  4266. lb_start_block(p, default_block);
  4267. lb_store_type_case_implicit(p, clause, parent_value);
  4268. lb_type_case_body(p, ss->label, clause, p->curr_block, done);
  4269. continue;
  4270. }
  4271. lbBlock *body = lb_create_block(p, "typeswitch.body");
  4272. Type *case_type = nullptr;
  4273. for_array(type_index, cc->list) {
  4274. case_type = type_of_expr(cc->list[type_index]);
  4275. lbValue on_val = {};
  4276. if (switch_kind == TypeSwitch_Union) {
  4277. Type *ut = base_type(type_deref(parent.type));
  4278. on_val = lb_const_union_tag(m, ut, case_type);
  4279. } else if (switch_kind == TypeSwitch_Any) {
  4280. on_val = lb_typeid(m, case_type);
  4281. }
  4282. GB_ASSERT(on_val.value != nullptr);
  4283. LLVMAddCase(switch_instr, on_val.value, body->block);
  4284. }
  4285. Entity *case_entity = implicit_entity_of_node(clause);
  4286. lbValue value = parent_value;
  4287. lb_start_block(p, body);
  4288. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  4289. if (cc->list.count == 1) {
  4290. lbValue data = {};
  4291. if (switch_kind == TypeSwitch_Union) {
  4292. data = union_data;
  4293. } else if (switch_kind == TypeSwitch_Any) {
  4294. data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  4295. }
  4296. Type *ct = case_entity->type;
  4297. Type *ct_ptr = alloc_type_pointer(ct);
  4298. value = lb_emit_conv(p, data, ct_ptr);
  4299. if (!by_reference) {
  4300. value = lb_emit_load(p, value);
  4301. }
  4302. }
  4303. lb_store_type_case_implicit(p, clause, value);
  4304. lb_type_case_body(p, ss->label, clause, body, done);
  4305. }
  4306. lb_emit_jump(p, done);
  4307. lb_start_block(p, done);
  4308. }
  4309. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  4310. lbModule *m = p->module;
  4311. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  4312. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  4313. type = default_type(type);
  4314. lbValue short_circuit = {};
  4315. if (op == Token_CmpAnd) {
  4316. lb_build_cond(p, left, rhs, done);
  4317. short_circuit = lb_const_bool(m, type, false);
  4318. } else if (op == Token_CmpOr) {
  4319. lb_build_cond(p, left, done, rhs);
  4320. short_circuit = lb_const_bool(m, type, true);
  4321. }
  4322. if (rhs->preds.count == 0) {
  4323. lb_start_block(p, done);
  4324. return short_circuit;
  4325. }
  4326. if (done->preds.count == 0) {
  4327. lb_start_block(p, rhs);
  4328. if (lb_is_expr_untyped_const(right)) {
  4329. return lb_expr_untyped_const_to_typed(m, right, type);
  4330. }
  4331. return lb_build_expr(p, right);
  4332. }
  4333. Array<LLVMValueRef> incoming_values = {};
  4334. Array<LLVMBasicBlockRef> incoming_blocks = {};
  4335. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  4336. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  4337. for_array(i, done->preds) {
  4338. incoming_values[i] = short_circuit.value;
  4339. incoming_blocks[i] = done->preds[i]->block;
  4340. }
  4341. lb_start_block(p, rhs);
  4342. lbValue edge = {};
  4343. if (lb_is_expr_untyped_const(right)) {
  4344. edge = lb_expr_untyped_const_to_typed(m, right, type);
  4345. } else {
  4346. edge = lb_build_expr(p, right);
  4347. }
  4348. incoming_values[done->preds.count] = edge.value;
  4349. incoming_blocks[done->preds.count] = p->curr_block->block;
  4350. lb_emit_jump(p, done);
  4351. lb_start_block(p, done);
  4352. lbValue res = {};
  4353. res.type = type;
  4354. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  4355. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  4356. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  4357. return res;
  4358. }
  4359. lbCopyElisionHint lb_set_copy_elision_hint(lbProcedure *p, lbAddr const &addr, Ast *ast) {
  4360. lbCopyElisionHint prev = p->copy_elision_hint;
  4361. p->copy_elision_hint.used = false;
  4362. p->copy_elision_hint.ptr = {};
  4363. p->copy_elision_hint.ast = nullptr;
  4364. #if 0
  4365. if (addr.kind == lbAddr_Default && addr.addr.value != nullptr) {
  4366. p->copy_elision_hint.ptr = lb_addr_get_ptr(p, addr);
  4367. p->copy_elision_hint.ast = unparen_expr(ast);
  4368. }
  4369. #endif
  4370. return prev;
  4371. }
  4372. void lb_reset_copy_elision_hint(lbProcedure *p, lbCopyElisionHint prev_hint) {
  4373. p->copy_elision_hint = prev_hint;
  4374. }
  4375. lbValue lb_consume_copy_elision_hint(lbProcedure *p) {
  4376. lbValue return_ptr = p->copy_elision_hint.ptr;
  4377. p->copy_elision_hint.used = true;
  4378. p->copy_elision_hint.ptr = {};
  4379. p->copy_elision_hint.ast = nullptr;
  4380. return return_ptr;
  4381. }
  4382. void lb_build_static_variables(lbProcedure *p, AstValueDecl *vd) {
  4383. for_array(i, vd->names) {
  4384. lbValue value = {};
  4385. if (vd->values.count > 0) {
  4386. GB_ASSERT(vd->names.count == vd->values.count);
  4387. Ast *ast_value = vd->values[i];
  4388. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  4389. ast_value->tav.mode == Addressing_Invalid);
  4390. bool allow_local = false;
  4391. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  4392. }
  4393. Ast *ident = vd->names[i];
  4394. GB_ASSERT(!is_blank_ident(ident));
  4395. Entity *e = entity_of_node(ident);
  4396. GB_ASSERT(e->flags & EntityFlag_Static);
  4397. String name = e->token.string;
  4398. String mangled_name = {};
  4399. {
  4400. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  4401. str = gb_string_appendc(str, "-");
  4402. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  4403. mangled_name.text = cast(u8 *)str;
  4404. mangled_name.len = gb_string_length(str);
  4405. }
  4406. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  4407. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  4408. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  4409. if (value.value != nullptr) {
  4410. LLVMSetInitializer(global, value.value);
  4411. } else {
  4412. }
  4413. if (e->Variable.thread_local_model != "") {
  4414. LLVMSetThreadLocal(global, true);
  4415. String m = e->Variable.thread_local_model;
  4416. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  4417. if (m == "default") {
  4418. mode = LLVMGeneralDynamicTLSModel;
  4419. } else if (m == "localdynamic") {
  4420. mode = LLVMLocalDynamicTLSModel;
  4421. } else if (m == "initialexec") {
  4422. mode = LLVMInitialExecTLSModel;
  4423. } else if (m == "localexec") {
  4424. mode = LLVMLocalExecTLSModel;
  4425. } else {
  4426. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  4427. }
  4428. LLVMSetThreadLocalMode(global, mode);
  4429. } else {
  4430. LLVMSetLinkage(global, LLVMInternalLinkage);
  4431. }
  4432. lbValue global_val = {global, alloc_type_pointer(e->type)};
  4433. lb_add_entity(p->module, e, global_val);
  4434. lb_add_member(p->module, mangled_name, global_val);
  4435. }
  4436. }
  4437. void lb_build_assignment(lbProcedure *p, Array<lbAddr> &lvals, Slice<Ast *> const &values) {
  4438. if (values.count == 0) {
  4439. return;
  4440. }
  4441. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4442. for_array(i, values) {
  4443. Ast *rhs = values[i];
  4444. if (is_type_tuple(type_of_expr(rhs))) {
  4445. lbValue init = lb_build_expr(p, rhs);
  4446. Type *t = init.type;
  4447. GB_ASSERT(t->kind == Type_Tuple);
  4448. for_array(i, t->Tuple.variables) {
  4449. Entity *e = t->Tuple.variables[i];
  4450. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4451. array_add(&inits, v);
  4452. }
  4453. } else {
  4454. auto prev_hint = lb_set_copy_elision_hint(p, lvals[inits.count], rhs);
  4455. lbValue init = lb_build_expr(p, rhs);
  4456. if (p->copy_elision_hint.used) {
  4457. lvals[inits.count] = {}; // zero lval
  4458. }
  4459. lb_reset_copy_elision_hint(p, prev_hint);
  4460. array_add(&inits, init);
  4461. }
  4462. }
  4463. GB_ASSERT(lvals.count == inits.count);
  4464. for_array(i, inits) {
  4465. lbAddr lval = lvals[i];
  4466. lbValue init = inits[i];
  4467. lb_addr_store(p, lval, init);
  4468. }
  4469. }
  4470. void lb_build_return_stmt(lbProcedure *p, Slice<Ast *> const &return_results) {
  4471. lb_ensure_abi_function_type(p->module, p);
  4472. lbValue res = {};
  4473. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4474. isize return_count = p->type->Proc.result_count;
  4475. isize res_count = return_results.count;
  4476. lbFunctionType *ft = lb_get_function_type(p->module, p, p->type);
  4477. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  4478. if (return_count == 0) {
  4479. // No return values
  4480. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4481. LLVMBuildRetVoid(p->builder);
  4482. return;
  4483. } else if (return_count == 1) {
  4484. Entity *e = tuple->variables[0];
  4485. if (res_count == 0) {
  4486. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4487. GB_ASSERT(found);
  4488. res = lb_emit_load(p, *found);
  4489. } else {
  4490. res = lb_build_expr(p, return_results[0]);
  4491. res = lb_emit_conv(p, res, e->type);
  4492. }
  4493. if (p->type->Proc.has_named_results) {
  4494. // NOTE(bill): store the named values before returning
  4495. if (e->token.string != "") {
  4496. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4497. GB_ASSERT(found != nullptr);
  4498. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  4499. }
  4500. }
  4501. } else {
  4502. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4503. if (res_count != 0) {
  4504. for (isize res_index = 0; res_index < res_count; res_index++) {
  4505. lbValue res = lb_build_expr(p, return_results[res_index]);
  4506. Type *t = res.type;
  4507. if (t->kind == Type_Tuple) {
  4508. for_array(i, t->Tuple.variables) {
  4509. Entity *e = t->Tuple.variables[i];
  4510. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4511. array_add(&results, v);
  4512. }
  4513. } else {
  4514. array_add(&results, res);
  4515. }
  4516. }
  4517. } else {
  4518. for (isize res_index = 0; res_index < return_count; res_index++) {
  4519. Entity *e = tuple->variables[res_index];
  4520. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4521. GB_ASSERT(found);
  4522. lbValue res = lb_emit_load(p, *found);
  4523. array_add(&results, res);
  4524. }
  4525. }
  4526. GB_ASSERT(results.count == return_count);
  4527. if (p->type->Proc.has_named_results) {
  4528. auto named_results = slice_make<lbValue>(temporary_allocator(), results.count);
  4529. auto values = slice_make<lbValue>(temporary_allocator(), results.count);
  4530. // NOTE(bill): store the named values before returning
  4531. for_array(i, p->type->Proc.results->Tuple.variables) {
  4532. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4533. if (e->kind != Entity_Variable) {
  4534. continue;
  4535. }
  4536. if (e->token.string == "") {
  4537. continue;
  4538. }
  4539. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4540. GB_ASSERT(found != nullptr);
  4541. named_results[i] = *found;
  4542. values[i] = lb_emit_conv(p, results[i], e->type);
  4543. }
  4544. for_array(i, named_results) {
  4545. lb_emit_store(p, named_results[i], values[i]);
  4546. }
  4547. }
  4548. Type *ret_type = p->type->Proc.results;
  4549. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4550. if (return_by_pointer) {
  4551. res = p->return_ptr.addr;
  4552. } else {
  4553. res = lb_add_local_generated(p, ret_type, false).addr;
  4554. }
  4555. auto result_values = slice_make<lbValue>(temporary_allocator(), results.count);
  4556. auto result_eps = slice_make<lbValue>(temporary_allocator(), results.count);
  4557. for_array(i, results) {
  4558. result_values[i] = lb_emit_conv(p, results[i], tuple->variables[i]->type);
  4559. }
  4560. for_array(i, results) {
  4561. result_eps[i] = lb_emit_struct_ep(p, res, cast(i32)i);
  4562. }
  4563. for_array(i, result_values) {
  4564. lb_emit_store(p, result_eps[i], result_values[i]);
  4565. }
  4566. if (return_by_pointer) {
  4567. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4568. LLVMBuildRetVoid(p->builder);
  4569. return;
  4570. }
  4571. res = lb_emit_load(p, res);
  4572. }
  4573. if (return_by_pointer) {
  4574. if (res.value != nullptr) {
  4575. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4576. } else {
  4577. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4578. }
  4579. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4580. LLVMBuildRetVoid(p->builder);
  4581. } else {
  4582. LLVMValueRef ret_val = res.value;
  4583. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4584. if (p->abi_function_type->ret.cast_type != nullptr) {
  4585. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4586. }
  4587. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4588. LLVMBuildRet(p->builder, ret_val);
  4589. }
  4590. }
  4591. void lb_build_if_stmt(lbProcedure *p, Ast *node) {
  4592. ast_node(is, IfStmt, node);
  4593. lb_open_scope(p, node->scope); // Scope #1
  4594. if (is->init != nullptr) {
  4595. // TODO(bill): Should this have a separate block to begin with?
  4596. #if 1
  4597. lbBlock *init = lb_create_block(p, "if.init");
  4598. lb_emit_jump(p, init);
  4599. lb_start_block(p, init);
  4600. #endif
  4601. lb_build_stmt(p, is->init);
  4602. }
  4603. lbBlock *then = lb_create_block(p, "if.then");
  4604. lbBlock *done = lb_create_block(p, "if.done");
  4605. lbBlock *else_ = done;
  4606. if (is->else_stmt != nullptr) {
  4607. else_ = lb_create_block(p, "if.else");
  4608. }
  4609. lb_build_cond(p, is->cond, then, else_);
  4610. lb_start_block(p, then);
  4611. if (is->label != nullptr) {
  4612. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4613. tl->is_block = true;
  4614. }
  4615. lb_build_stmt(p, is->body);
  4616. lb_emit_jump(p, done);
  4617. if (is->else_stmt != nullptr) {
  4618. lb_start_block(p, else_);
  4619. lb_open_scope(p, is->else_stmt->scope);
  4620. lb_build_stmt(p, is->else_stmt);
  4621. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4622. lb_emit_jump(p, done);
  4623. }
  4624. lb_start_block(p, done);
  4625. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4626. }
  4627. void lb_build_for_stmt(lbProcedure *p, Ast *node) {
  4628. ast_node(fs, ForStmt, node);
  4629. lb_open_scope(p, node->scope); // Open Scope here
  4630. if (fs->init != nullptr) {
  4631. #if 1
  4632. lbBlock *init = lb_create_block(p, "for.init");
  4633. lb_emit_jump(p, init);
  4634. lb_start_block(p, init);
  4635. #endif
  4636. lb_build_stmt(p, fs->init);
  4637. }
  4638. lbBlock *body = lb_create_block(p, "for.body");
  4639. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4640. lbBlock *loop = body;
  4641. if (fs->cond != nullptr) {
  4642. loop = lb_create_block(p, "for.loop");
  4643. }
  4644. lbBlock *post = loop;
  4645. if (fs->post != nullptr) {
  4646. post = lb_create_block(p, "for.post");
  4647. }
  4648. lb_emit_jump(p, loop);
  4649. lb_start_block(p, loop);
  4650. if (loop != body) {
  4651. lb_build_cond(p, fs->cond, body, done);
  4652. lb_start_block(p, body);
  4653. }
  4654. lb_push_target_list(p, fs->label, done, post, nullptr);
  4655. lb_build_stmt(p, fs->body);
  4656. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4657. lb_pop_target_list(p);
  4658. lb_emit_jump(p, post);
  4659. if (fs->post != nullptr) {
  4660. lb_start_block(p, post);
  4661. lb_build_stmt(p, fs->post);
  4662. lb_emit_jump(p, loop);
  4663. }
  4664. lb_start_block(p, done);
  4665. }
  4666. void lb_build_assign_stmt_array(lbProcedure *p, TokenKind op, lbAddr const &lhs, lbValue const &value) {
  4667. Type *lhs_type = lb_addr_type(lhs);
  4668. Type *rhs_type = value.type;
  4669. Type *array_type = base_type(lhs_type);
  4670. GB_ASSERT(is_type_array_like(array_type));
  4671. i64 count = get_array_type_count(array_type);
  4672. Type *elem_type = base_array_type(array_type);
  4673. lbValue rhs = lb_emit_conv(p, value, lhs_type);
  4674. bool inline_array_arith = type_size_of(array_type) <= build_context.max_align;
  4675. if (lhs.kind == lbAddr_Swizzle) {
  4676. GB_ASSERT(is_type_array(lhs_type));
  4677. struct ValueAndIndex {
  4678. lbValue value;
  4679. u8 index;
  4680. };
  4681. bool indices_handled[4] = {};
  4682. i32 indices[4] = {};
  4683. i32 index_count = 0;
  4684. for (u8 i = 0; i < lhs.swizzle.count; i++) {
  4685. u8 index = lhs.swizzle.indices[i];
  4686. if (indices_handled[index]) {
  4687. continue;
  4688. }
  4689. indices[index_count++] = index;
  4690. }
  4691. gb_sort_array(indices, index_count, gb_i32_cmp(0));
  4692. lbValue lhs_ptrs[4] = {};
  4693. lbValue x_loads[4] = {};
  4694. lbValue y_loads[4] = {};
  4695. lbValue ops[4] = {};
  4696. for (i32 i = 0; i < index_count; i++) {
  4697. lhs_ptrs[i] = lb_emit_array_epi(p, lhs.addr, indices[i]);
  4698. }
  4699. for (i32 i = 0; i < index_count; i++) {
  4700. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  4701. }
  4702. for (i32 i = 0; i < index_count; i++) {
  4703. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  4704. y_loads[i].type = elem_type;
  4705. }
  4706. for (i32 i = 0; i < index_count; i++) {
  4707. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  4708. }
  4709. for (i32 i = 0; i < index_count; i++) {
  4710. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  4711. }
  4712. return;
  4713. }
  4714. lbValue x = lb_addr_get_ptr(p, lhs);
  4715. if (inline_array_arith) {
  4716. #if 1
  4717. #if 1
  4718. unsigned n = cast(unsigned)count;
  4719. auto lhs_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  4720. auto x_loads = slice_make<lbValue>(temporary_allocator(), n);
  4721. auto y_loads = slice_make<lbValue>(temporary_allocator(), n);
  4722. auto ops = slice_make<lbValue>(temporary_allocator(), n);
  4723. for (unsigned i = 0; i < n; i++) {
  4724. lhs_ptrs[i] = lb_emit_array_epi(p, x, i);
  4725. }
  4726. for (unsigned i = 0; i < n; i++) {
  4727. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  4728. }
  4729. for (unsigned i = 0; i < n; i++) {
  4730. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  4731. y_loads[i].type = elem_type;
  4732. }
  4733. for (unsigned i = 0; i < n; i++) {
  4734. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  4735. }
  4736. for (unsigned i = 0; i < n; i++) {
  4737. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  4738. }
  4739. #else
  4740. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4741. unsigned n = cast(unsigned)count;
  4742. auto lhs_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  4743. auto rhs_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  4744. auto x_loads = slice_make<lbValue>(temporary_allocator(), n);
  4745. auto y_loads = slice_make<lbValue>(temporary_allocator(), n);
  4746. auto ops = slice_make<lbValue>(temporary_allocator(), n);
  4747. for (unsigned i = 0; i < n; i++) {
  4748. lhs_ptrs[i] = lb_emit_array_epi(p, x, i);
  4749. }
  4750. for (unsigned i = 0; i < n; i++) {
  4751. rhs_ptrs[i] = lb_emit_array_epi(p, y, i);
  4752. }
  4753. for (unsigned i = 0; i < n; i++) {
  4754. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  4755. }
  4756. for (unsigned i = 0; i < n; i++) {
  4757. y_loads[i] = lb_emit_load(p, rhs_ptrs[i]);
  4758. }
  4759. for (unsigned i = 0; i < n; i++) {
  4760. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  4761. }
  4762. for (unsigned i = 0; i < n; i++) {
  4763. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  4764. }
  4765. #endif
  4766. #else
  4767. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4768. for (i64 i = 0; i < count; i++) {
  4769. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  4770. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  4771. lbValue a = lb_emit_load(p, a_ptr);
  4772. lbValue b = lb_emit_load(p, b_ptr);
  4773. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4774. lb_emit_store(p, a_ptr, c);
  4775. }
  4776. #endif
  4777. } else {
  4778. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4779. auto loop_data = lb_loop_start(p, count, t_i32);
  4780. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  4781. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  4782. lbValue a = lb_emit_load(p, a_ptr);
  4783. lbValue b = lb_emit_load(p, b_ptr);
  4784. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4785. lb_emit_store(p, a_ptr, c);
  4786. lb_loop_end(p, loop_data);
  4787. }
  4788. }
  4789. void lb_build_assign_stmt(lbProcedure *p, AstAssignStmt *as) {
  4790. if (as->op.kind == Token_Eq) {
  4791. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  4792. for_array(i, as->lhs) {
  4793. Ast *lhs = as->lhs[i];
  4794. lbAddr lval = {};
  4795. if (!is_blank_ident(lhs)) {
  4796. lval = lb_build_addr(p, lhs);
  4797. }
  4798. array_add(&lvals, lval);
  4799. }
  4800. lb_build_assignment(p, lvals, as->rhs);
  4801. return;
  4802. }
  4803. GB_ASSERT(as->lhs.count == 1);
  4804. GB_ASSERT(as->rhs.count == 1);
  4805. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4806. // +=, -=, etc
  4807. i32 op_ = cast(i32)as->op.kind;
  4808. op_ += Token_Add - Token_AddEq; // Convert += to +
  4809. TokenKind op = cast(TokenKind)op_;
  4810. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4811. Type *type = as->lhs[0]->tav.type;
  4812. lbValue new_value = lb_emit_logical_binary_expr(p, op, as->lhs[0], as->rhs[0], type);
  4813. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4814. lb_addr_store(p, lhs, new_value);
  4815. } else {
  4816. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4817. lbValue value = lb_build_expr(p, as->rhs[0]);
  4818. Type *lhs_type = lb_addr_type(lhs);
  4819. if (is_type_array(lhs_type)) {
  4820. lb_build_assign_stmt_array(p, op, lhs, value);
  4821. return;
  4822. } else {
  4823. lbValue old_value = lb_addr_load(p, lhs);
  4824. Type *type = old_value.type;
  4825. lbValue change = lb_emit_conv(p, value, type);
  4826. lbValue new_value = lb_emit_arith(p, op, old_value, change, type);
  4827. lb_addr_store(p, lhs, new_value);
  4828. }
  4829. }
  4830. }
  4831. void lb_build_stmt(lbProcedure *p, Ast *node) {
  4832. Ast *prev_stmt = p->curr_stmt;
  4833. defer (p->curr_stmt = prev_stmt);
  4834. p->curr_stmt = node;
  4835. if (p->curr_block != nullptr) {
  4836. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  4837. if (lb_is_instr_terminating(last_instr)) {
  4838. return;
  4839. }
  4840. }
  4841. LLVMMetadataRef prev_debug_location = nullptr;
  4842. if (p->debug_info != nullptr) {
  4843. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  4844. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  4845. }
  4846. defer (if (prev_debug_location != nullptr) {
  4847. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  4848. });
  4849. u16 prev_state_flags = p->state_flags;
  4850. defer (p->state_flags = prev_state_flags);
  4851. if (node->state_flags != 0) {
  4852. u16 in = node->state_flags;
  4853. u16 out = p->state_flags;
  4854. if (in & StateFlag_bounds_check) {
  4855. out |= StateFlag_bounds_check;
  4856. out &= ~StateFlag_no_bounds_check;
  4857. } else if (in & StateFlag_no_bounds_check) {
  4858. out |= StateFlag_no_bounds_check;
  4859. out &= ~StateFlag_bounds_check;
  4860. }
  4861. p->state_flags = out;
  4862. }
  4863. switch (node->kind) {
  4864. case_ast_node(bs, EmptyStmt, node);
  4865. case_end;
  4866. case_ast_node(us, UsingStmt, node);
  4867. case_end;
  4868. case_ast_node(ws, WhenStmt, node);
  4869. lb_build_when_stmt(p, ws);
  4870. case_end;
  4871. case_ast_node(bs, BlockStmt, node);
  4872. lbBlock *done = nullptr;
  4873. if (bs->label != nullptr) {
  4874. done = lb_create_block(p, "block.done");
  4875. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  4876. tl->is_block = true;
  4877. }
  4878. lb_open_scope(p, node->scope);
  4879. lb_build_stmt_list(p, bs->stmts);
  4880. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4881. if (done != nullptr) {
  4882. lb_emit_jump(p, done);
  4883. lb_start_block(p, done);
  4884. }
  4885. case_end;
  4886. case_ast_node(vd, ValueDecl, node);
  4887. if (!vd->is_mutable) {
  4888. return;
  4889. }
  4890. bool is_static = false;
  4891. if (vd->names.count > 0) {
  4892. Entity *e = entity_of_node(vd->names[0]);
  4893. if (e->flags & EntityFlag_Static) {
  4894. // NOTE(bill): If one of the entities is static, they all are
  4895. is_static = true;
  4896. }
  4897. }
  4898. if (is_static) {
  4899. lb_build_static_variables(p, vd);
  4900. return;
  4901. }
  4902. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  4903. for_array(i, vd->names) {
  4904. Ast *name = vd->names[i];
  4905. lbAddr lval = {};
  4906. if (!is_blank_ident(name)) {
  4907. Entity *e = entity_of_node(name);
  4908. bool zero_init = true; // Always do it
  4909. lval = lb_add_local(p, e->type, e, zero_init);
  4910. }
  4911. array_add(&lvals, lval);
  4912. }
  4913. lb_build_assignment(p, lvals, vd->values);
  4914. case_end;
  4915. case_ast_node(as, AssignStmt, node);
  4916. lb_build_assign_stmt(p, as);
  4917. case_end;
  4918. case_ast_node(es, ExprStmt, node);
  4919. lb_build_expr(p, es->expr);
  4920. case_end;
  4921. case_ast_node(ds, DeferStmt, node);
  4922. lb_add_defer_node(p, p->scope_index, ds->stmt);
  4923. case_end;
  4924. case_ast_node(rs, ReturnStmt, node);
  4925. lb_build_return_stmt(p, rs->results);
  4926. case_end;
  4927. case_ast_node(is, IfStmt, node);
  4928. lb_build_if_stmt(p, node);
  4929. case_end;
  4930. case_ast_node(fs, ForStmt, node);
  4931. lb_build_for_stmt(p, node);
  4932. case_end;
  4933. case_ast_node(rs, RangeStmt, node);
  4934. lb_build_range_stmt(p, rs, node->scope);
  4935. case_end;
  4936. case_ast_node(rs, UnrollRangeStmt, node);
  4937. lb_build_unroll_range_stmt(p, rs, node->scope);
  4938. case_end;
  4939. case_ast_node(ss, SwitchStmt, node);
  4940. lb_build_switch_stmt(p, ss, node->scope);
  4941. case_end;
  4942. case_ast_node(ss, TypeSwitchStmt, node);
  4943. lb_build_type_switch_stmt(p, ss);
  4944. case_end;
  4945. case_ast_node(bs, BranchStmt, node);
  4946. lbBlock *block = nullptr;
  4947. if (bs->label != nullptr) {
  4948. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4949. switch (bs->token.kind) {
  4950. case Token_break: block = bb.break_; break;
  4951. case Token_continue: block = bb.continue_; break;
  4952. case Token_fallthrough:
  4953. GB_PANIC("fallthrough cannot have a label");
  4954. break;
  4955. }
  4956. } else {
  4957. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4958. if (t->is_block) {
  4959. continue;
  4960. }
  4961. switch (bs->token.kind) {
  4962. case Token_break: block = t->break_; break;
  4963. case Token_continue: block = t->continue_; break;
  4964. case Token_fallthrough: block = t->fallthrough_; break;
  4965. }
  4966. }
  4967. }
  4968. if (block != nullptr) {
  4969. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4970. }
  4971. lb_emit_jump(p, block);
  4972. case_end;
  4973. }
  4974. }
  4975. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4976. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4977. lbValue res = {};
  4978. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4979. res.type = x.type;
  4980. return res;
  4981. }
  4982. lbValue lb_const_nil(lbModule *m, Type *type) {
  4983. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4984. return lbValue{v, type};
  4985. }
  4986. lbValue lb_const_undef(lbModule *m, Type *type) {
  4987. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4988. return lbValue{v, type};
  4989. }
  4990. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4991. lbValue res = {};
  4992. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4993. res.type = type;
  4994. return res;
  4995. }
  4996. lbValue lb_const_string(lbModule *m, String const &value) {
  4997. return lb_const_value(m, t_string, exact_value_string(value));
  4998. }
  4999. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  5000. lbValue res = {};
  5001. res.value = LLVMConstInt(lb_type(m, type), value, false);
  5002. res.type = type;
  5003. return res;
  5004. }
  5005. LLVMValueRef lb_const_f16(lbModule *m, f32 f, Type *type=t_f16) {
  5006. GB_ASSERT(type_size_of(type) == 2);
  5007. u16 u = f32_to_f16(f);
  5008. if (is_type_different_to_arch_endianness(type)) {
  5009. u = gb_endian_swap16(u);
  5010. }
  5011. LLVMValueRef i = LLVMConstInt(LLVMInt16TypeInContext(m->ctx), u, false);
  5012. return LLVMConstBitCast(i, lb_type(m, type));
  5013. }
  5014. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  5015. GB_ASSERT(type_size_of(type) == 4);
  5016. u32 u = bit_cast<u32>(f);
  5017. if (is_type_different_to_arch_endianness(type)) {
  5018. u = gb_endian_swap32(u);
  5019. }
  5020. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  5021. return LLVMConstBitCast(i, lb_type(m, type));
  5022. }
  5023. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  5024. x = lb_emit_conv(p, x, t);
  5025. y = lb_emit_conv(p, y, t);
  5026. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  5027. }
  5028. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  5029. x = lb_emit_conv(p, x, t);
  5030. y = lb_emit_conv(p, y, t);
  5031. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  5032. }
  5033. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  5034. lbValue z = {};
  5035. z = lb_emit_max(p, t, x, min);
  5036. z = lb_emit_min(p, t, z, max);
  5037. return z;
  5038. }
  5039. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  5040. StringHashKey key = string_hash_string(str);
  5041. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  5042. if (found != nullptr) {
  5043. return *found;
  5044. } else {
  5045. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5046. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  5047. cast(char const *)str.text,
  5048. cast(unsigned)str.len,
  5049. false);
  5050. isize max_len = 7+8+1;
  5051. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  5052. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  5053. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  5054. len -= 1;
  5055. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  5056. LLVMSetInitializer(global_data, data);
  5057. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  5058. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  5059. string_map_set(&m->const_strings, key, ptr);
  5060. return ptr;
  5061. }
  5062. }
  5063. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  5064. LLVMValueRef ptr = nullptr;
  5065. if (str.len != 0) {
  5066. ptr = lb_find_or_add_entity_string_ptr(m, str);
  5067. } else {
  5068. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  5069. }
  5070. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  5071. LLVMValueRef values[2] = {ptr, str_len};
  5072. lbValue res = {};
  5073. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  5074. res.type = t_string;
  5075. return res;
  5076. }
  5077. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  5078. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5079. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  5080. cast(char const *)str.text,
  5081. cast(unsigned)str.len,
  5082. false);
  5083. char *name = nullptr;
  5084. {
  5085. isize max_len = 7+8+1;
  5086. name = gb_alloc_array(permanent_allocator(), char, max_len);
  5087. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  5088. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  5089. len -= 1;
  5090. }
  5091. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  5092. LLVMSetInitializer(global_data, data);
  5093. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  5094. LLVMValueRef ptr = nullptr;
  5095. if (str.len != 0) {
  5096. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  5097. } else {
  5098. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  5099. }
  5100. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  5101. LLVMValueRef values[2] = {ptr, len};
  5102. lbValue res = {};
  5103. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  5104. res.type = t_u8_slice;
  5105. return res;
  5106. }
  5107. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  5108. isize index = type_info_index(info, type, false);
  5109. if (index >= 0) {
  5110. auto *set = &info->minimum_dependency_type_info_set;
  5111. for_array(i, set->entries) {
  5112. if (set->entries[i].ptr == index) {
  5113. return i+1;
  5114. }
  5115. }
  5116. }
  5117. if (err_on_not_found) {
  5118. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  5119. }
  5120. return -1;
  5121. }
  5122. lbValue lb_typeid(lbModule *m, Type *type) {
  5123. type = default_type(type);
  5124. u64 id = cast(u64)lb_type_info_index(m->info, type);
  5125. GB_ASSERT(id >= 0);
  5126. u64 kind = Typeid_Invalid;
  5127. u64 named = is_type_named(type) && type->kind != Type_Basic;
  5128. u64 special = 0;
  5129. u64 reserved = 0;
  5130. Type *bt = base_type(type);
  5131. TypeKind tk = bt->kind;
  5132. switch (tk) {
  5133. case Type_Basic: {
  5134. u32 flags = bt->Basic.flags;
  5135. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  5136. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  5137. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  5138. if (flags & BasicFlag_Float) kind = Typeid_Float;
  5139. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  5140. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  5141. if (flags & BasicFlag_String) kind = Typeid_String;
  5142. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  5143. } break;
  5144. case Type_Pointer: kind = Typeid_Pointer; break;
  5145. case Type_Array: kind = Typeid_Array; break;
  5146. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  5147. case Type_Slice: kind = Typeid_Slice; break;
  5148. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  5149. case Type_Map: kind = Typeid_Map; break;
  5150. case Type_Struct: kind = Typeid_Struct; break;
  5151. case Type_Enum: kind = Typeid_Enum; break;
  5152. case Type_Union: kind = Typeid_Union; break;
  5153. case Type_Tuple: kind = Typeid_Tuple; break;
  5154. case Type_Proc: kind = Typeid_Procedure; break;
  5155. case Type_BitSet: kind = Typeid_Bit_Set; break;
  5156. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  5157. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  5158. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  5159. }
  5160. if (is_type_cstring(type)) {
  5161. special = 1;
  5162. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  5163. special = 1;
  5164. }
  5165. u64 data = 0;
  5166. if (build_context.word_size == 4) {
  5167. GB_ASSERT(id <= (1u<<24u));
  5168. data |= (id &~ (1u<<24)) << 0u; // index
  5169. data |= (kind &~ (1u<<5)) << 24u; // kind
  5170. data |= (named &~ (1u<<1)) << 29u; // kind
  5171. data |= (special &~ (1u<<1)) << 30u; // kind
  5172. data |= (reserved &~ (1u<<1)) << 31u; // kind
  5173. } else {
  5174. GB_ASSERT(build_context.word_size == 8);
  5175. GB_ASSERT(id <= (1ull<<56u));
  5176. data |= (id &~ (1ull<<56)) << 0ul; // index
  5177. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  5178. data |= (named &~ (1ull<<1)) << 61ull; // kind
  5179. data |= (special &~ (1ull<<1)) << 62ull; // kind
  5180. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  5181. }
  5182. lbValue res = {};
  5183. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  5184. res.type = t_typeid;
  5185. return res;
  5186. }
  5187. lbValue lb_type_info(lbModule *m, Type *type) {
  5188. type = default_type(type);
  5189. isize index = lb_type_info_index(m->info, type);
  5190. GB_ASSERT(index >= 0);
  5191. LLVMTypeRef it = lb_type(m, t_int);
  5192. LLVMValueRef indices[2] = {
  5193. LLVMConstInt(it, 0, false),
  5194. LLVMConstInt(it, index, true),
  5195. };
  5196. lbValue value = {};
  5197. value.value = LLVMConstGEP(lb_global_type_info_data_ptr(m).value, indices, gb_count_of(indices));
  5198. value.type = t_type_info_ptr;
  5199. return value;
  5200. }
  5201. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  5202. bool is_local = allow_local && m->curr_procedure != nullptr;
  5203. bool is_const = true;
  5204. if (is_local) {
  5205. for (isize i = 0; i < count; i++) {
  5206. GB_ASSERT(values[i] != nullptr);
  5207. if (!LLVMIsConstant(values[i])) {
  5208. is_const = false;
  5209. break;
  5210. }
  5211. }
  5212. }
  5213. if (!is_const) {
  5214. lbProcedure *p = m->curr_procedure;
  5215. GB_ASSERT(p != nullptr);
  5216. lbAddr v = lb_add_local_generated(p, type, false);
  5217. lbValue ptr = lb_addr_get_ptr(p, v);
  5218. for (isize i = 0; i < count; i++) {
  5219. lbValue elem = lb_emit_array_epi(p, ptr, i);
  5220. LLVMBuildStore(p->builder, values[i], elem.value);
  5221. }
  5222. return lb_addr_load(p, v).value;
  5223. }
  5224. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  5225. }
  5226. lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  5227. GB_ASSERT(is_type_proc(e->type));
  5228. e = strip_entity_wrapping(e);
  5229. GB_ASSERT(e != nullptr);
  5230. auto *found = map_get(&m->values, hash_entity(e));
  5231. if (found) {
  5232. return *found;
  5233. }
  5234. bool ignore_body = false;
  5235. if (USE_SEPARTE_MODULES) {
  5236. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  5237. ignore_body = other_module != m;
  5238. }
  5239. lbProcedure *missing_proc = lb_create_procedure(m, e, ignore_body);
  5240. found = map_get(&m->values, hash_entity(e));
  5241. if (found) {
  5242. return *found;
  5243. }
  5244. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  5245. return {};
  5246. }
  5247. void lb_set_entity_from_other_modules_linkage_correctly(lbModule *other_module, Entity *e, String const &name) {
  5248. if (other_module == nullptr) {
  5249. return;
  5250. }
  5251. char const *cname = alloc_cstring(temporary_allocator(), name);
  5252. LLVMValueRef other_global = nullptr;
  5253. if (e->kind == Entity_Variable) {
  5254. other_global = LLVMGetNamedGlobal(other_module->mod, cname);
  5255. } else if (e->kind == Entity_Procedure) {
  5256. other_global = LLVMGetNamedFunction(other_module->mod, cname);
  5257. }
  5258. if (other_global) {
  5259. LLVMSetLinkage(other_global, LLVMExternalLinkage);
  5260. }
  5261. }
  5262. lbValue lb_find_value_from_entity(lbModule *m, Entity *e) {
  5263. e = strip_entity_wrapping(e);
  5264. GB_ASSERT(e != nullptr);
  5265. GB_ASSERT(e->token.string != "_");
  5266. if (e->kind == Entity_Procedure) {
  5267. return lb_find_procedure_value_from_entity(m, e);
  5268. }
  5269. auto *found = map_get(&m->values, hash_entity(e));
  5270. if (found) {
  5271. return *found;
  5272. }
  5273. if (USE_SEPARTE_MODULES) {
  5274. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  5275. // TODO(bill): correct this logic
  5276. bool is_external = other_module != m;
  5277. if (!is_external) {
  5278. if (e->code_gen_module != nullptr) {
  5279. other_module = e->code_gen_module;
  5280. } else {
  5281. other_module = nullptr;
  5282. }
  5283. is_external = other_module != m;
  5284. }
  5285. if (is_external) {
  5286. String name = lb_get_entity_name(other_module, e);
  5287. lbValue g = {};
  5288. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  5289. g.type = alloc_type_pointer(e->type);
  5290. lb_add_entity(m, e, g);
  5291. lb_add_member(m, name, g);
  5292. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  5293. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  5294. // LLVMSetLinkage(other_g.value, LLVMExternalLinkage);
  5295. if (e->Variable.thread_local_model != "") {
  5296. LLVMSetThreadLocal(g.value, true);
  5297. String m = e->Variable.thread_local_model;
  5298. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  5299. if (m == "default") {
  5300. mode = LLVMGeneralDynamicTLSModel;
  5301. } else if (m == "localdynamic") {
  5302. mode = LLVMLocalDynamicTLSModel;
  5303. } else if (m == "initialexec") {
  5304. mode = LLVMInitialExecTLSModel;
  5305. } else if (m == "localexec") {
  5306. mode = LLVMLocalExecTLSModel;
  5307. } else {
  5308. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  5309. }
  5310. LLVMSetThreadLocalMode(g.value, mode);
  5311. }
  5312. return g;
  5313. }
  5314. }
  5315. GB_PANIC("\n\tError in: %s, missing value %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  5316. return {};
  5317. }
  5318. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  5319. LLVMContextRef ctx = m->ctx;
  5320. type = default_type(type);
  5321. Type *original_type = type;
  5322. lbValue res = {};
  5323. res.type = original_type;
  5324. type = core_type(type);
  5325. value = convert_exact_value_for_type(value, type);
  5326. if (value.kind == ExactValue_Typeid) {
  5327. return lb_typeid(m, value.value_typeid);
  5328. }
  5329. if (value.kind == ExactValue_Invalid) {
  5330. return lb_const_nil(m, type);
  5331. }
  5332. if (value.kind == ExactValue_Procedure) {
  5333. Ast *expr = unparen_expr(value.value_procedure);
  5334. if (expr->kind == Ast_ProcLit) {
  5335. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5336. }
  5337. Entity *e = entity_from_expr(expr);
  5338. return lb_find_procedure_value_from_entity(m, e);
  5339. }
  5340. bool is_local = allow_local && m->curr_procedure != nullptr;
  5341. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  5342. if (is_type_slice(type)) {
  5343. if (value.kind == ExactValue_String) {
  5344. GB_ASSERT(is_type_u8_slice(type));
  5345. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  5346. return res;
  5347. } else {
  5348. ast_node(cl, CompoundLit, value.value_compound);
  5349. isize count = cl->elems.count;
  5350. if (count == 0) {
  5351. return lb_const_nil(m, type);
  5352. }
  5353. count = gb_max(cl->max_count, count);
  5354. Type *elem = base_type(type)->Slice.elem;
  5355. Type *t = alloc_type_array(elem, count);
  5356. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  5357. LLVMValueRef array_data = nullptr;
  5358. if (is_local) {
  5359. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  5360. // its backing data on the stack
  5361. lbProcedure *p = m->curr_procedure;
  5362. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  5363. LLVMTypeRef llvm_type = lb_type(m, t);
  5364. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  5365. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  5366. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  5367. LLVMBuildStore(p->builder, backing_array.value, array_data);
  5368. {
  5369. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5370. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  5371. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  5372. lbAddr slice = lb_add_local_generated(p, type, false);
  5373. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  5374. return lb_addr_load(p, slice);
  5375. }
  5376. } else {
  5377. isize max_len = 7+8+1;
  5378. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  5379. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_array_index, 1);
  5380. isize len = gb_snprintf(str, max_len, "csba$%x", id);
  5381. String name = make_string(cast(u8 *)str, len-1);
  5382. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  5383. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  5384. LLVMSetInitializer(array_data, backing_array.value);
  5385. lbValue g = {};
  5386. g.value = array_data;
  5387. g.type = t;
  5388. lb_add_entity(m, e, g);
  5389. lb_add_member(m, name, g);
  5390. {
  5391. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  5392. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  5393. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  5394. LLVMValueRef values[2] = {ptr, len};
  5395. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5396. return res;
  5397. }
  5398. }
  5399. }
  5400. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  5401. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  5402. i64 count = type->Array.count;
  5403. Type *elem = type->Array.elem;
  5404. LLVMTypeRef et = lb_type(m, elem);
  5405. Rune rune;
  5406. isize offset = 0;
  5407. isize width = 1;
  5408. String s = value.value_string;
  5409. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  5410. for (i64 i = 0; i < count && offset < s.len; i++) {
  5411. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  5412. offset += width;
  5413. elems[i] = LLVMConstInt(et, rune, true);
  5414. }
  5415. GB_ASSERT(offset == s.len);
  5416. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  5417. return res;
  5418. }
  5419. GB_PANIC("This should not have happened!\n");
  5420. LLVMValueRef data = LLVMConstStringInContext(ctx,
  5421. cast(char const *)value.value_string.text,
  5422. cast(unsigned)value.value_string.len,
  5423. false /*DontNullTerminate*/);
  5424. res.value = data;
  5425. return res;
  5426. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  5427. GB_ASSERT(type->Array.count == value.value_string.len);
  5428. LLVMValueRef data = LLVMConstStringInContext(ctx,
  5429. cast(char const *)value.value_string.text,
  5430. cast(unsigned)value.value_string.len,
  5431. true /*DontNullTerminate*/);
  5432. res.value = data;
  5433. return res;
  5434. } else if (is_type_array(type) &&
  5435. value.kind != ExactValue_Invalid &&
  5436. value.kind != ExactValue_String &&
  5437. value.kind != ExactValue_Compound) {
  5438. i64 count = type->Array.count;
  5439. Type *elem = type->Array.elem;
  5440. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  5441. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  5442. for (i64 i = 0; i < count; i++) {
  5443. elems[i] = single_elem.value;
  5444. }
  5445. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  5446. return res;
  5447. }
  5448. switch (value.kind) {
  5449. case ExactValue_Invalid:
  5450. res.value = LLVMConstNull(lb_type(m, original_type));
  5451. return res;
  5452. case ExactValue_Bool:
  5453. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  5454. return res;
  5455. case ExactValue_String:
  5456. {
  5457. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  5458. lbValue res = {};
  5459. res.type = default_type(original_type);
  5460. if (is_type_cstring(res.type)) {
  5461. res.value = ptr;
  5462. } else {
  5463. if (value.value_string.len == 0) {
  5464. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  5465. }
  5466. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  5467. LLVMValueRef values[2] = {ptr, str_len};
  5468. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5469. }
  5470. return res;
  5471. }
  5472. case ExactValue_Integer:
  5473. if (is_type_pointer(type)) {
  5474. unsigned len = cast(unsigned)value.value_integer.len;
  5475. LLVMTypeRef t = lb_type(m, original_type);
  5476. if (len == 0) {
  5477. res.value = LLVMConstNull(t);
  5478. } else {
  5479. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), len, big_int_ptr(&value.value_integer));
  5480. res.value = LLVMConstIntToPtr(i, t);
  5481. }
  5482. } else {
  5483. unsigned len = cast(unsigned)value.value_integer.len;
  5484. if (len == 0) {
  5485. res.value = LLVMConstNull(lb_type(m, original_type));
  5486. } else {
  5487. u64 *words = big_int_ptr(&value.value_integer);
  5488. if (is_type_different_to_arch_endianness(type)) {
  5489. // NOTE(bill): Swap byte order for different endianness
  5490. i64 sz = type_size_of(type);
  5491. isize byte_len = gb_size_of(u64)*len;
  5492. u8 *old_bytes = cast(u8 *)words;
  5493. // TODO(bill): Use a different allocator here for a temporary allocation
  5494. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  5495. for (i64 i = 0; i < sz; i++) {
  5496. new_bytes[i] = old_bytes[sz-1-i];
  5497. }
  5498. words = cast(u64 *)new_bytes;
  5499. }
  5500. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  5501. if (value.value_integer.neg) {
  5502. res.value = LLVMConstNeg(res.value);
  5503. }
  5504. }
  5505. }
  5506. return res;
  5507. case ExactValue_Float:
  5508. if (is_type_different_to_arch_endianness(type)) {
  5509. u64 u = bit_cast<u64>(value.value_float);
  5510. u = gb_endian_swap64(u);
  5511. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  5512. } else {
  5513. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  5514. }
  5515. return res;
  5516. case ExactValue_Complex:
  5517. {
  5518. LLVMValueRef values[2] = {};
  5519. switch (8*type_size_of(type)) {
  5520. case 32:
  5521. values[0] = lb_const_f16(m, cast(f32)value.value_complex->real);
  5522. values[1] = lb_const_f16(m, cast(f32)value.value_complex->imag);
  5523. break;
  5524. case 64:
  5525. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  5526. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  5527. break;
  5528. case 128:
  5529. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  5530. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  5531. break;
  5532. }
  5533. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  5534. return res;
  5535. }
  5536. break;
  5537. case ExactValue_Quaternion:
  5538. {
  5539. LLVMValueRef values[4] = {};
  5540. switch (8*type_size_of(type)) {
  5541. case 64:
  5542. // @QuaternionLayout
  5543. values[3] = lb_const_f16(m, cast(f32)value.value_quaternion->real);
  5544. values[0] = lb_const_f16(m, cast(f32)value.value_quaternion->imag);
  5545. values[1] = lb_const_f16(m, cast(f32)value.value_quaternion->jmag);
  5546. values[2] = lb_const_f16(m, cast(f32)value.value_quaternion->kmag);
  5547. break;
  5548. case 128:
  5549. // @QuaternionLayout
  5550. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  5551. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  5552. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  5553. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  5554. break;
  5555. case 256:
  5556. // @QuaternionLayout
  5557. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  5558. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  5559. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  5560. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  5561. break;
  5562. }
  5563. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  5564. return res;
  5565. }
  5566. break;
  5567. case ExactValue_Pointer:
  5568. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  5569. return res;
  5570. case ExactValue_Compound:
  5571. if (is_type_slice(type)) {
  5572. return lb_const_value(m, type, value, allow_local);
  5573. } else if (is_type_array(type)) {
  5574. ast_node(cl, CompoundLit, value.value_compound);
  5575. Type *elem_type = type->Array.elem;
  5576. isize elem_count = cl->elems.count;
  5577. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5578. return lb_const_nil(m, original_type);
  5579. }
  5580. if (cl->elems[0]->kind == Ast_FieldValue) {
  5581. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5582. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5583. isize value_index = 0;
  5584. for (i64 i = 0; i < type->Array.count; i++) {
  5585. bool found = false;
  5586. for (isize j = 0; j < elem_count; j++) {
  5587. Ast *elem = cl->elems[j];
  5588. ast_node(fv, FieldValue, elem);
  5589. if (is_ast_range(fv->field)) {
  5590. ast_node(ie, BinaryExpr, fv->field);
  5591. TypeAndValue lo_tav = ie->left->tav;
  5592. TypeAndValue hi_tav = ie->right->tav;
  5593. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5594. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5595. TokenKind op = ie->op.kind;
  5596. i64 lo = exact_value_to_i64(lo_tav.value);
  5597. i64 hi = exact_value_to_i64(hi_tav.value);
  5598. if (op != Token_RangeHalf) {
  5599. hi += 1;
  5600. }
  5601. if (lo == i) {
  5602. TypeAndValue tav = fv->value->tav;
  5603. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5604. for (i64 k = lo; k < hi; k++) {
  5605. values[value_index++] = val;
  5606. }
  5607. found = true;
  5608. i += (hi-lo-1);
  5609. break;
  5610. }
  5611. } else {
  5612. TypeAndValue index_tav = fv->field->tav;
  5613. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5614. i64 index = exact_value_to_i64(index_tav.value);
  5615. if (index == i) {
  5616. TypeAndValue tav = fv->value->tav;
  5617. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5618. values[value_index++] = val;
  5619. found = true;
  5620. break;
  5621. }
  5622. }
  5623. }
  5624. if (!found) {
  5625. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5626. }
  5627. }
  5628. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5629. return res;
  5630. } else {
  5631. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  5632. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  5633. for (isize i = 0; i < elem_count; i++) {
  5634. TypeAndValue tav = cl->elems[i]->tav;
  5635. GB_ASSERT(tav.mode != Addressing_Invalid);
  5636. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5637. }
  5638. for (isize i = elem_count; i < type->Array.count; i++) {
  5639. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5640. }
  5641. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  5642. return res;
  5643. }
  5644. } else if (is_type_enumerated_array(type)) {
  5645. ast_node(cl, CompoundLit, value.value_compound);
  5646. Type *elem_type = type->EnumeratedArray.elem;
  5647. isize elem_count = cl->elems.count;
  5648. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  5649. return lb_const_nil(m, original_type);
  5650. }
  5651. if (cl->elems[0]->kind == Ast_FieldValue) {
  5652. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  5653. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5654. isize value_index = 0;
  5655. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  5656. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  5657. for (i64 i = total_lo; i <= total_hi; i++) {
  5658. bool found = false;
  5659. for (isize j = 0; j < elem_count; j++) {
  5660. Ast *elem = cl->elems[j];
  5661. ast_node(fv, FieldValue, elem);
  5662. if (is_ast_range(fv->field)) {
  5663. ast_node(ie, BinaryExpr, fv->field);
  5664. TypeAndValue lo_tav = ie->left->tav;
  5665. TypeAndValue hi_tav = ie->right->tav;
  5666. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  5667. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  5668. TokenKind op = ie->op.kind;
  5669. i64 lo = exact_value_to_i64(lo_tav.value);
  5670. i64 hi = exact_value_to_i64(hi_tav.value);
  5671. if (op != Token_RangeHalf) {
  5672. hi += 1;
  5673. }
  5674. if (lo == i) {
  5675. TypeAndValue tav = fv->value->tav;
  5676. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5677. for (i64 k = lo; k < hi; k++) {
  5678. values[value_index++] = val;
  5679. }
  5680. found = true;
  5681. i += (hi-lo-1);
  5682. break;
  5683. }
  5684. } else {
  5685. TypeAndValue index_tav = fv->field->tav;
  5686. GB_ASSERT(index_tav.mode == Addressing_Constant);
  5687. i64 index = exact_value_to_i64(index_tav.value);
  5688. if (index == i) {
  5689. TypeAndValue tav = fv->value->tav;
  5690. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5691. values[value_index++] = val;
  5692. found = true;
  5693. break;
  5694. }
  5695. }
  5696. }
  5697. if (!found) {
  5698. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  5699. }
  5700. }
  5701. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5702. return res;
  5703. } else {
  5704. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  5705. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  5706. for (isize i = 0; i < elem_count; i++) {
  5707. TypeAndValue tav = cl->elems[i]->tav;
  5708. GB_ASSERT(tav.mode != Addressing_Invalid);
  5709. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5710. }
  5711. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  5712. values[i] = LLVMConstNull(lb_type(m, elem_type));
  5713. }
  5714. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  5715. return res;
  5716. }
  5717. } else if (is_type_simd_vector(type)) {
  5718. ast_node(cl, CompoundLit, value.value_compound);
  5719. Type *elem_type = type->SimdVector.elem;
  5720. isize elem_count = cl->elems.count;
  5721. if (elem_count == 0) {
  5722. return lb_const_nil(m, original_type);
  5723. }
  5724. GB_ASSERT(elem_type_can_be_constant(elem_type));
  5725. isize total_elem_count = type->SimdVector.count;
  5726. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  5727. for (isize i = 0; i < elem_count; i++) {
  5728. TypeAndValue tav = cl->elems[i]->tav;
  5729. GB_ASSERT(tav.mode != Addressing_Invalid);
  5730. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5731. }
  5732. LLVMTypeRef et = lb_type(m, elem_type);
  5733. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  5734. values[i] = LLVMConstNull(et);
  5735. }
  5736. for (isize i = 0; i< total_elem_count; i++) {
  5737. values[i] = llvm_const_cast(values[i], et);
  5738. }
  5739. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  5740. return res;
  5741. } else if (is_type_struct(type)) {
  5742. ast_node(cl, CompoundLit, value.value_compound);
  5743. if (cl->elems.count == 0) {
  5744. return lb_const_nil(m, original_type);
  5745. }
  5746. if (is_type_raw_union(type)) {
  5747. return lb_const_nil(m, original_type);
  5748. }
  5749. isize offset = 0;
  5750. if (type->Struct.custom_align > 0) {
  5751. offset = 1;
  5752. }
  5753. isize value_count = type->Struct.fields.count + offset;
  5754. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5755. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  5756. if (cl->elems.count > 0) {
  5757. if (cl->elems[0]->kind == Ast_FieldValue) {
  5758. isize elem_count = cl->elems.count;
  5759. for (isize i = 0; i < elem_count; i++) {
  5760. ast_node(fv, FieldValue, cl->elems[i]);
  5761. String name = fv->field->Ident.token.string;
  5762. TypeAndValue tav = fv->value->tav;
  5763. GB_ASSERT(tav.mode != Addressing_Invalid);
  5764. Selection sel = lookup_field(type, name, false);
  5765. Entity *f = type->Struct.fields[sel.index[0]];
  5766. if (elem_type_can_be_constant(f->type)) {
  5767. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  5768. visited[offset+f->Variable.field_index] = true;
  5769. }
  5770. }
  5771. } else {
  5772. for_array(i, cl->elems) {
  5773. Entity *f = type->Struct.fields[i];
  5774. TypeAndValue tav = cl->elems[i]->tav;
  5775. ExactValue val = {};
  5776. if (tav.mode != Addressing_Invalid) {
  5777. val = tav.value;
  5778. }
  5779. if (elem_type_can_be_constant(f->type)) {
  5780. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5781. visited[offset+f->Variable.field_index] = true;
  5782. }
  5783. }
  5784. }
  5785. }
  5786. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5787. if (!visited[offset+i]) {
  5788. GB_ASSERT(values[offset+i] == nullptr);
  5789. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5790. }
  5791. }
  5792. if (type->Struct.custom_align > 0) {
  5793. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5794. }
  5795. bool is_constant = true;
  5796. for (isize i = 0; i < value_count; i++) {
  5797. LLVMValueRef val = values[i];
  5798. if (!LLVMIsConstant(val)) {
  5799. GB_ASSERT(is_local);
  5800. GB_ASSERT(LLVMGetInstructionOpcode(val) == LLVMLoad);
  5801. is_constant = false;
  5802. }
  5803. }
  5804. if (is_constant) {
  5805. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5806. return res;
  5807. } else {
  5808. // TODO(bill): THIS IS HACK BUT IT WORKS FOR WHAT I NEED
  5809. LLVMValueRef *old_values = values;
  5810. LLVMValueRef *new_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5811. for (isize i = 0; i < value_count; i++) {
  5812. LLVMValueRef old_value = old_values[i];
  5813. if (LLVMIsConstant(old_value)) {
  5814. new_values[i] = old_value;
  5815. } else {
  5816. new_values[i] = LLVMConstNull(LLVMTypeOf(old_value));
  5817. }
  5818. }
  5819. LLVMValueRef constant_value = llvm_const_named_struct(lb_type(m, original_type), new_values, cast(unsigned)value_count);
  5820. GB_ASSERT(is_local);
  5821. lbProcedure *p = m->curr_procedure;
  5822. lbAddr v = lb_add_local_generated(p, res.type, true);
  5823. LLVMBuildStore(p->builder, constant_value, v.addr.value);
  5824. for (isize i = 0; i < value_count; i++) {
  5825. LLVMValueRef val = old_values[i];
  5826. if (!LLVMIsConstant(val)) {
  5827. LLVMValueRef dst = LLVMBuildStructGEP(p->builder, v.addr.value, cast(unsigned)i, "");
  5828. LLVMBuildStore(p->builder, val, dst);
  5829. }
  5830. }
  5831. return lb_addr_load(p, v);
  5832. }
  5833. } else if (is_type_bit_set(type)) {
  5834. ast_node(cl, CompoundLit, value.value_compound);
  5835. if (cl->elems.count == 0) {
  5836. return lb_const_nil(m, original_type);
  5837. }
  5838. i64 sz = type_size_of(type);
  5839. if (sz == 0) {
  5840. return lb_const_nil(m, original_type);
  5841. }
  5842. u64 bits = 0;
  5843. for_array(i, cl->elems) {
  5844. Ast *e = cl->elems[i];
  5845. GB_ASSERT(e->kind != Ast_FieldValue);
  5846. TypeAndValue tav = e->tav;
  5847. if (tav.mode != Addressing_Constant) {
  5848. continue;
  5849. }
  5850. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5851. i64 v = big_int_to_i64(&tav.value.value_integer);
  5852. i64 lower = type->BitSet.lower;
  5853. bits |= 1ull<<cast(u64)(v-lower);
  5854. }
  5855. if (is_type_different_to_arch_endianness(type)) {
  5856. i64 size = type_size_of(type);
  5857. switch (size) {
  5858. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5859. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5860. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5861. }
  5862. }
  5863. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5864. return res;
  5865. } else {
  5866. return lb_const_nil(m, original_type);
  5867. }
  5868. break;
  5869. case ExactValue_Procedure:
  5870. {
  5871. Ast *expr = value.value_procedure;
  5872. GB_ASSERT(expr != nullptr);
  5873. if (expr->kind == Ast_ProcLit) {
  5874. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5875. }
  5876. }
  5877. break;
  5878. case ExactValue_Typeid:
  5879. return lb_typeid(m, value.value_typeid);
  5880. }
  5881. return lb_const_nil(m, original_type);
  5882. }
  5883. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5884. lbModule *m = p->module;
  5885. LLVMValueRef fields[4] = {};
  5886. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5887. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5888. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5889. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5890. lbValue res = {};
  5891. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5892. res.type = t_source_code_location;
  5893. return res;
  5894. }
  5895. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5896. String proc_name = {};
  5897. if (p->entity) {
  5898. proc_name = p->entity->token.string;
  5899. }
  5900. TokenPos pos = {};
  5901. if (node) {
  5902. pos = ast_token(node).pos;
  5903. }
  5904. return lb_emit_source_code_location(p, proc_name, pos);
  5905. }
  5906. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5907. switch (op) {
  5908. case Token_Add:
  5909. return x;
  5910. case Token_Not: // Boolean not
  5911. case Token_Xor: // Bitwise not
  5912. case Token_Sub: // Number negation
  5913. break;
  5914. case Token_Pointer:
  5915. GB_PANIC("This should be handled elsewhere");
  5916. break;
  5917. }
  5918. if (is_type_array_like(x.type)) {
  5919. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5920. Type *tl = base_type(x.type);
  5921. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5922. GB_ASSERT(is_type_array_like(type));
  5923. Type *elem_type = base_array_type(type);
  5924. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5925. lbAddr res_addr = lb_add_local(p, type, nullptr, false, 0, true);
  5926. lbValue res = lb_addr_get_ptr(p, res_addr);
  5927. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5928. i32 count = cast(i32)get_array_type_count(tl);
  5929. LLVMTypeRef vector_type = nullptr;
  5930. if (op != Token_Not && lb_try_vector_cast(p->module, val, &vector_type)) {
  5931. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, val.value, LLVMPointerType(vector_type, 0), "");
  5932. LLVMValueRef v = LLVMBuildLoad2(p->builder, vector_type, vp, "");
  5933. LLVMValueRef opv = nullptr;
  5934. switch (op) {
  5935. case Token_Xor:
  5936. opv = LLVMBuildNot(p->builder, v, "");
  5937. break;
  5938. case Token_Sub:
  5939. if (is_type_float(elem_type)) {
  5940. opv = LLVMBuildFNeg(p->builder, v, "");
  5941. } else {
  5942. opv = LLVMBuildNeg(p->builder, v, "");
  5943. }
  5944. break;
  5945. }
  5946. if (opv != nullptr) {
  5947. LLVMSetAlignment(res.value, cast(unsigned)lb_alignof(vector_type));
  5948. LLVMValueRef res_ptr = LLVMBuildPointerCast(p->builder, res.value, LLVMPointerType(vector_type, 0), "");
  5949. LLVMBuildStore(p->builder, opv, res_ptr);
  5950. return lb_emit_conv(p, lb_emit_load(p, res), type);
  5951. }
  5952. }
  5953. if (inline_array_arith) {
  5954. // inline
  5955. for (i32 i = 0; i < count; i++) {
  5956. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5957. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5958. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5959. }
  5960. } else {
  5961. auto loop_data = lb_loop_start(p, count, t_i32);
  5962. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5963. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5964. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5965. lb_loop_end(p, loop_data);
  5966. }
  5967. return lb_emit_load(p, res);
  5968. }
  5969. if (op == Token_Xor) {
  5970. lbValue cmp = {};
  5971. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5972. cmp.type = x.type;
  5973. return lb_emit_conv(p, cmp, type);
  5974. }
  5975. if (op == Token_Not) {
  5976. lbValue cmp = {};
  5977. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5978. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5979. cmp.type = t_llvm_bool;
  5980. return lb_emit_conv(p, cmp, type);
  5981. }
  5982. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5983. Type *platform_type = integer_endian_type_to_platform_type(type);
  5984. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5985. lbValue res = {};
  5986. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5987. res.type = platform_type;
  5988. return lb_emit_byte_swap(p, res, type);
  5989. }
  5990. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5991. Type *platform_type = integer_endian_type_to_platform_type(type);
  5992. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5993. lbValue res = {};
  5994. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5995. res.type = platform_type;
  5996. return lb_emit_byte_swap(p, res, type);
  5997. }
  5998. lbValue res = {};
  5999. switch (op) {
  6000. case Token_Not: // Boolean not
  6001. case Token_Xor: // Bitwise not
  6002. res.value = LLVMBuildNot(p->builder, x.value, "");
  6003. res.type = x.type;
  6004. return res;
  6005. case Token_Sub: // Number negation
  6006. if (is_type_integer(x.type)) {
  6007. res.value = LLVMBuildNeg(p->builder, x.value, "");
  6008. } else if (is_type_float(x.type)) {
  6009. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  6010. } else if (is_type_complex(x.type)) {
  6011. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  6012. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  6013. lbAddr addr = lb_add_local_generated(p, x.type, false);
  6014. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  6015. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  6016. return lb_addr_load(p, addr);
  6017. } else if (is_type_quaternion(x.type)) {
  6018. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  6019. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  6020. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  6021. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  6022. lbAddr addr = lb_add_local_generated(p, x.type, false);
  6023. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  6024. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  6025. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  6026. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  6027. return lb_addr_load(p, addr);
  6028. } else {
  6029. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  6030. }
  6031. res.type = x.type;
  6032. return res;
  6033. }
  6034. return res;
  6035. }
  6036. bool lb_try_direct_vector_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type, lbValue *res_) {
  6037. GB_ASSERT(is_type_array_like(type));
  6038. Type *elem_type = base_array_type(type);
  6039. // NOTE(bill): Shift operations cannot be easily dealt with due to Odin's semantics
  6040. if (op == Token_Shl || op == Token_Shr) {
  6041. return false;
  6042. }
  6043. if (!LLVMIsALoadInst(lhs.value) || !LLVMIsALoadInst(rhs.value)) {
  6044. return false;
  6045. }
  6046. lbValue lhs_ptr = {};
  6047. lbValue rhs_ptr = {};
  6048. lhs_ptr.value = LLVMGetOperand(lhs.value, 0);
  6049. lhs_ptr.type = alloc_type_pointer(lhs.type);
  6050. rhs_ptr.value = LLVMGetOperand(rhs.value, 0);
  6051. rhs_ptr.type = alloc_type_pointer(rhs.type);
  6052. LLVMTypeRef vector_type0 = nullptr;
  6053. LLVMTypeRef vector_type1 = nullptr;
  6054. if (lb_try_vector_cast(p->module, lhs_ptr, &vector_type0) &&
  6055. lb_try_vector_cast(p->module, rhs_ptr, &vector_type1)) {
  6056. GB_ASSERT(vector_type0 == vector_type1);
  6057. LLVMTypeRef vector_type = vector_type0;
  6058. LLVMValueRef lhs_vp = LLVMBuildPointerCast(p->builder, lhs_ptr.value, LLVMPointerType(vector_type, 0), "");
  6059. LLVMValueRef rhs_vp = LLVMBuildPointerCast(p->builder, rhs_ptr.value, LLVMPointerType(vector_type, 0), "");
  6060. LLVMValueRef x = LLVMBuildLoad2(p->builder, vector_type, lhs_vp, "");
  6061. LLVMValueRef y = LLVMBuildLoad2(p->builder, vector_type, rhs_vp, "");
  6062. LLVMValueRef z = nullptr;
  6063. Type *integral_type = base_type(elem_type);
  6064. if (is_type_simd_vector(integral_type)) {
  6065. integral_type = core_array_type(integral_type);
  6066. }
  6067. if (is_type_bit_set(integral_type)) {
  6068. switch (op) {
  6069. case Token_Add: op = Token_Or; break;
  6070. case Token_Sub: op = Token_AndNot; break;
  6071. }
  6072. }
  6073. if (is_type_float(integral_type)) {
  6074. switch (op) {
  6075. case Token_Add:
  6076. z = LLVMBuildFAdd(p->builder, x, y, "");
  6077. break;
  6078. case Token_Sub:
  6079. z = LLVMBuildFSub(p->builder, x, y, "");
  6080. break;
  6081. case Token_Mul:
  6082. z = LLVMBuildFMul(p->builder, x, y, "");
  6083. break;
  6084. case Token_Quo:
  6085. z = LLVMBuildFDiv(p->builder, x, y, "");
  6086. break;
  6087. case Token_Mod:
  6088. z = LLVMBuildFRem(p->builder, x, y, "");
  6089. break;
  6090. default:
  6091. GB_PANIC("Unsupported vector operation");
  6092. break;
  6093. }
  6094. } else {
  6095. switch (op) {
  6096. case Token_Add:
  6097. z = LLVMBuildAdd(p->builder, x, y, "");
  6098. break;
  6099. case Token_Sub:
  6100. z = LLVMBuildSub(p->builder, x, y, "");
  6101. break;
  6102. case Token_Mul:
  6103. z = LLVMBuildMul(p->builder, x, y, "");
  6104. break;
  6105. case Token_Quo:
  6106. if (is_type_unsigned(integral_type)) {
  6107. z = LLVMBuildUDiv(p->builder, x, y, "");
  6108. } else {
  6109. z = LLVMBuildSDiv(p->builder, x, y, "");
  6110. }
  6111. break;
  6112. case Token_Mod:
  6113. if (is_type_unsigned(integral_type)) {
  6114. z = LLVMBuildURem(p->builder, x, y, "");
  6115. } else {
  6116. z = LLVMBuildSRem(p->builder, x, y, "");
  6117. }
  6118. break;
  6119. case Token_ModMod:
  6120. if (is_type_unsigned(integral_type)) {
  6121. z = LLVMBuildURem(p->builder, x, y, "");
  6122. } else {
  6123. LLVMValueRef a = LLVMBuildSRem(p->builder, x, y, "");
  6124. LLVMValueRef b = LLVMBuildAdd(p->builder, a, y, "");
  6125. z = LLVMBuildSRem(p->builder, b, y, "");
  6126. }
  6127. break;
  6128. case Token_And:
  6129. z = LLVMBuildAnd(p->builder, x, y, "");
  6130. break;
  6131. case Token_AndNot:
  6132. z = LLVMBuildAnd(p->builder, x, LLVMBuildNot(p->builder, y, ""), "");
  6133. break;
  6134. case Token_Or:
  6135. z = LLVMBuildOr(p->builder, x, y, "");
  6136. break;
  6137. case Token_Xor:
  6138. z = LLVMBuildXor(p->builder, x, y, "");
  6139. break;
  6140. default:
  6141. GB_PANIC("Unsupported vector operation");
  6142. break;
  6143. }
  6144. }
  6145. if (z != nullptr) {
  6146. lbAddr res = lb_add_local_generated_temp(p, type, lb_alignof(vector_type));
  6147. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, res.addr.value, LLVMPointerType(vector_type, 0), "");
  6148. LLVMBuildStore(p->builder, z, vp);
  6149. lbValue v = lb_addr_load(p, res);
  6150. if (res_) *res_ = v;
  6151. return true;
  6152. }
  6153. }
  6154. return false;
  6155. }
  6156. lbValue lb_emit_arith_array(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  6157. GB_ASSERT(is_type_array_like(lhs.type) || is_type_array_like(rhs.type));
  6158. lhs = lb_emit_conv(p, lhs, type);
  6159. rhs = lb_emit_conv(p, rhs, type);
  6160. GB_ASSERT(is_type_array_like(type));
  6161. Type *elem_type = base_array_type(type);
  6162. i64 count = get_array_type_count(type);
  6163. unsigned n = cast(unsigned)count;
  6164. // NOTE(bill, 2021-06-12): Try to do a direct operation as a vector, if possible
  6165. lbValue direct_vector_res = {};
  6166. if (lb_try_direct_vector_arith(p, op, lhs, rhs, type, &direct_vector_res)) {
  6167. return direct_vector_res;
  6168. }
  6169. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  6170. if (inline_array_arith) {
  6171. auto dst_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  6172. auto a_loads = slice_make<lbValue>(temporary_allocator(), n);
  6173. auto b_loads = slice_make<lbValue>(temporary_allocator(), n);
  6174. auto c_ops = slice_make<lbValue>(temporary_allocator(), n);
  6175. for (unsigned i = 0; i < n; i++) {
  6176. a_loads[i].value = LLVMBuildExtractValue(p->builder, lhs.value, i, "");
  6177. a_loads[i].type = elem_type;
  6178. }
  6179. for (unsigned i = 0; i < n; i++) {
  6180. b_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  6181. b_loads[i].type = elem_type;
  6182. }
  6183. for (unsigned i = 0; i < n; i++) {
  6184. c_ops[i] = lb_emit_arith(p, op, a_loads[i], b_loads[i], elem_type);
  6185. }
  6186. lbAddr res = lb_add_local_generated(p, type, false);
  6187. for (unsigned i = 0; i < n; i++) {
  6188. dst_ptrs[i] = lb_emit_array_epi(p, res.addr, i);
  6189. }
  6190. for (unsigned i = 0; i < n; i++) {
  6191. lb_emit_store(p, dst_ptrs[i], c_ops[i]);
  6192. }
  6193. return lb_addr_load(p, res);
  6194. } else {
  6195. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  6196. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  6197. lbAddr res = lb_add_local_generated(p, type, false);
  6198. auto loop_data = lb_loop_start(p, count, t_i32);
  6199. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  6200. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  6201. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  6202. lbValue a = lb_emit_load(p, a_ptr);
  6203. lbValue b = lb_emit_load(p, b_ptr);
  6204. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  6205. lb_emit_store(p, dst_ptr, c);
  6206. lb_loop_end(p, loop_data);
  6207. return lb_addr_load(p, res);
  6208. }
  6209. }
  6210. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  6211. lbModule *m = p->module;
  6212. if (is_type_array_like(lhs.type) || is_type_array_like(rhs.type)) {
  6213. return lb_emit_arith_array(p, op, lhs, rhs, type);
  6214. } else if (is_type_complex(type)) {
  6215. lhs = lb_emit_conv(p, lhs, type);
  6216. rhs = lb_emit_conv(p, rhs, type);
  6217. Type *ft = base_complex_elem_type(type);
  6218. if (op == Token_Quo) {
  6219. auto args = array_make<lbValue>(permanent_allocator(), 2);
  6220. args[0] = lhs;
  6221. args[1] = rhs;
  6222. switch (type_size_of(ft)) {
  6223. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  6224. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  6225. default: GB_PANIC("Unknown float type"); break;
  6226. }
  6227. }
  6228. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  6229. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  6230. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  6231. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  6232. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  6233. lbValue real = {};
  6234. lbValue imag = {};
  6235. switch (op) {
  6236. case Token_Add:
  6237. real = lb_emit_arith(p, Token_Add, a, c, ft);
  6238. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  6239. break;
  6240. case Token_Sub:
  6241. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  6242. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  6243. break;
  6244. case Token_Mul: {
  6245. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  6246. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  6247. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  6248. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  6249. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  6250. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  6251. break;
  6252. }
  6253. }
  6254. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  6255. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  6256. return lb_addr_load(p, res);
  6257. } else if (is_type_quaternion(type)) {
  6258. lhs = lb_emit_conv(p, lhs, type);
  6259. rhs = lb_emit_conv(p, rhs, type);
  6260. Type *ft = base_complex_elem_type(type);
  6261. if (op == Token_Add || op == Token_Sub) {
  6262. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  6263. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  6264. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  6265. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  6266. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  6267. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  6268. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  6269. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  6270. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  6271. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  6272. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  6273. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  6274. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  6275. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  6276. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  6277. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  6278. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  6279. return lb_addr_load(p, res);
  6280. } else if (op == Token_Mul) {
  6281. auto args = array_make<lbValue>(permanent_allocator(), 2);
  6282. args[0] = lhs;
  6283. args[1] = rhs;
  6284. switch (8*type_size_of(ft)) {
  6285. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  6286. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  6287. default: GB_PANIC("Unknown float type"); break;
  6288. }
  6289. } else if (op == Token_Quo) {
  6290. auto args = array_make<lbValue>(permanent_allocator(), 2);
  6291. args[0] = lhs;
  6292. args[1] = rhs;
  6293. switch (8*type_size_of(ft)) {
  6294. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  6295. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  6296. default: GB_PANIC("Unknown float type"); break;
  6297. }
  6298. }
  6299. }
  6300. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  6301. switch (op) {
  6302. case Token_AndNot:
  6303. case Token_And:
  6304. case Token_Or:
  6305. case Token_Xor:
  6306. goto handle_op;
  6307. }
  6308. Type *platform_type = integer_endian_type_to_platform_type(type);
  6309. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  6310. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  6311. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  6312. return lb_emit_byte_swap(p, res, type);
  6313. }
  6314. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  6315. Type *platform_type = integer_endian_type_to_platform_type(type);
  6316. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  6317. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  6318. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  6319. return lb_emit_byte_swap(p, res, type);
  6320. }
  6321. handle_op:
  6322. lhs = lb_emit_conv(p, lhs, type);
  6323. rhs = lb_emit_conv(p, rhs, type);
  6324. lbValue res = {};
  6325. res.type = type;
  6326. // NOTE(bill): Bit Set Aliases for + and -
  6327. if (is_type_bit_set(type)) {
  6328. switch (op) {
  6329. case Token_Add: op = Token_Or; break;
  6330. case Token_Sub: op = Token_AndNot; break;
  6331. }
  6332. }
  6333. Type *integral_type = type;
  6334. if (is_type_simd_vector(integral_type)) {
  6335. integral_type = core_array_type(integral_type);
  6336. }
  6337. switch (op) {
  6338. case Token_Add:
  6339. if (is_type_float(integral_type)) {
  6340. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  6341. return res;
  6342. }
  6343. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  6344. return res;
  6345. case Token_Sub:
  6346. if (is_type_float(integral_type)) {
  6347. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  6348. return res;
  6349. }
  6350. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  6351. return res;
  6352. case Token_Mul:
  6353. if (is_type_float(integral_type)) {
  6354. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  6355. return res;
  6356. }
  6357. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  6358. return res;
  6359. case Token_Quo:
  6360. if (is_type_float(integral_type)) {
  6361. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  6362. return res;
  6363. } else if (is_type_unsigned(integral_type)) {
  6364. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  6365. return res;
  6366. }
  6367. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  6368. return res;
  6369. case Token_Mod:
  6370. if (is_type_float(integral_type)) {
  6371. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  6372. return res;
  6373. } else if (is_type_unsigned(integral_type)) {
  6374. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  6375. return res;
  6376. }
  6377. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  6378. return res;
  6379. case Token_ModMod:
  6380. if (is_type_unsigned(integral_type)) {
  6381. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  6382. return res;
  6383. } else {
  6384. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  6385. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  6386. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  6387. res.value = c;
  6388. return res;
  6389. }
  6390. case Token_And:
  6391. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  6392. return res;
  6393. case Token_Or:
  6394. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  6395. return res;
  6396. case Token_Xor:
  6397. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  6398. return res;
  6399. case Token_Shl:
  6400. {
  6401. rhs = lb_emit_conv(p, rhs, lhs.type);
  6402. LLVMValueRef lhsval = lhs.value;
  6403. LLVMValueRef bits = rhs.value;
  6404. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  6405. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  6406. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  6407. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  6408. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  6409. return res;
  6410. }
  6411. case Token_Shr:
  6412. {
  6413. rhs = lb_emit_conv(p, rhs, lhs.type);
  6414. LLVMValueRef lhsval = lhs.value;
  6415. LLVMValueRef bits = rhs.value;
  6416. bool is_unsigned = is_type_unsigned(integral_type);
  6417. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  6418. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  6419. if (is_unsigned) {
  6420. res.value = LLVMBuildLShr(p->builder, lhsval, bits, "");
  6421. } else {
  6422. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  6423. }
  6424. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  6425. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  6426. return res;
  6427. }
  6428. case Token_AndNot:
  6429. {
  6430. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  6431. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  6432. return res;
  6433. }
  6434. break;
  6435. }
  6436. GB_PANIC("unhandled operator of lb_emit_arith");
  6437. return {};
  6438. }
  6439. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  6440. ast_node(be, BinaryExpr, expr);
  6441. TypeAndValue tv = type_and_value_of_expr(expr);
  6442. switch (be->op.kind) {
  6443. case Token_Add:
  6444. case Token_Sub:
  6445. case Token_Mul:
  6446. case Token_Quo:
  6447. case Token_Mod:
  6448. case Token_ModMod:
  6449. case Token_And:
  6450. case Token_Or:
  6451. case Token_Xor:
  6452. case Token_AndNot: {
  6453. Type *type = default_type(tv.type);
  6454. lbValue left = lb_build_expr(p, be->left);
  6455. lbValue right = lb_build_expr(p, be->right);
  6456. return lb_emit_arith(p, be->op.kind, left, right, type);
  6457. }
  6458. case Token_Shl:
  6459. case Token_Shr: {
  6460. lbValue left, right;
  6461. Type *type = default_type(tv.type);
  6462. left = lb_build_expr(p, be->left);
  6463. if (lb_is_expr_untyped_const(be->right)) {
  6464. // NOTE(bill): RHS shift operands can still be untyped
  6465. // Just bypass the standard lb_build_expr
  6466. right = lb_expr_untyped_const_to_typed(p->module, be->right, type);
  6467. } else {
  6468. right = lb_build_expr(p, be->right);
  6469. }
  6470. return lb_emit_arith(p, be->op.kind, left, right, type);
  6471. }
  6472. case Token_CmpEq:
  6473. case Token_NotEq:
  6474. case Token_Lt:
  6475. case Token_LtEq:
  6476. case Token_Gt:
  6477. case Token_GtEq:
  6478. {
  6479. lbValue left = {};
  6480. lbValue right = {};
  6481. if (be->left->tav.mode == Addressing_Type) {
  6482. left = lb_typeid(p->module, be->left->tav.type);
  6483. }
  6484. if (be->right->tav.mode == Addressing_Type) {
  6485. right = lb_typeid(p->module, be->right->tav.type);
  6486. }
  6487. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  6488. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  6489. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  6490. Type *type = default_type(tv.type);
  6491. return lb_emit_conv(p, cmp, type);
  6492. }
  6493. case Token_CmpAnd:
  6494. case Token_CmpOr:
  6495. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  6496. case Token_in:
  6497. case Token_not_in:
  6498. {
  6499. lbValue left = lb_build_expr(p, be->left);
  6500. Type *type = default_type(tv.type);
  6501. lbValue right = lb_build_expr(p, be->right);
  6502. Type *rt = base_type(right.type);
  6503. switch (rt->kind) {
  6504. case Type_Map:
  6505. {
  6506. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  6507. lbValue h = lb_gen_map_header(p, addr, rt);
  6508. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  6509. auto args = array_make<lbValue>(permanent_allocator(), 2);
  6510. args[0] = h;
  6511. args[1] = key;
  6512. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  6513. if (be->op.kind == Token_in) {
  6514. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  6515. } else {
  6516. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  6517. }
  6518. }
  6519. break;
  6520. case Type_BitSet:
  6521. {
  6522. Type *key_type = rt->BitSet.elem;
  6523. GB_ASSERT(are_types_identical(left.type, key_type));
  6524. Type *it = bit_set_to_int(rt);
  6525. left = lb_emit_conv(p, left, it);
  6526. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  6527. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  6528. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  6529. bit = lb_emit_conv(p, bit, it);
  6530. lbValue old_value = lb_emit_transmute(p, right, it);
  6531. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  6532. if (be->op.kind == Token_in) {
  6533. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  6534. } else {
  6535. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  6536. }
  6537. }
  6538. break;
  6539. default:
  6540. GB_PANIC("Invalid 'in' type");
  6541. }
  6542. break;
  6543. }
  6544. break;
  6545. default:
  6546. GB_PANIC("Invalid binary expression");
  6547. break;
  6548. }
  6549. return {};
  6550. }
  6551. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  6552. Type *prev_src = src;
  6553. // Type *prev_dst = dst;
  6554. src = base_type(type_deref(src));
  6555. // dst = base_type(type_deref(dst));
  6556. bool src_is_ptr = src != prev_src;
  6557. // bool dst_is_ptr = dst != prev_dst;
  6558. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  6559. for_array(i, src->Struct.fields) {
  6560. Entity *f = src->Struct.fields[i];
  6561. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  6562. if (are_types_identical(dst, f->type)) {
  6563. return f->token.string;
  6564. }
  6565. if (src_is_ptr && is_type_pointer(dst)) {
  6566. if (are_types_identical(type_deref(dst), f->type)) {
  6567. return f->token.string;
  6568. }
  6569. }
  6570. if (is_type_struct(f->type)) {
  6571. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  6572. if (name.len > 0) {
  6573. return name;
  6574. }
  6575. }
  6576. }
  6577. }
  6578. return str_lit("");
  6579. }
  6580. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  6581. GB_ASSERT(is_type_pointer(value.type));
  6582. GB_ASSERT(is_type_pointer(t));
  6583. GB_ASSERT(lb_is_const(value));
  6584. lbValue res = {};
  6585. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  6586. res.type = t;
  6587. return res;
  6588. }
  6589. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  6590. lbModule *m = p->module;
  6591. t = reduce_tuple_to_single_type(t);
  6592. Type *src_type = value.type;
  6593. if (are_types_identical(t, src_type)) {
  6594. return value;
  6595. }
  6596. Type *src = core_type(src_type);
  6597. Type *dst = core_type(t);
  6598. GB_ASSERT(src != nullptr);
  6599. GB_ASSERT(dst != nullptr);
  6600. if (is_type_untyped_nil(src)) {
  6601. return lb_const_nil(m, t);
  6602. }
  6603. if (is_type_untyped_undef(src)) {
  6604. return lb_const_undef(m, t);
  6605. }
  6606. if (LLVMIsConstant(value.value)) {
  6607. if (is_type_any(dst)) {
  6608. Type *st = default_type(src_type);
  6609. lbAddr default_value = lb_add_local_generated(p, st, false);
  6610. lb_addr_store(p, default_value, value);
  6611. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  6612. lbValue id = lb_typeid(m, st);
  6613. lbAddr res = lb_add_local_generated(p, t, false);
  6614. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  6615. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  6616. lb_emit_store(p, a0, data);
  6617. lb_emit_store(p, a1, id);
  6618. return lb_addr_load(p, res);
  6619. } else if (dst->kind == Type_Basic) {
  6620. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  6621. String str = lb_get_const_string(m, value);
  6622. lbValue res = {};
  6623. res.type = t;
  6624. res.value = llvm_cstring(m, str);
  6625. return res;
  6626. }
  6627. // if (is_type_float(dst)) {
  6628. // return value;
  6629. // } else if (is_type_integer(dst)) {
  6630. // return value;
  6631. // }
  6632. // ExactValue ev = value->Constant.value;
  6633. // if (is_type_float(dst)) {
  6634. // ev = exact_value_to_float(ev);
  6635. // } else if (is_type_complex(dst)) {
  6636. // ev = exact_value_to_complex(ev);
  6637. // } else if (is_type_quaternion(dst)) {
  6638. // ev = exact_value_to_quaternion(ev);
  6639. // } else if (is_type_string(dst)) {
  6640. // // Handled elsewhere
  6641. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  6642. // } else if (is_type_integer(dst)) {
  6643. // ev = exact_value_to_integer(ev);
  6644. // } else if (is_type_pointer(dst)) {
  6645. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  6646. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  6647. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  6648. // }
  6649. // return lb_const_value(p->module, t, ev);
  6650. }
  6651. }
  6652. if (are_types_identical(src, dst)) {
  6653. if (!are_types_identical(src_type, t)) {
  6654. return lb_emit_transmute(p, value, t);
  6655. }
  6656. return value;
  6657. }
  6658. // bool <-> llvm bool
  6659. if (is_type_boolean(src) && dst == t_llvm_bool) {
  6660. lbValue res = {};
  6661. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  6662. res.type = dst;
  6663. return res;
  6664. }
  6665. if (src == t_llvm_bool && is_type_boolean(dst)) {
  6666. lbValue res = {};
  6667. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  6668. res.type = dst;
  6669. return res;
  6670. }
  6671. // integer -> integer
  6672. if (is_type_integer(src) && is_type_integer(dst)) {
  6673. GB_ASSERT(src->kind == Type_Basic &&
  6674. dst->kind == Type_Basic);
  6675. i64 sz = type_size_of(default_type(src));
  6676. i64 dz = type_size_of(default_type(dst));
  6677. if (sz == dz) {
  6678. if (dz > 1 && !types_have_same_internal_endian(src, dst)) {
  6679. return lb_emit_byte_swap(p, value, t);
  6680. }
  6681. lbValue res = {};
  6682. res.value = value.value;
  6683. res.type = t;
  6684. return res;
  6685. }
  6686. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  6687. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6688. value = lb_emit_byte_swap(p, value, platform_src_type);
  6689. }
  6690. LLVMOpcode op = LLVMTrunc;
  6691. if (dz < sz) {
  6692. op = LLVMTrunc;
  6693. } else if (dz == sz) {
  6694. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  6695. // NOTE(bill): Copy the value just for type correctness
  6696. op = LLVMBitCast;
  6697. } else if (dz > sz) {
  6698. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  6699. }
  6700. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  6701. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6702. lbValue res = {};
  6703. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  6704. res.type = t;
  6705. return lb_emit_byte_swap(p, res, t);
  6706. } else {
  6707. lbValue res = {};
  6708. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  6709. res.type = t;
  6710. return res;
  6711. }
  6712. }
  6713. // boolean -> boolean/integer
  6714. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  6715. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  6716. lbValue res = {};
  6717. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  6718. res.type = t;
  6719. return res;
  6720. }
  6721. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  6722. return lb_emit_transmute(p, value, dst);
  6723. }
  6724. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  6725. return lb_emit_transmute(p, value, dst);
  6726. }
  6727. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  6728. return lb_emit_transmute(p, value, dst);
  6729. }
  6730. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  6731. return lb_emit_transmute(p, value, dst);
  6732. }
  6733. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  6734. lbValue c = lb_emit_conv(p, value, t_cstring);
  6735. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6736. args[0] = c;
  6737. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  6738. return lb_emit_conv(p, s, dst);
  6739. }
  6740. // integer -> boolean
  6741. if (is_type_integer(src) && is_type_boolean(dst)) {
  6742. lbValue res = {};
  6743. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  6744. res.type = t_llvm_bool;
  6745. return lb_emit_conv(p, res, t);
  6746. }
  6747. // float -> float
  6748. if (is_type_float(src) && is_type_float(dst)) {
  6749. i64 sz = type_size_of(src);
  6750. i64 dz = type_size_of(dst);
  6751. if (dz == sz) {
  6752. if (types_have_same_internal_endian(src, dst)) {
  6753. lbValue res = {};
  6754. res.type = t;
  6755. res.value = value.value;
  6756. return res;
  6757. } else {
  6758. return lb_emit_byte_swap(p, value, t);
  6759. }
  6760. }
  6761. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6762. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6763. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6764. lbValue res = {};
  6765. res = lb_emit_conv(p, value, platform_src_type);
  6766. res = lb_emit_conv(p, res, platform_dst_type);
  6767. if (is_type_different_to_arch_endianness(dst)) {
  6768. res = lb_emit_byte_swap(p, res, t);
  6769. }
  6770. return lb_emit_conv(p, res, t);
  6771. }
  6772. lbValue res = {};
  6773. res.type = t;
  6774. if (dz >= sz) {
  6775. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  6776. } else {
  6777. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  6778. }
  6779. return res;
  6780. }
  6781. if (is_type_complex(src) && is_type_complex(dst)) {
  6782. Type *ft = base_complex_elem_type(dst);
  6783. lbAddr gen = lb_add_local_generated(p, dst, false);
  6784. lbValue gp = lb_addr_get_ptr(p, gen);
  6785. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6786. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6787. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6788. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  6789. return lb_addr_load(p, gen);
  6790. }
  6791. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  6792. // @QuaternionLayout
  6793. Type *ft = base_complex_elem_type(dst);
  6794. lbAddr gen = lb_add_local_generated(p, dst, false);
  6795. lbValue gp = lb_addr_get_ptr(p, gen);
  6796. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6797. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6798. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  6799. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  6800. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  6801. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  6802. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  6803. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  6804. return lb_addr_load(p, gen);
  6805. }
  6806. if (is_type_float(src) && is_type_complex(dst)) {
  6807. Type *ft = base_complex_elem_type(dst);
  6808. lbAddr gen = lb_add_local_generated(p, dst, true);
  6809. lbValue gp = lb_addr_get_ptr(p, gen);
  6810. lbValue real = lb_emit_conv(p, value, ft);
  6811. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  6812. return lb_addr_load(p, gen);
  6813. }
  6814. if (is_type_float(src) && is_type_quaternion(dst)) {
  6815. Type *ft = base_complex_elem_type(dst);
  6816. lbAddr gen = lb_add_local_generated(p, dst, true);
  6817. lbValue gp = lb_addr_get_ptr(p, gen);
  6818. lbValue real = lb_emit_conv(p, value, ft);
  6819. // @QuaternionLayout
  6820. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6821. return lb_addr_load(p, gen);
  6822. }
  6823. if (is_type_complex(src) && is_type_quaternion(dst)) {
  6824. Type *ft = base_complex_elem_type(dst);
  6825. lbAddr gen = lb_add_local_generated(p, dst, true);
  6826. lbValue gp = lb_addr_get_ptr(p, gen);
  6827. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  6828. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  6829. // @QuaternionLayout
  6830. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  6831. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  6832. return lb_addr_load(p, gen);
  6833. }
  6834. // float <-> integer
  6835. if (is_type_float(src) && is_type_integer(dst)) {
  6836. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6837. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6838. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6839. lbValue res = {};
  6840. res = lb_emit_conv(p, value, platform_src_type);
  6841. res = lb_emit_conv(p, res, platform_dst_type);
  6842. if (is_type_different_to_arch_endianness(dst)) {
  6843. res = lb_emit_byte_swap(p, res, t);
  6844. }
  6845. return lb_emit_conv(p, res, t);
  6846. }
  6847. lbValue res = {};
  6848. res.type = t;
  6849. if (is_type_unsigned(dst)) {
  6850. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  6851. } else {
  6852. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  6853. }
  6854. return res;
  6855. }
  6856. if (is_type_integer(src) && is_type_float(dst)) {
  6857. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  6858. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  6859. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  6860. lbValue res = {};
  6861. res = lb_emit_conv(p, value, platform_src_type);
  6862. res = lb_emit_conv(p, res, platform_dst_type);
  6863. if (is_type_different_to_arch_endianness(dst)) {
  6864. res = lb_emit_byte_swap(p, res, t);
  6865. }
  6866. return lb_emit_conv(p, res, t);
  6867. }
  6868. if (is_type_integer_128bit(src)) {
  6869. auto args = array_make<lbValue>(temporary_allocator(), 1);
  6870. args[0] = value;
  6871. char const *call = "floattidf";
  6872. if (is_type_unsigned(src)) {
  6873. call = "floattidf_unsigned";
  6874. }
  6875. lbValue res_f64 = lb_emit_runtime_call(p, call, args);
  6876. return lb_emit_conv(p, res_f64, t);
  6877. }
  6878. lbValue res = {};
  6879. res.type = t;
  6880. if (is_type_unsigned(src)) {
  6881. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  6882. } else {
  6883. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  6884. }
  6885. return res;
  6886. }
  6887. // Pointer <-> uintptr
  6888. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6889. lbValue res = {};
  6890. res.type = t;
  6891. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6892. return res;
  6893. }
  6894. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6895. lbValue res = {};
  6896. res.type = t;
  6897. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6898. return res;
  6899. }
  6900. #if 1
  6901. if (is_type_union(dst)) {
  6902. for_array(i, dst->Union.variants) {
  6903. Type *vt = dst->Union.variants[i];
  6904. if (are_types_identical(vt, src_type)) {
  6905. lbAddr parent = lb_add_local_generated(p, t, true);
  6906. lb_emit_store_union_variant(p, parent.addr, value, vt);
  6907. return lb_addr_load(p, parent);
  6908. }
  6909. }
  6910. }
  6911. #endif
  6912. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  6913. // subtype polymorphism casting
  6914. if (check_is_assignable_to_using_subtype(src_type, t)) {
  6915. Type *st = type_deref(src_type);
  6916. Type *pst = st;
  6917. st = type_deref(st);
  6918. bool st_is_ptr = is_type_pointer(src_type);
  6919. st = base_type(st);
  6920. Type *dt = t;
  6921. bool dt_is_ptr = type_deref(dt) != dt;
  6922. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  6923. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  6924. if (field_name.len > 0) {
  6925. // NOTE(bill): It can be casted
  6926. Selection sel = lookup_field(st, field_name, false, true);
  6927. if (sel.entity != nullptr) {
  6928. if (st_is_ptr) {
  6929. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  6930. Type *rt = res.type;
  6931. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6932. res = lb_emit_load(p, res);
  6933. }
  6934. return res;
  6935. } else {
  6936. if (is_type_pointer(value.type)) {
  6937. Type *rt = value.type;
  6938. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  6939. value = lb_emit_load(p, value);
  6940. } else {
  6941. value = lb_emit_deep_field_gep(p, value, sel);
  6942. return lb_emit_load(p, value);
  6943. }
  6944. }
  6945. return lb_emit_deep_field_ev(p, value, sel);
  6946. }
  6947. } else {
  6948. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  6949. }
  6950. }
  6951. }
  6952. // Pointer <-> Pointer
  6953. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6954. lbValue res = {};
  6955. res.type = t;
  6956. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6957. return res;
  6958. }
  6959. // proc <-> proc
  6960. if (is_type_proc(src) && is_type_proc(dst)) {
  6961. lbValue res = {};
  6962. res.type = t;
  6963. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6964. return res;
  6965. }
  6966. // pointer -> proc
  6967. if (is_type_pointer(src) && is_type_proc(dst)) {
  6968. lbValue res = {};
  6969. res.type = t;
  6970. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6971. return res;
  6972. }
  6973. // proc -> pointer
  6974. if (is_type_proc(src) && is_type_pointer(dst)) {
  6975. lbValue res = {};
  6976. res.type = t;
  6977. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  6978. return res;
  6979. }
  6980. // []byte/[]u8 <-> string
  6981. if (is_type_u8_slice(src) && is_type_string(dst)) {
  6982. return lb_emit_transmute(p, value, t);
  6983. }
  6984. if (is_type_string(src) && is_type_u8_slice(dst)) {
  6985. return lb_emit_transmute(p, value, t);
  6986. }
  6987. if (is_type_array_like(dst)) {
  6988. Type *elem = base_array_type(dst);
  6989. lbValue e = lb_emit_conv(p, value, elem);
  6990. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6991. lbAddr v = lb_add_local_generated(p, t, false);
  6992. isize index_count = cast(isize)get_array_type_count(dst);
  6993. for (isize i = 0; i < index_count; i++) {
  6994. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  6995. lb_emit_store(p, elem, e);
  6996. }
  6997. return lb_addr_load(p, v);
  6998. }
  6999. if (is_type_any(dst)) {
  7000. if (is_type_untyped_nil(src)) {
  7001. return lb_const_nil(p->module, t);
  7002. }
  7003. if (is_type_untyped_undef(src)) {
  7004. return lb_const_undef(p->module, t);
  7005. }
  7006. lbAddr result = lb_add_local_generated(p, t, true);
  7007. Type *st = default_type(src_type);
  7008. lbValue data = lb_address_from_load_or_generate_local(p, value);
  7009. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  7010. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  7011. data = lb_emit_conv(p, data, t_rawptr);
  7012. lbValue id = lb_typeid(p->module, st);
  7013. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  7014. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  7015. lb_emit_store(p, any_data, data);
  7016. lb_emit_store(p, any_id, id);
  7017. return lb_addr_load(p, result);
  7018. }
  7019. i64 src_sz = type_size_of(src);
  7020. i64 dst_sz = type_size_of(dst);
  7021. if (src_sz == dst_sz) {
  7022. // bit_set <-> integer
  7023. if (is_type_integer(src) && is_type_bit_set(dst)) {
  7024. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  7025. res.type = dst;
  7026. return res;
  7027. }
  7028. if (is_type_bit_set(src) && is_type_integer(dst)) {
  7029. lbValue bs = value;
  7030. bs.type = bit_set_to_int(src);
  7031. return lb_emit_conv(p, bs, dst);
  7032. }
  7033. // typeid <-> integer
  7034. if (is_type_integer(src) && is_type_typeid(dst)) {
  7035. return lb_emit_transmute(p, value, dst);
  7036. }
  7037. if (is_type_typeid(src) && is_type_integer(dst)) {
  7038. return lb_emit_transmute(p, value, dst);
  7039. }
  7040. }
  7041. if (is_type_untyped(src)) {
  7042. if (is_type_string(src) && is_type_string(dst)) {
  7043. lbAddr result = lb_add_local_generated(p, t, false);
  7044. lb_addr_store(p, result, value);
  7045. return lb_addr_load(p, result);
  7046. }
  7047. }
  7048. gb_printf_err("%.*s\n", LIT(p->name));
  7049. gb_printf_err("lb_emit_conv: src -> dst\n");
  7050. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  7051. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  7052. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  7053. gb_printf_err("Not Identical %p != %p\n", src, dst);
  7054. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  7055. type_to_string(src_type), type_to_string(t),
  7056. LIT(p->name));
  7057. return {};
  7058. }
  7059. bool lb_is_type_aggregate(Type *t) {
  7060. t = base_type(t);
  7061. switch (t->kind) {
  7062. case Type_Basic:
  7063. switch (t->Basic.kind) {
  7064. case Basic_string:
  7065. case Basic_any:
  7066. return true;
  7067. case Basic_complex32:
  7068. case Basic_complex64:
  7069. case Basic_complex128:
  7070. case Basic_quaternion64:
  7071. case Basic_quaternion128:
  7072. case Basic_quaternion256:
  7073. return true;
  7074. }
  7075. break;
  7076. case Type_Pointer:
  7077. return false;
  7078. case Type_Array:
  7079. case Type_Slice:
  7080. case Type_Struct:
  7081. case Type_Union:
  7082. case Type_Tuple:
  7083. case Type_DynamicArray:
  7084. case Type_Map:
  7085. case Type_SimdVector:
  7086. return true;
  7087. case Type_Named:
  7088. return lb_is_type_aggregate(t->Named.base);
  7089. }
  7090. return false;
  7091. }
  7092. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  7093. Type *src_type = value.type;
  7094. if (are_types_identical(t, src_type)) {
  7095. return value;
  7096. }
  7097. lbValue res = {};
  7098. res.type = t;
  7099. Type *src = base_type(src_type);
  7100. Type *dst = base_type(t);
  7101. lbModule *m = p->module;
  7102. i64 sz = type_size_of(src);
  7103. i64 dz = type_size_of(dst);
  7104. if (sz != dz) {
  7105. LLVMTypeRef s = lb_type(m, src);
  7106. LLVMTypeRef d = lb_type(m, dst);
  7107. i64 llvm_sz = lb_sizeof(s);
  7108. i64 llvm_dz = lb_sizeof(d);
  7109. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  7110. }
  7111. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  7112. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  7113. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  7114. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  7115. return res;
  7116. }
  7117. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  7118. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  7119. return res;
  7120. }
  7121. if (is_type_uintptr(src) && is_type_proc(dst)) {
  7122. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  7123. return res;
  7124. }
  7125. if (is_type_proc(src) && is_type_uintptr(dst)) {
  7126. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  7127. return res;
  7128. }
  7129. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  7130. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  7131. return res;
  7132. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  7133. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  7134. return res;
  7135. }
  7136. if (is_type_pointer(src) && is_type_pointer(dst)) {
  7137. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  7138. return res;
  7139. }
  7140. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  7141. lbValue s = lb_address_from_load_or_generate_local(p, value);
  7142. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  7143. return lb_emit_load(p, d);
  7144. }
  7145. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  7146. return res;
  7147. }
  7148. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  7149. GB_ASSERT(addr.kind == lbAddr_Context);
  7150. GB_ASSERT(addr.ctx.sel.index.count == 0);
  7151. lbModule *m = p->module;
  7152. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7153. args[0] = addr.addr;
  7154. lb_emit_runtime_call(p, "__init_context", args);
  7155. }
  7156. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  7157. Type *pt = base_type(p->type);
  7158. GB_ASSERT(pt->kind == Type_Proc);
  7159. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  7160. String name = str_lit("__.context_ptr");
  7161. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  7162. e->flags |= EntityFlag_NoAlias;
  7163. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  7164. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  7165. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  7166. lbValue param = {context_ptr, e->type};
  7167. lb_add_entity(p->module, e, param);
  7168. lbAddr ctx_addr = {};
  7169. ctx_addr.kind = lbAddr_Context;
  7170. ctx_addr.addr = param;
  7171. lbContextData *cd = array_add_and_get(&p->context_stack);
  7172. cd->ctx = ctx_addr;
  7173. cd->scope_index = -1;
  7174. cd->uses = +1; // make sure it has been used already
  7175. return cd;
  7176. }
  7177. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  7178. ctx.kind = lbAddr_Context;
  7179. lbContextData *cd = array_add_and_get(&p->context_stack);
  7180. cd->ctx = ctx;
  7181. cd->scope_index = p->scope_index;
  7182. return cd;
  7183. }
  7184. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  7185. if (p->context_stack.count > 0) {
  7186. return p->context_stack[p->context_stack.count-1].ctx;
  7187. }
  7188. Type *pt = base_type(p->type);
  7189. GB_ASSERT(pt->kind == Type_Proc);
  7190. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  7191. lbAddr c = lb_add_local_generated(p, t_context, true);
  7192. c.kind = lbAddr_Context;
  7193. lb_emit_init_context(p, c);
  7194. lb_push_context_onto_stack(p, c);
  7195. lb_add_debug_context_variable(p, c);
  7196. return c;
  7197. }
  7198. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  7199. if (LLVMIsALoadInst(value.value)) {
  7200. lbValue res = {};
  7201. res.value = LLVMGetOperand(value.value, 0);
  7202. res.type = alloc_type_pointer(value.type);
  7203. return res;
  7204. }
  7205. GB_ASSERT(is_type_typed(value.type));
  7206. lbAddr res = lb_add_local_generated(p, value.type, false);
  7207. lb_addr_store(p, res, value);
  7208. return res.addr;
  7209. }
  7210. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  7211. if (LLVMIsALoadInst(value.value)) {
  7212. lbValue res = {};
  7213. res.value = LLVMGetOperand(value.value, 0);
  7214. res.type = alloc_type_pointer(value.type);
  7215. return res;
  7216. }
  7217. GB_PANIC("lb_address_from_load");
  7218. return {};
  7219. }
  7220. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  7221. i64 type_alignment = type_align_of(new_type);
  7222. if (alignment < type_alignment) {
  7223. alignment = type_alignment;
  7224. }
  7225. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  7226. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  7227. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  7228. lb_addr_store(p, ptr, val);
  7229. // ptr.kind = lbAddr_Context;
  7230. return ptr.addr;
  7231. }
  7232. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  7233. GB_ASSERT(is_type_pointer(s.type));
  7234. Type *t = base_type(type_deref(s.type));
  7235. Type *result_type = nullptr;
  7236. if (is_type_relative_pointer(t)) {
  7237. s = lb_addr_get_ptr(p, lb_addr(s));
  7238. }
  7239. if (is_type_struct(t)) {
  7240. result_type = get_struct_field_type(t, index);
  7241. } else if (is_type_union(t)) {
  7242. GB_ASSERT(index == -1);
  7243. return lb_emit_union_tag_ptr(p, s);
  7244. } else if (is_type_tuple(t)) {
  7245. GB_ASSERT(t->Tuple.variables.count > 0);
  7246. result_type = t->Tuple.variables[index]->type;
  7247. } else if (is_type_complex(t)) {
  7248. Type *ft = base_complex_elem_type(t);
  7249. switch (index) {
  7250. case 0: result_type = ft; break;
  7251. case 1: result_type = ft; break;
  7252. }
  7253. } else if (is_type_quaternion(t)) {
  7254. Type *ft = base_complex_elem_type(t);
  7255. switch (index) {
  7256. case 0: result_type = ft; break;
  7257. case 1: result_type = ft; break;
  7258. case 2: result_type = ft; break;
  7259. case 3: result_type = ft; break;
  7260. }
  7261. } else if (is_type_slice(t)) {
  7262. switch (index) {
  7263. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  7264. case 1: result_type = t_int; break;
  7265. }
  7266. } else if (is_type_string(t)) {
  7267. switch (index) {
  7268. case 0: result_type = t_u8_ptr; break;
  7269. case 1: result_type = t_int; break;
  7270. }
  7271. } else if (is_type_any(t)) {
  7272. switch (index) {
  7273. case 0: result_type = t_rawptr; break;
  7274. case 1: result_type = t_typeid; break;
  7275. }
  7276. } else if (is_type_dynamic_array(t)) {
  7277. switch (index) {
  7278. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  7279. case 1: result_type = t_int; break;
  7280. case 2: result_type = t_int; break;
  7281. case 3: result_type = t_allocator; break;
  7282. }
  7283. } else if (is_type_map(t)) {
  7284. init_map_internal_types(t);
  7285. Type *itp = alloc_type_pointer(t->Map.internal_type);
  7286. s = lb_emit_transmute(p, s, itp);
  7287. Type *gst = t->Map.internal_type;
  7288. GB_ASSERT(gst->kind == Type_Struct);
  7289. switch (index) {
  7290. case 0: result_type = get_struct_field_type(gst, 0); break;
  7291. case 1: result_type = get_struct_field_type(gst, 1); break;
  7292. }
  7293. } else if (is_type_array(t)) {
  7294. return lb_emit_array_epi(p, s, index);
  7295. } else if (is_type_relative_slice(t)) {
  7296. switch (index) {
  7297. case 0: result_type = t->RelativeSlice.base_integer; break;
  7298. case 1: result_type = t->RelativeSlice.base_integer; break;
  7299. }
  7300. } else {
  7301. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  7302. }
  7303. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  7304. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  7305. index += 1;
  7306. }
  7307. if (lb_is_const(s)) {
  7308. lbModule *m = p->module;
  7309. lbValue res = {};
  7310. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  7311. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  7312. res.type = alloc_type_pointer(result_type);
  7313. return res;
  7314. } else {
  7315. lbValue res = {};
  7316. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  7317. res.type = alloc_type_pointer(result_type);
  7318. return res;
  7319. }
  7320. }
  7321. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  7322. if (LLVMIsALoadInst(s.value)) {
  7323. lbValue res = {};
  7324. res.value = LLVMGetOperand(s.value, 0);
  7325. res.type = alloc_type_pointer(s.type);
  7326. lbValue ptr = lb_emit_struct_ep(p, res, index);
  7327. return lb_emit_load(p, ptr);
  7328. }
  7329. Type *t = base_type(s.type);
  7330. Type *result_type = nullptr;
  7331. switch (t->kind) {
  7332. case Type_Basic:
  7333. switch (t->Basic.kind) {
  7334. case Basic_string:
  7335. switch (index) {
  7336. case 0: result_type = t_u8_ptr; break;
  7337. case 1: result_type = t_int; break;
  7338. }
  7339. break;
  7340. case Basic_any:
  7341. switch (index) {
  7342. case 0: result_type = t_rawptr; break;
  7343. case 1: result_type = t_typeid; break;
  7344. }
  7345. break;
  7346. case Basic_complex32:
  7347. case Basic_complex64:
  7348. case Basic_complex128:
  7349. {
  7350. Type *ft = base_complex_elem_type(t);
  7351. switch (index) {
  7352. case 0: result_type = ft; break;
  7353. case 1: result_type = ft; break;
  7354. }
  7355. break;
  7356. }
  7357. case Basic_quaternion64:
  7358. case Basic_quaternion128:
  7359. case Basic_quaternion256:
  7360. {
  7361. Type *ft = base_complex_elem_type(t);
  7362. switch (index) {
  7363. case 0: result_type = ft; break;
  7364. case 1: result_type = ft; break;
  7365. case 2: result_type = ft; break;
  7366. case 3: result_type = ft; break;
  7367. }
  7368. break;
  7369. }
  7370. }
  7371. break;
  7372. case Type_Struct:
  7373. result_type = get_struct_field_type(t, index);
  7374. break;
  7375. case Type_Union:
  7376. GB_ASSERT(index == -1);
  7377. // return lb_emit_union_tag_value(p, s);
  7378. GB_PANIC("lb_emit_union_tag_value");
  7379. case Type_Tuple:
  7380. GB_ASSERT(t->Tuple.variables.count > 0);
  7381. result_type = t->Tuple.variables[index]->type;
  7382. if (t->Tuple.variables.count == 1) {
  7383. return s;
  7384. }
  7385. break;
  7386. case Type_Slice:
  7387. switch (index) {
  7388. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  7389. case 1: result_type = t_int; break;
  7390. }
  7391. break;
  7392. case Type_DynamicArray:
  7393. switch (index) {
  7394. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  7395. case 1: result_type = t_int; break;
  7396. case 2: result_type = t_int; break;
  7397. case 3: result_type = t_allocator; break;
  7398. }
  7399. break;
  7400. case Type_Map:
  7401. {
  7402. init_map_internal_types(t);
  7403. Type *gst = t->Map.generated_struct_type;
  7404. switch (index) {
  7405. case 0: result_type = get_struct_field_type(gst, 0); break;
  7406. case 1: result_type = get_struct_field_type(gst, 1); break;
  7407. }
  7408. }
  7409. break;
  7410. case Type_Array:
  7411. result_type = t->Array.elem;
  7412. break;
  7413. default:
  7414. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  7415. break;
  7416. }
  7417. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  7418. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  7419. index += 1;
  7420. }
  7421. lbValue res = {};
  7422. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  7423. res.type = result_type;
  7424. return res;
  7425. }
  7426. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  7427. GB_ASSERT(sel.index.count > 0);
  7428. Type *type = type_deref(e.type);
  7429. for_array(i, sel.index) {
  7430. i32 index = cast(i32)sel.index[i];
  7431. if (is_type_pointer(type)) {
  7432. type = type_deref(type);
  7433. e = lb_emit_load(p, e);
  7434. }
  7435. type = core_type(type);
  7436. if (is_type_quaternion(type)) {
  7437. e = lb_emit_struct_ep(p, e, index);
  7438. } else if (is_type_raw_union(type)) {
  7439. type = get_struct_field_type(type, index);
  7440. GB_ASSERT(is_type_pointer(e.type));
  7441. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  7442. } else if (is_type_struct(type)) {
  7443. type = get_struct_field_type(type, index);
  7444. e = lb_emit_struct_ep(p, e, index);
  7445. } else if (type->kind == Type_Union) {
  7446. GB_ASSERT(index == -1);
  7447. type = t_type_info_ptr;
  7448. e = lb_emit_struct_ep(p, e, index);
  7449. } else if (type->kind == Type_Tuple) {
  7450. type = type->Tuple.variables[index]->type;
  7451. e = lb_emit_struct_ep(p, e, index);
  7452. } else if (type->kind == Type_Basic) {
  7453. switch (type->Basic.kind) {
  7454. case Basic_any: {
  7455. if (index == 0) {
  7456. type = t_rawptr;
  7457. } else if (index == 1) {
  7458. type = t_type_info_ptr;
  7459. }
  7460. e = lb_emit_struct_ep(p, e, index);
  7461. break;
  7462. }
  7463. case Basic_string:
  7464. e = lb_emit_struct_ep(p, e, index);
  7465. break;
  7466. default:
  7467. GB_PANIC("un-gep-able type %s", type_to_string(type));
  7468. break;
  7469. }
  7470. } else if (type->kind == Type_Slice) {
  7471. e = lb_emit_struct_ep(p, e, index);
  7472. } else if (type->kind == Type_DynamicArray) {
  7473. e = lb_emit_struct_ep(p, e, index);
  7474. } else if (type->kind == Type_Array) {
  7475. e = lb_emit_array_epi(p, e, index);
  7476. } else if (type->kind == Type_Map) {
  7477. e = lb_emit_struct_ep(p, e, index);
  7478. } else if (type->kind == Type_RelativePointer) {
  7479. e = lb_emit_struct_ep(p, e, index);
  7480. } else {
  7481. GB_PANIC("un-gep-able type %s", type_to_string(type));
  7482. }
  7483. }
  7484. return e;
  7485. }
  7486. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  7487. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  7488. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  7489. return lb_emit_load(p, res);
  7490. }
  7491. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  7492. if (p->curr_block == nullptr) {
  7493. return;
  7494. }
  7495. // NOTE(bill): The prev block may defer injection before it's terminator
  7496. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  7497. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  7498. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  7499. return;
  7500. }
  7501. isize prev_context_stack_count = p->context_stack.count;
  7502. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  7503. defer (p->context_stack.count = prev_context_stack_count);
  7504. p->context_stack.count = d.context_stack_count;
  7505. lbBlock *b = lb_create_block(p, "defer");
  7506. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  7507. lb_emit_jump(p, b);
  7508. }
  7509. lb_start_block(p, b);
  7510. if (d.kind == lbDefer_Node) {
  7511. lb_build_stmt(p, d.stmt);
  7512. } else if (d.kind == lbDefer_Instr) {
  7513. // NOTE(bill): Need to make a new copy
  7514. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  7515. LLVMInsertIntoBuilder(p->builder, instr);
  7516. } else if (d.kind == lbDefer_Proc) {
  7517. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  7518. }
  7519. }
  7520. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  7521. isize count = p->defer_stmts.count;
  7522. isize i = count;
  7523. while (i --> 0) {
  7524. lbDefer const &d = p->defer_stmts[i];
  7525. if (kind == lbDeferExit_Default) {
  7526. if (p->scope_index == d.scope_index &&
  7527. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  7528. lb_build_defer_stmt(p, d);
  7529. array_pop(&p->defer_stmts);
  7530. continue;
  7531. } else {
  7532. break;
  7533. }
  7534. } else if (kind == lbDeferExit_Return) {
  7535. lb_build_defer_stmt(p, d);
  7536. } else if (kind == lbDeferExit_Branch) {
  7537. GB_ASSERT(block != nullptr);
  7538. isize lower_limit = block->scope_index;
  7539. if (lower_limit < d.scope_index) {
  7540. lb_build_defer_stmt(p, d);
  7541. }
  7542. }
  7543. }
  7544. }
  7545. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  7546. Type *pt = base_type(p->type);
  7547. GB_ASSERT(pt->kind == Type_Proc);
  7548. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7549. GB_ASSERT(p->context_stack.count != 0);
  7550. }
  7551. lbDefer *d = array_add_and_get(&p->defer_stmts);
  7552. d->kind = lbDefer_Node;
  7553. d->scope_index = scope_index;
  7554. d->context_stack_count = p->context_stack.count;
  7555. d->block = p->curr_block;
  7556. d->stmt = stmt;
  7557. }
  7558. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  7559. Type *pt = base_type(p->type);
  7560. GB_ASSERT(pt->kind == Type_Proc);
  7561. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7562. GB_ASSERT(p->context_stack.count != 0);
  7563. }
  7564. lbDefer *d = array_add_and_get(&p->defer_stmts);
  7565. d->kind = lbDefer_Proc;
  7566. d->scope_index = p->scope_index;
  7567. d->block = p->curr_block;
  7568. d->context_stack_count = p->context_stack.count;
  7569. d->proc.deferred = deferred;
  7570. d->proc.result_as_args = result_as_args;
  7571. }
  7572. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  7573. Array<lbValue> array = {};
  7574. Type *t = base_type(value.type);
  7575. if (t == nullptr) {
  7576. // Do nothing
  7577. } else if (is_type_tuple(t)) {
  7578. GB_ASSERT(t->kind == Type_Tuple);
  7579. auto *rt = &t->Tuple;
  7580. if (rt->variables.count > 0) {
  7581. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  7582. for_array(i, rt->variables) {
  7583. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  7584. array[i] = elem;
  7585. }
  7586. }
  7587. } else {
  7588. array = array_make<lbValue>(permanent_allocator(), 1);
  7589. array[0] = value;
  7590. }
  7591. return array;
  7592. }
  7593. 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) {
  7594. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  7595. unsigned arg_count = cast(unsigned)processed_args.count;
  7596. if (return_ptr.value != nullptr) {
  7597. arg_count += 1;
  7598. }
  7599. if (context_ptr.addr.value != nullptr) {
  7600. arg_count += 1;
  7601. }
  7602. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  7603. isize arg_index = 0;
  7604. if (return_ptr.value != nullptr) {
  7605. args[arg_index++] = return_ptr.value;
  7606. }
  7607. for_array(i, processed_args) {
  7608. lbValue arg = processed_args[i];
  7609. args[arg_index++] = arg.value;
  7610. }
  7611. if (context_ptr.addr.value != nullptr) {
  7612. LLVMValueRef cp = context_ptr.addr.value;
  7613. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  7614. args[arg_index++] = cp;
  7615. }
  7616. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  7617. GB_ASSERT(curr_block != p->decl_block->block);
  7618. {
  7619. LLVMTypeRef ftp = lb_type(p->module, value.type);
  7620. LLVMTypeRef ft = LLVMGetElementType(ftp);
  7621. LLVMValueRef fn = value.value;
  7622. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  7623. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  7624. }
  7625. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  7626. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  7627. {
  7628. unsigned param_count = LLVMCountParamTypes(fnp);
  7629. GB_ASSERT(arg_count >= param_count);
  7630. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  7631. LLVMGetParamTypes(fnp, param_types);
  7632. for (unsigned i = 0; i < param_count; i++) {
  7633. LLVMTypeRef param_type = param_types[i];
  7634. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  7635. GB_ASSERT_MSG(
  7636. arg_type == param_type,
  7637. "Parameter types do not match: %s != %s, argument: %s",
  7638. LLVMPrintTypeToString(arg_type),
  7639. LLVMPrintTypeToString(param_type),
  7640. LLVMPrintValueToString(args[i])
  7641. );
  7642. }
  7643. }
  7644. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  7645. switch (inlining) {
  7646. case ProcInlining_none:
  7647. break;
  7648. case ProcInlining_inline:
  7649. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  7650. break;
  7651. case ProcInlining_no_inline:
  7652. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  7653. break;
  7654. }
  7655. lbValue res = {};
  7656. res.value = ret;
  7657. res.type = abi_rt;
  7658. return res;
  7659. }
  7660. }
  7661. lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7662. AstPackage *pkg = m->info->runtime_package;
  7663. Entity *e = scope_lookup_current(pkg->scope, name);
  7664. return lb_find_procedure_value_from_entity(m, e);
  7665. }
  7666. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  7667. String name = make_string_c(c_name);
  7668. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  7669. return lb_emit_call(p, proc, args);
  7670. }
  7671. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_copy_elision_hint) {
  7672. lbModule *m = p->module;
  7673. Type *pt = base_type(value.type);
  7674. GB_ASSERT(pt->kind == Type_Proc);
  7675. Type *results = pt->Proc.results;
  7676. if (p->entity != nullptr) {
  7677. if (p->entity->flags & EntityFlag_Disabled) {
  7678. return {};
  7679. }
  7680. }
  7681. lbAddr context_ptr = {};
  7682. if (pt->Proc.calling_convention == ProcCC_Odin) {
  7683. context_ptr = lb_find_or_generate_context_ptr(p);
  7684. }
  7685. defer (if (pt->Proc.diverging) {
  7686. LLVMBuildUnreachable(p->builder);
  7687. });
  7688. bool is_c_vararg = pt->Proc.c_vararg;
  7689. isize param_count = pt->Proc.param_count;
  7690. if (is_c_vararg) {
  7691. GB_ASSERT(param_count-1 <= args.count);
  7692. param_count -= 1;
  7693. } else {
  7694. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  7695. }
  7696. lbValue result = {};
  7697. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  7698. {
  7699. lbFunctionType *ft = lb_get_function_type(m, p, pt);
  7700. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  7701. unsigned param_index = 0;
  7702. for (isize i = 0; i < param_count; i++) {
  7703. Entity *e = pt->Proc.params->Tuple.variables[i];
  7704. if (e->kind != Entity_Variable) {
  7705. continue;
  7706. }
  7707. GB_ASSERT(e->flags & EntityFlag_Param);
  7708. Type *original_type = e->type;
  7709. lbArgType *arg = &ft->args[param_index];
  7710. if (arg->kind == lbArg_Ignore) {
  7711. continue;
  7712. }
  7713. lbValue x = lb_emit_conv(p, args[i], original_type);
  7714. LLVMTypeRef xt = lb_type(p->module, x.type);
  7715. if (arg->kind == lbArg_Direct) {
  7716. LLVMTypeRef abi_type = arg->cast_type;
  7717. if (!abi_type) {
  7718. abi_type = arg->type;
  7719. }
  7720. if (xt == abi_type) {
  7721. array_add(&processed_args, x);
  7722. } else {
  7723. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  7724. array_add(&processed_args, x);
  7725. }
  7726. } else if (arg->kind == lbArg_Indirect) {
  7727. lbValue ptr = {};
  7728. if (arg->is_byval) {
  7729. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  7730. } else if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  7731. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  7732. // i.e. `T const &` in C++
  7733. ptr = lb_address_from_load_or_generate_local(p, x);
  7734. } else {
  7735. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  7736. }
  7737. array_add(&processed_args, ptr);
  7738. }
  7739. param_index += 1;
  7740. }
  7741. if (is_c_vararg) {
  7742. for (isize i = processed_args.count; i < args.count; i++) {
  7743. array_add(&processed_args, args[i]);
  7744. }
  7745. }
  7746. if (inlining == ProcInlining_none) {
  7747. inlining = p->inlining;
  7748. }
  7749. Type *rt = reduce_tuple_to_single_type(results);
  7750. if (return_by_pointer) {
  7751. lbValue return_ptr = {};
  7752. if (use_copy_elision_hint && p->copy_elision_hint.ptr.value != nullptr) {
  7753. if (are_types_identical(type_deref(p->copy_elision_hint.ptr.type), rt)) {
  7754. return_ptr = lb_consume_copy_elision_hint(p);
  7755. }
  7756. }
  7757. if (return_ptr.value == nullptr) {
  7758. lbAddr r = lb_add_local_generated(p, rt, true);
  7759. return_ptr = r.addr;
  7760. }
  7761. GB_ASSERT(is_type_pointer(return_ptr.type));
  7762. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  7763. result = lb_emit_load(p, return_ptr);
  7764. } else if (rt != nullptr) {
  7765. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  7766. if (ft->ret.cast_type) {
  7767. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  7768. }
  7769. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  7770. result.type = rt;
  7771. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  7772. result.type = t_llvm_bool;
  7773. }
  7774. if (!is_type_tuple(rt)) {
  7775. result = lb_emit_conv(p, result, rt);
  7776. }
  7777. } else {
  7778. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  7779. }
  7780. }
  7781. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  7782. if (found != nullptr) {
  7783. Entity *e = *found;
  7784. if (e != nullptr && entity_has_deferred_procedure(e)) {
  7785. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  7786. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  7787. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  7788. auto in_args = args;
  7789. Array<lbValue> result_as_args = {};
  7790. switch (kind) {
  7791. case DeferredProcedure_none:
  7792. break;
  7793. case DeferredProcedure_in:
  7794. result_as_args = in_args;
  7795. break;
  7796. case DeferredProcedure_out:
  7797. result_as_args = lb_value_to_array(p, result);
  7798. break;
  7799. case DeferredProcedure_in_out:
  7800. {
  7801. auto out_args = lb_value_to_array(p, result);
  7802. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  7803. array_copy(&result_as_args, in_args, 0);
  7804. array_copy(&result_as_args, out_args, in_args.count);
  7805. }
  7806. break;
  7807. }
  7808. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  7809. }
  7810. }
  7811. return result;
  7812. }
  7813. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  7814. Type *t = s.type;
  7815. GB_ASSERT(is_type_pointer(t));
  7816. Type *st = base_type(type_deref(t));
  7817. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7818. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  7819. LLVMValueRef indices[2] = {};
  7820. indices[0] = llvm_zero(p->module);
  7821. indices[1] = lb_emit_conv(p, index, t_int).value;
  7822. Type *ptr = base_array_type(st);
  7823. lbValue res = {};
  7824. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  7825. res.type = alloc_type_pointer(ptr);
  7826. return res;
  7827. }
  7828. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  7829. Type *t = s.type;
  7830. GB_ASSERT(is_type_pointer(t));
  7831. Type *st = base_type(type_deref(t));
  7832. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  7833. GB_ASSERT(0 <= index);
  7834. Type *ptr = base_array_type(st);
  7835. LLVMValueRef indices[2] = {
  7836. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  7837. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  7838. };
  7839. lbValue res = {};
  7840. if (lb_is_const(s)) {
  7841. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  7842. } else {
  7843. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  7844. }
  7845. res.type = alloc_type_pointer(ptr);
  7846. return res;
  7847. }
  7848. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  7849. LLVMValueRef indices[1] = {index.value};
  7850. lbValue res = {};
  7851. res.type = ptr.type;
  7852. if (lb_is_const(ptr) && lb_is_const(index)) {
  7853. res.value = LLVMConstGEP(ptr.value, indices, 1);
  7854. } else {
  7855. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  7856. }
  7857. return res;
  7858. }
  7859. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  7860. GB_ASSERT(is_type_pointer(data.type));
  7861. GB_ASSERT(are_types_identical(len.type, t_int));
  7862. LLVMValueRef vals[2] = {
  7863. data.value,
  7864. len.value,
  7865. };
  7866. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  7867. }
  7868. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  7869. Type *t = lb_addr_type(slice);
  7870. GB_ASSERT(is_type_slice(t));
  7871. lbValue ptr = lb_addr_get_ptr(p, slice);
  7872. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7873. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7874. }
  7875. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  7876. Type *t = lb_addr_type(string);
  7877. GB_ASSERT(is_type_string(t));
  7878. lbValue ptr = lb_addr_get_ptr(p, string);
  7879. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  7880. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  7881. }
  7882. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  7883. Type *t = base_type(string.type);
  7884. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  7885. return lb_emit_struct_ev(p, string, 0);
  7886. }
  7887. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  7888. Type *t = base_type(string.type);
  7889. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  7890. return lb_emit_struct_ev(p, string, 1);
  7891. }
  7892. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  7893. GB_ASSERT(is_type_cstring(value.type));
  7894. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7895. args[0] = lb_emit_conv(p, value, t_cstring);
  7896. return lb_emit_runtime_call(p, "cstring_len", args);
  7897. }
  7898. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  7899. Type *t = type_deref(array_ptr.type);
  7900. GB_ASSERT(is_type_array(t));
  7901. return lb_emit_struct_ep(p, array_ptr, 0);
  7902. }
  7903. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  7904. GB_ASSERT(is_type_slice(slice.type));
  7905. return lb_emit_struct_ev(p, slice, 0);
  7906. }
  7907. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  7908. GB_ASSERT(is_type_slice(slice.type));
  7909. return lb_emit_struct_ev(p, slice, 1);
  7910. }
  7911. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  7912. GB_ASSERT(is_type_dynamic_array(da.type));
  7913. return lb_emit_struct_ev(p, da, 0);
  7914. }
  7915. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  7916. GB_ASSERT(is_type_dynamic_array(da.type));
  7917. return lb_emit_struct_ev(p, da, 1);
  7918. }
  7919. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  7920. GB_ASSERT(is_type_dynamic_array(da.type));
  7921. return lb_emit_struct_ev(p, da, 2);
  7922. }
  7923. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  7924. GB_ASSERT(is_type_dynamic_array(da.type));
  7925. return lb_emit_struct_ev(p, da, 3);
  7926. }
  7927. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  7928. Type *t = base_type(value.type);
  7929. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7930. init_map_internal_types(t);
  7931. Type *gst = t->Map.generated_struct_type;
  7932. i32 index = 1;
  7933. lbValue entries = lb_emit_struct_ev(p, value, index);
  7934. return entries;
  7935. }
  7936. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  7937. Type *t = base_type(type_deref(value.type));
  7938. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  7939. init_map_internal_types(t);
  7940. Type *gst = t->Map.generated_struct_type;
  7941. i32 index = 1;
  7942. lbValue entries = lb_emit_struct_ep(p, value, index);
  7943. return entries;
  7944. }
  7945. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  7946. lbValue entries = lb_map_entries(p, value);
  7947. return lb_dynamic_array_len(p, entries);
  7948. }
  7949. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  7950. lbValue entries = lb_map_entries(p, value);
  7951. return lb_dynamic_array_cap(p, entries);
  7952. }
  7953. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  7954. Type *t = base_type(value.type);
  7955. bool is_ptr = false;
  7956. if (is_type_pointer(t)) {
  7957. is_ptr = true;
  7958. t = base_type(type_deref(t));
  7959. }
  7960. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7961. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7962. }
  7963. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  7964. t->Struct.soa_kind == StructSoa_Dynamic);
  7965. isize n = 0;
  7966. Type *elem = base_type(t->Struct.soa_elem);
  7967. if (elem->kind == Type_Struct) {
  7968. n = elem->Struct.fields.count;
  7969. } else if (elem->kind == Type_Array) {
  7970. n = elem->Array.count;
  7971. } else {
  7972. GB_PANIC("Unreachable");
  7973. }
  7974. if (is_ptr) {
  7975. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  7976. return lb_emit_load(p, v);
  7977. }
  7978. return lb_emit_struct_ev(p, value, cast(i32)n);
  7979. }
  7980. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  7981. Type *t = base_type(value.type);
  7982. bool is_ptr = false;
  7983. if (is_type_pointer(t)) {
  7984. is_ptr = true;
  7985. t = base_type(type_deref(t));
  7986. }
  7987. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7988. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  7989. }
  7990. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  7991. isize n = 0;
  7992. Type *elem = base_type(t->Struct.soa_elem);
  7993. if (elem->kind == Type_Struct) {
  7994. n = elem->Struct.fields.count+1;
  7995. } else if (elem->kind == Type_Array) {
  7996. n = elem->Array.count+1;
  7997. } else {
  7998. GB_PANIC("Unreachable");
  7999. }
  8000. if (is_ptr) {
  8001. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  8002. return lb_emit_load(p, v);
  8003. }
  8004. return lb_emit_struct_ev(p, value, cast(i32)n);
  8005. }
  8006. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  8007. GB_ASSERT(ce->args.count > 0);
  8008. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  8009. for_array(i, slices) {
  8010. Ast *arg = ce->args[i];
  8011. if (arg->kind == Ast_FieldValue) {
  8012. arg = arg->FieldValue.value;
  8013. }
  8014. slices[i] = lb_build_expr(p, arg);
  8015. }
  8016. lbValue len = lb_slice_len(p, slices[0]);
  8017. for (isize i = 1; i < slices.count; i++) {
  8018. lbValue other_len = lb_slice_len(p, slices[i]);
  8019. len = lb_emit_min(p, t_int, len, other_len);
  8020. }
  8021. GB_ASSERT(is_type_soa_struct(tv.type));
  8022. lbAddr res = lb_add_local_generated(p, tv.type, true);
  8023. for_array(i, slices) {
  8024. lbValue src = lb_slice_elem(p, slices[i]);
  8025. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  8026. lb_emit_store(p, dst, src);
  8027. }
  8028. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  8029. lb_emit_store(p, len_dst, len);
  8030. return lb_addr_load(p, res);
  8031. }
  8032. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  8033. GB_ASSERT(ce->args.count == 1);
  8034. lbValue arg = lb_build_expr(p, ce->args[0]);
  8035. Type *t = base_type(arg.type);
  8036. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  8037. lbValue len = lb_soa_struct_len(p, arg);
  8038. lbAddr res = lb_add_local_generated(p, tv.type, true);
  8039. if (is_type_tuple(tv.type)) {
  8040. lbValue rp = lb_addr_get_ptr(p, res);
  8041. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  8042. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  8043. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  8044. lb_fill_slice(p, dst, ptr, len);
  8045. }
  8046. } else {
  8047. GB_ASSERT(is_type_slice(tv.type));
  8048. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  8049. lb_fill_slice(p, res, ptr, len);
  8050. }
  8051. return lb_addr_load(p, res);
  8052. }
  8053. lbValue lb_emit_try(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  8054. Ast *arg = ce->args[0];
  8055. lbValue lhs = {};
  8056. lbValue rhs = {};
  8057. TypeAndValue const &arg_tav = type_and_value_of_expr(arg);
  8058. lbValue value = lb_build_expr(p, arg);
  8059. if (is_type_tuple(value.type)) {
  8060. i32 n = cast(i32)(value.type->Tuple.variables.count-1);
  8061. if (value.type->Tuple.variables.count == 2) {
  8062. lhs = lb_emit_struct_ev(p, value, 0);
  8063. } else {
  8064. lbAddr lhs_addr = lb_add_local_generated(p, tv.type, false);
  8065. lbValue lhs_ptr = lb_addr_get_ptr(p, lhs_addr);
  8066. for (i32 i = 0; i < n; i++) {
  8067. lb_emit_store(p, lb_emit_struct_ep(p, lhs_ptr, i), lb_emit_struct_ev(p, value, i));
  8068. }
  8069. lhs = lb_addr_load(p, lhs_addr);
  8070. }
  8071. rhs = lb_emit_struct_ev(p, value, n);
  8072. } else {
  8073. rhs = value;
  8074. }
  8075. GB_ASSERT(rhs.value != nullptr);
  8076. lbValue do_early_return = {};
  8077. if (is_type_boolean(rhs.type)) {
  8078. do_early_return = lb_emit_unary_arith(p, Token_Not, rhs, t_bool);
  8079. } else {
  8080. GB_ASSERT(type_has_nil(rhs.type));
  8081. do_early_return = lb_emit_comp_against_nil(p, Token_NotEq, rhs);
  8082. }
  8083. GB_ASSERT(do_early_return.value != nullptr);
  8084. lbBlock *return_block = lb_create_block(p, "try.return", false);
  8085. lbBlock *continue_block = lb_create_block(p, "try.continue", false);
  8086. lb_emit_if(p, do_early_return, return_block, continue_block);
  8087. lb_start_block(p, return_block);
  8088. {
  8089. Type *proc_type = base_type(p->type);
  8090. // TODO(bill): multiple return values
  8091. Type *results = proc_type->Proc.results;
  8092. GB_ASSERT(results != nullptr && results->kind == Type_Tuple);
  8093. TypeTuple *tuple = &results->Tuple;
  8094. isize return_count = tuple->variables.count;
  8095. // TODO(bill) multiple
  8096. GB_ASSERT(return_count != 0);
  8097. lbFunctionType *ft = lb_get_function_type(p->module, p, proc_type);
  8098. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  8099. if (p->type->Proc.has_named_results) {
  8100. Entity *e = tuple->variables[tuple->variables.count-1];
  8101. // NOTE(bill): store the named values before returning
  8102. if (e->token.string != "") {
  8103. lbValue *found = map_get(&p->module->values, hash_entity(e));
  8104. GB_ASSERT(found != nullptr);
  8105. lb_emit_store(p, *found, lb_emit_conv(p, rhs, e->type));
  8106. }
  8107. lb_build_return_stmt(p, {});
  8108. } else {
  8109. GB_ASSERT(return_count == 1);
  8110. Entity *e = tuple->variables[0];
  8111. lbValue res = lb_emit_conv(p, rhs, e->type);
  8112. if (return_by_pointer) {
  8113. if (res.value != nullptr) {
  8114. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  8115. } else {
  8116. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  8117. }
  8118. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  8119. LLVMBuildRetVoid(p->builder);
  8120. } else {
  8121. LLVMValueRef ret_val = res.value;
  8122. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  8123. if (p->abi_function_type->ret.cast_type != nullptr) {
  8124. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  8125. }
  8126. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  8127. LLVMBuildRet(p->builder, ret_val);
  8128. }
  8129. }
  8130. }
  8131. lb_start_block(p, continue_block);
  8132. if (tv.type != nullptr) {
  8133. return lb_emit_conv(p, lhs, tv.type);
  8134. }
  8135. return {};
  8136. }
  8137. lbValue lb_emit_or_else(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  8138. Ast *arg = ce->args[0];
  8139. Ast *else_value = ce->args[1];
  8140. lbValue lhs = {};
  8141. lbValue rhs = {};
  8142. TypeAndValue const &arg_tav = type_and_value_of_expr(arg);
  8143. if (unparen_expr(arg)->kind == Ast_TypeAssertion) {
  8144. GB_ASSERT_MSG(is_type_tuple(arg_tav.type), "%s", type_to_string(arg_tav.type));
  8145. }
  8146. lbValue value = lb_build_expr(p, arg);
  8147. if (is_type_tuple(value.type)) {
  8148. i32 end_index = cast(i32)(value.type->Tuple.variables.count-1);
  8149. if (value.type->Tuple.variables.count == 2) {
  8150. lhs = lb_emit_struct_ev(p, value, 0);
  8151. } else {
  8152. lbAddr lhs_addr = lb_add_local_generated(p, tv.type, false);
  8153. lbValue lhs_ptr = lb_addr_get_ptr(p, lhs_addr);
  8154. for (i32 i = 0; i < end_index; i++) {
  8155. lb_emit_store(p, lb_emit_struct_ep(p, lhs_ptr, i), lb_emit_struct_ev(p, value, i));
  8156. }
  8157. lhs = lb_addr_load(p, lhs_addr);
  8158. }
  8159. rhs = lb_emit_struct_ev(p, value, end_index);
  8160. } else {
  8161. rhs = value;
  8162. }
  8163. GB_ASSERT(rhs.value != nullptr);
  8164. lbValue has_value = {};
  8165. if (is_type_boolean(rhs.type)) {
  8166. has_value = rhs;
  8167. } else {
  8168. GB_ASSERT_MSG(type_has_nil(rhs.type), "%s", type_to_string(rhs.type));
  8169. has_value = lb_emit_comp_against_nil(p, Token_CmpEq, rhs);
  8170. }
  8171. GB_ASSERT(has_value.value != nullptr);
  8172. LLVMValueRef incoming_values[2] = {};
  8173. LLVMBasicBlockRef incoming_blocks[2] = {};
  8174. GB_ASSERT(else_value != nullptr);
  8175. lbBlock *then = lb_create_block(p, "or_else.then");
  8176. lbBlock *done = lb_create_block(p, "or_else.done"); // NOTE(bill): Append later
  8177. lbBlock *else_ = lb_create_block(p, "or_else.else");
  8178. lb_emit_if(p, has_value, then, else_);
  8179. lb_start_block(p, then);
  8180. Type *type = default_type(tv.type);
  8181. incoming_values[0] = lb_emit_conv(p, lhs, type).value;
  8182. lb_emit_jump(p, done);
  8183. lb_start_block(p, else_);
  8184. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, else_value), type).value;
  8185. lb_emit_jump(p, done);
  8186. lb_start_block(p, done);
  8187. lbValue res = {};
  8188. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8189. res.type = type;
  8190. GB_ASSERT(p->curr_block->preds.count >= 2);
  8191. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8192. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8193. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8194. return res;
  8195. }
  8196. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  8197. ast_node(ce, CallExpr, expr);
  8198. switch (id) {
  8199. case BuiltinProc_DIRECTIVE: {
  8200. ast_node(bd, BasicDirective, ce->proc);
  8201. String name = bd->name.string;
  8202. GB_ASSERT(name == "location");
  8203. String procedure = p->entity->token.string;
  8204. TokenPos pos = ast_token(ce->proc).pos;
  8205. if (ce->args.count > 0) {
  8206. Ast *ident = unselector_expr(ce->args[0]);
  8207. GB_ASSERT(ident->kind == Ast_Ident);
  8208. Entity *e = entity_of_node(ident);
  8209. GB_ASSERT(e != nullptr);
  8210. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  8211. procedure = e->parent_proc_decl->entity->token.string;
  8212. } else {
  8213. procedure = str_lit("");
  8214. }
  8215. pos = e->token.pos;
  8216. }
  8217. return lb_emit_source_code_location(p, procedure, pos);
  8218. }
  8219. case BuiltinProc_type_info_of: {
  8220. Ast *arg = ce->args[0];
  8221. TypeAndValue tav = type_and_value_of_expr(arg);
  8222. if (tav.mode == Addressing_Type) {
  8223. Type *t = default_type(type_of_expr(arg));
  8224. return lb_type_info(p->module, t);
  8225. }
  8226. GB_ASSERT(is_type_typeid(tav.type));
  8227. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8228. args[0] = lb_build_expr(p, arg);
  8229. return lb_emit_runtime_call(p, "__type_info_of", args);
  8230. }
  8231. case BuiltinProc_typeid_of: {
  8232. Ast *arg = ce->args[0];
  8233. TypeAndValue tav = type_and_value_of_expr(arg);
  8234. GB_ASSERT(tav.mode == Addressing_Type);
  8235. Type *t = default_type(type_of_expr(arg));
  8236. return lb_typeid(p->module, t);
  8237. }
  8238. case BuiltinProc_len: {
  8239. lbValue v = lb_build_expr(p, ce->args[0]);
  8240. Type *t = base_type(v.type);
  8241. if (is_type_pointer(t)) {
  8242. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  8243. v = lb_emit_load(p, v);
  8244. t = type_deref(t);
  8245. }
  8246. if (is_type_cstring(t)) {
  8247. return lb_cstring_len(p, v);
  8248. } else if (is_type_string(t)) {
  8249. return lb_string_len(p, v);
  8250. } else if (is_type_array(t)) {
  8251. GB_PANIC("Array lengths are constant");
  8252. } else if (is_type_slice(t)) {
  8253. return lb_slice_len(p, v);
  8254. } else if (is_type_dynamic_array(t)) {
  8255. return lb_dynamic_array_len(p, v);
  8256. } else if (is_type_map(t)) {
  8257. return lb_map_len(p, v);
  8258. } else if (is_type_soa_struct(t)) {
  8259. return lb_soa_struct_len(p, v);
  8260. }
  8261. GB_PANIC("Unreachable");
  8262. break;
  8263. }
  8264. case BuiltinProc_cap: {
  8265. lbValue v = lb_build_expr(p, ce->args[0]);
  8266. Type *t = base_type(v.type);
  8267. if (is_type_pointer(t)) {
  8268. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  8269. v = lb_emit_load(p, v);
  8270. t = type_deref(t);
  8271. }
  8272. if (is_type_string(t)) {
  8273. GB_PANIC("Unreachable");
  8274. } else if (is_type_array(t)) {
  8275. GB_PANIC("Array lengths are constant");
  8276. } else if (is_type_slice(t)) {
  8277. return lb_slice_len(p, v);
  8278. } else if (is_type_dynamic_array(t)) {
  8279. return lb_dynamic_array_cap(p, v);
  8280. } else if (is_type_map(t)) {
  8281. return lb_map_cap(p, v);
  8282. } else if (is_type_soa_struct(t)) {
  8283. return lb_soa_struct_cap(p, v);
  8284. }
  8285. GB_PANIC("Unreachable");
  8286. break;
  8287. }
  8288. case BuiltinProc_swizzle: {
  8289. isize index_count = ce->args.count-1;
  8290. if (is_type_simd_vector(tv.type)) {
  8291. lbValue vec = lb_build_expr(p, ce->args[0]);
  8292. if (index_count == 0) {
  8293. return vec;
  8294. }
  8295. unsigned mask_len = cast(unsigned)index_count;
  8296. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  8297. for (isize i = 1; i < ce->args.count; i++) {
  8298. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  8299. GB_ASSERT(is_type_integer(tv.type));
  8300. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  8301. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  8302. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  8303. }
  8304. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  8305. LLVMValueRef v1 = vec.value;
  8306. LLVMValueRef v2 = vec.value;
  8307. lbValue res = {};
  8308. res.type = tv.type;
  8309. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  8310. return res;
  8311. }
  8312. lbAddr addr = lb_build_addr(p, ce->args[0]);
  8313. if (index_count == 0) {
  8314. return lb_addr_load(p, addr);
  8315. }
  8316. lbValue src = lb_addr_get_ptr(p, addr);
  8317. // TODO(bill): Should this be zeroed or not?
  8318. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  8319. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  8320. for (i32 i = 1; i < ce->args.count; i++) {
  8321. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  8322. GB_ASSERT(is_type_integer(tv.type));
  8323. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  8324. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  8325. i32 dst_index = i-1;
  8326. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  8327. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  8328. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  8329. }
  8330. return lb_addr_load(p, dst);
  8331. }
  8332. case BuiltinProc_complex: {
  8333. lbValue real = lb_build_expr(p, ce->args[0]);
  8334. lbValue imag = lb_build_expr(p, ce->args[1]);
  8335. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  8336. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  8337. Type *ft = base_complex_elem_type(tv.type);
  8338. real = lb_emit_conv(p, real, ft);
  8339. imag = lb_emit_conv(p, imag, ft);
  8340. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  8341. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  8342. return lb_emit_load(p, dst);
  8343. }
  8344. case BuiltinProc_quaternion: {
  8345. lbValue real = lb_build_expr(p, ce->args[0]);
  8346. lbValue imag = lb_build_expr(p, ce->args[1]);
  8347. lbValue jmag = lb_build_expr(p, ce->args[2]);
  8348. lbValue kmag = lb_build_expr(p, ce->args[3]);
  8349. // @QuaternionLayout
  8350. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  8351. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  8352. Type *ft = base_complex_elem_type(tv.type);
  8353. real = lb_emit_conv(p, real, ft);
  8354. imag = lb_emit_conv(p, imag, ft);
  8355. jmag = lb_emit_conv(p, jmag, ft);
  8356. kmag = lb_emit_conv(p, kmag, ft);
  8357. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  8358. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  8359. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  8360. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  8361. return lb_emit_load(p, dst);
  8362. }
  8363. case BuiltinProc_real: {
  8364. lbValue val = lb_build_expr(p, ce->args[0]);
  8365. if (is_type_complex(val.type)) {
  8366. lbValue real = lb_emit_struct_ev(p, val, 0);
  8367. return lb_emit_conv(p, real, tv.type);
  8368. } else if (is_type_quaternion(val.type)) {
  8369. // @QuaternionLayout
  8370. lbValue real = lb_emit_struct_ev(p, val, 3);
  8371. return lb_emit_conv(p, real, tv.type);
  8372. }
  8373. GB_PANIC("invalid type for real");
  8374. return {};
  8375. }
  8376. case BuiltinProc_imag: {
  8377. lbValue val = lb_build_expr(p, ce->args[0]);
  8378. if (is_type_complex(val.type)) {
  8379. lbValue imag = lb_emit_struct_ev(p, val, 1);
  8380. return lb_emit_conv(p, imag, tv.type);
  8381. } else if (is_type_quaternion(val.type)) {
  8382. // @QuaternionLayout
  8383. lbValue imag = lb_emit_struct_ev(p, val, 0);
  8384. return lb_emit_conv(p, imag, tv.type);
  8385. }
  8386. GB_PANIC("invalid type for imag");
  8387. return {};
  8388. }
  8389. case BuiltinProc_jmag: {
  8390. lbValue val = lb_build_expr(p, ce->args[0]);
  8391. if (is_type_quaternion(val.type)) {
  8392. // @QuaternionLayout
  8393. lbValue imag = lb_emit_struct_ev(p, val, 1);
  8394. return lb_emit_conv(p, imag, tv.type);
  8395. }
  8396. GB_PANIC("invalid type for jmag");
  8397. return {};
  8398. }
  8399. case BuiltinProc_kmag: {
  8400. lbValue val = lb_build_expr(p, ce->args[0]);
  8401. if (is_type_quaternion(val.type)) {
  8402. // @QuaternionLayout
  8403. lbValue imag = lb_emit_struct_ev(p, val, 2);
  8404. return lb_emit_conv(p, imag, tv.type);
  8405. }
  8406. GB_PANIC("invalid type for kmag");
  8407. return {};
  8408. }
  8409. case BuiltinProc_conj: {
  8410. lbValue val = lb_build_expr(p, ce->args[0]);
  8411. lbValue res = {};
  8412. Type *t = val.type;
  8413. if (is_type_complex(t)) {
  8414. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  8415. lbValue real = lb_emit_struct_ev(p, val, 0);
  8416. lbValue imag = lb_emit_struct_ev(p, val, 1);
  8417. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  8418. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  8419. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  8420. } else if (is_type_quaternion(t)) {
  8421. // @QuaternionLayout
  8422. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  8423. lbValue real = lb_emit_struct_ev(p, val, 3);
  8424. lbValue imag = lb_emit_struct_ev(p, val, 0);
  8425. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  8426. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  8427. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  8428. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  8429. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  8430. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  8431. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  8432. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  8433. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  8434. }
  8435. return lb_emit_load(p, res);
  8436. }
  8437. case BuiltinProc_expand_to_tuple: {
  8438. lbValue val = lb_build_expr(p, ce->args[0]);
  8439. Type *t = base_type(val.type);
  8440. if (!is_type_tuple(tv.type)) {
  8441. if (t->kind == Type_Struct) {
  8442. GB_ASSERT(t->Struct.fields.count == 1);
  8443. return lb_emit_struct_ev(p, val, 0);
  8444. } else if (t->kind == Type_Array) {
  8445. GB_ASSERT(t->Array.count == 1);
  8446. return lb_emit_array_epi(p, val, 0);
  8447. } else {
  8448. GB_PANIC("Unknown type of expand_to_tuple");
  8449. }
  8450. }
  8451. GB_ASSERT(is_type_tuple(tv.type));
  8452. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  8453. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  8454. if (t->kind == Type_Struct) {
  8455. for_array(src_index, t->Struct.fields) {
  8456. Entity *field = t->Struct.fields[src_index];
  8457. i32 field_index = field->Variable.field_index;
  8458. lbValue f = lb_emit_struct_ev(p, val, field_index);
  8459. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  8460. lb_emit_store(p, ep, f);
  8461. }
  8462. } else if (is_type_array_like(t)) {
  8463. // TODO(bill): Clean-up this code
  8464. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  8465. i32 n = cast(i32)get_array_type_count(t);
  8466. for (i32 i = 0; i < n; i++) {
  8467. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  8468. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  8469. lb_emit_store(p, ep, f);
  8470. }
  8471. } else {
  8472. GB_PANIC("Unknown type of expand_to_tuple");
  8473. }
  8474. return lb_emit_load(p, tuple);
  8475. }
  8476. case BuiltinProc_min: {
  8477. Type *t = type_of_expr(expr);
  8478. if (ce->args.count == 2) {
  8479. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  8480. } else {
  8481. lbValue x = lb_build_expr(p, ce->args[0]);
  8482. for (isize i = 1; i < ce->args.count; i++) {
  8483. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  8484. }
  8485. return x;
  8486. }
  8487. }
  8488. case BuiltinProc_max: {
  8489. Type *t = type_of_expr(expr);
  8490. if (ce->args.count == 2) {
  8491. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  8492. } else {
  8493. lbValue x = lb_build_expr(p, ce->args[0]);
  8494. for (isize i = 1; i < ce->args.count; i++) {
  8495. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  8496. }
  8497. return x;
  8498. }
  8499. }
  8500. case BuiltinProc_abs: {
  8501. lbValue x = lb_build_expr(p, ce->args[0]);
  8502. Type *t = x.type;
  8503. if (is_type_unsigned(t)) {
  8504. return x;
  8505. }
  8506. if (is_type_quaternion(t)) {
  8507. i64 sz = 8*type_size_of(t);
  8508. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8509. args[0] = x;
  8510. switch (sz) {
  8511. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  8512. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  8513. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  8514. }
  8515. GB_PANIC("Unknown complex type");
  8516. } else if (is_type_complex(t)) {
  8517. i64 sz = 8*type_size_of(t);
  8518. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8519. args[0] = x;
  8520. switch (sz) {
  8521. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  8522. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  8523. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  8524. }
  8525. GB_PANIC("Unknown complex type");
  8526. }
  8527. lbValue zero = lb_const_nil(p->module, t);
  8528. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  8529. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  8530. return lb_emit_select(p, cond, neg, x);
  8531. }
  8532. case BuiltinProc_clamp:
  8533. return lb_emit_clamp(p, type_of_expr(expr),
  8534. lb_build_expr(p, ce->args[0]),
  8535. lb_build_expr(p, ce->args[1]),
  8536. lb_build_expr(p, ce->args[2]));
  8537. case BuiltinProc_soa_zip:
  8538. return lb_soa_zip(p, ce, tv);
  8539. case BuiltinProc_soa_unzip:
  8540. return lb_soa_unzip(p, ce, tv);
  8541. case BuiltinProc_try:
  8542. return lb_emit_try(p, ce, tv);
  8543. case BuiltinProc_or_else:
  8544. return lb_emit_or_else(p, ce, tv);
  8545. // "Intrinsics"
  8546. case BuiltinProc_alloca:
  8547. {
  8548. lbValue sz = lb_build_expr(p, ce->args[0]);
  8549. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  8550. lbValue res = {};
  8551. res.type = t_u8_ptr;
  8552. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  8553. LLVMSetAlignment(res.value, cast(unsigned)al);
  8554. return res;
  8555. }
  8556. case BuiltinProc_cpu_relax:
  8557. if (build_context.metrics.arch == TargetArch_386 ||
  8558. build_context.metrics.arch == TargetArch_amd64) {
  8559. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  8560. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8561. cast(char *)"pause", 5,
  8562. cast(char *)"", 0,
  8563. /*HasSideEffects*/true, /*IsAlignStack*/false,
  8564. LLVMInlineAsmDialectATT
  8565. );
  8566. GB_ASSERT(the_asm != nullptr);
  8567. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  8568. } else if (build_context.metrics.arch == TargetArch_arm64) {
  8569. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  8570. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8571. cast(char *)"yield", 5,
  8572. cast(char *)"", 0,
  8573. /*HasSideEffects*/true, /*IsAlignStack*/false,
  8574. LLVMInlineAsmDialectATT
  8575. );
  8576. GB_ASSERT(the_asm != nullptr);
  8577. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  8578. }
  8579. return {};
  8580. case BuiltinProc_debug_trap:
  8581. case BuiltinProc_trap:
  8582. {
  8583. char const *name = nullptr;
  8584. switch (id) {
  8585. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  8586. case BuiltinProc_trap: name = "llvm.trap"; break;
  8587. }
  8588. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8589. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  8590. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  8591. LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  8592. if (id == BuiltinProc_trap) {
  8593. LLVMBuildUnreachable(p->builder);
  8594. }
  8595. return {};
  8596. }
  8597. case BuiltinProc_read_cycle_counter:
  8598. {
  8599. char const *name = "llvm.readcyclecounter";
  8600. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8601. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  8602. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  8603. lbValue res = {};
  8604. res.value = LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  8605. res.type = tv.type;
  8606. return res;
  8607. }
  8608. case BuiltinProc_count_trailing_zeros:
  8609. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  8610. case BuiltinProc_count_leading_zeros:
  8611. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  8612. case BuiltinProc_count_ones:
  8613. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  8614. case BuiltinProc_count_zeros:
  8615. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  8616. case BuiltinProc_reverse_bits:
  8617. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  8618. case BuiltinProc_byte_swap:
  8619. {
  8620. lbValue x = lb_build_expr(p, ce->args[0]);
  8621. x = lb_emit_conv(p, x, tv.type);
  8622. return lb_emit_byte_swap(p, x, tv.type);
  8623. }
  8624. case BuiltinProc_overflow_add:
  8625. case BuiltinProc_overflow_sub:
  8626. case BuiltinProc_overflow_mul:
  8627. {
  8628. Type *main_type = tv.type;
  8629. Type *type = main_type;
  8630. if (is_type_tuple(main_type)) {
  8631. type = main_type->Tuple.variables[0]->type;
  8632. }
  8633. lbValue x = lb_build_expr(p, ce->args[0]);
  8634. lbValue y = lb_build_expr(p, ce->args[1]);
  8635. x = lb_emit_conv(p, x, type);
  8636. y = lb_emit_conv(p, y, type);
  8637. char const *name = nullptr;
  8638. if (is_type_unsigned(type)) {
  8639. switch (id) {
  8640. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  8641. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  8642. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  8643. }
  8644. } else {
  8645. switch (id) {
  8646. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  8647. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  8648. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  8649. }
  8650. }
  8651. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8652. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8653. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8654. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8655. LLVMValueRef args[2] = {};
  8656. args[0] = x.value;
  8657. args[1] = y.value;
  8658. lbValue res = {};
  8659. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8660. if (is_type_tuple(main_type)) {
  8661. Type *res_type = nullptr;
  8662. gbAllocator a = permanent_allocator();
  8663. res_type = alloc_type_tuple();
  8664. array_init(&res_type->Tuple.variables, a, 2);
  8665. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  8666. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  8667. res.type = res_type;
  8668. } else {
  8669. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  8670. res.type = type;
  8671. }
  8672. return res;
  8673. }
  8674. case BuiltinProc_sqrt:
  8675. {
  8676. Type *type = tv.type;
  8677. lbValue x = lb_build_expr(p, ce->args[0]);
  8678. x = lb_emit_conv(p, x, type);
  8679. char const *name = "llvm.sqrt";
  8680. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  8681. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8682. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  8683. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8684. LLVMValueRef args[1] = {};
  8685. args[0] = x.value;
  8686. lbValue res = {};
  8687. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8688. res.type = type;
  8689. return res;
  8690. }
  8691. case BuiltinProc_mem_copy:
  8692. case BuiltinProc_mem_copy_non_overlapping:
  8693. {
  8694. lbValue dst = lb_build_expr(p, ce->args[0]);
  8695. lbValue src = lb_build_expr(p, ce->args[1]);
  8696. lbValue len = lb_build_expr(p, ce->args[2]);
  8697. dst = lb_emit_conv(p, dst, t_rawptr);
  8698. src = lb_emit_conv(p, src, t_rawptr);
  8699. len = lb_emit_conv(p, len, t_int);
  8700. bool is_inlinable = false;
  8701. if (ce->args[2]->tav.mode == Addressing_Constant) {
  8702. ExactValue ev = exact_value_to_integer(ce->args[2]->tav.value);
  8703. i64 const_len = exact_value_to_i64(ev);
  8704. // TODO(bill): Determine when it is better to do the `*.inline` versions
  8705. if (const_len <= 4*build_context.word_size) {
  8706. is_inlinable = true;
  8707. }
  8708. }
  8709. char const *name = nullptr;
  8710. switch (id) {
  8711. case BuiltinProc_mem_copy:
  8712. if (is_inlinable) {
  8713. name = "llvm.memmove.inline";
  8714. } else {
  8715. name = "llvm.memmove";
  8716. }
  8717. break;
  8718. case BuiltinProc_mem_copy_non_overlapping:
  8719. if (is_inlinable) {
  8720. name = "llvm.memcpy.line";
  8721. } else {
  8722. name = "llvm.memcpy";
  8723. }
  8724. break;
  8725. }
  8726. LLVMTypeRef types[3] = {
  8727. lb_type(p->module, t_rawptr),
  8728. lb_type(p->module, t_rawptr),
  8729. lb_type(p->module, t_int)
  8730. };
  8731. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  8732. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]), LLVMPrintTypeToString(types[2]));
  8733. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  8734. LLVMValueRef args[4] = {};
  8735. args[0] = dst.value;
  8736. args[1] = src.value;
  8737. args[2] = len.value;
  8738. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, false); // is_volatile parameter
  8739. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  8740. return {};
  8741. }
  8742. case BuiltinProc_mem_zero:
  8743. {
  8744. lbValue ptr = lb_build_expr(p, ce->args[0]);
  8745. lbValue len = lb_build_expr(p, ce->args[1]);
  8746. ptr = lb_emit_conv(p, ptr, t_rawptr);
  8747. len = lb_emit_conv(p, len, t_int);
  8748. unsigned alignment = 1;
  8749. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment);
  8750. return {};
  8751. }
  8752. case BuiltinProc_ptr_offset:
  8753. {
  8754. lbValue ptr = lb_build_expr(p, ce->args[0]);
  8755. lbValue len = lb_build_expr(p, ce->args[1]);
  8756. len = lb_emit_conv(p, len, t_int);
  8757. LLVMValueRef indices[1] = {
  8758. len.value,
  8759. };
  8760. lbValue res = {};
  8761. res.type = tv.type;
  8762. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, gb_count_of(indices), "");
  8763. return res;
  8764. }
  8765. case BuiltinProc_ptr_sub:
  8766. {
  8767. lbValue ptr0 = lb_build_expr(p, ce->args[0]);
  8768. lbValue ptr1 = lb_build_expr(p, ce->args[1]);
  8769. LLVMTypeRef type_int = lb_type(p->module, t_int);
  8770. LLVMValueRef diff = LLVMBuildPtrDiff(p->builder, ptr0.value, ptr1.value, "");
  8771. diff = LLVMBuildIntCast2(p->builder, diff, type_int, /*signed*/true, "");
  8772. lbValue res = {};
  8773. res.type = t_int;
  8774. res.value = diff;
  8775. return res;
  8776. }
  8777. case BuiltinProc_atomic_fence:
  8778. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  8779. return {};
  8780. case BuiltinProc_atomic_fence_acq:
  8781. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  8782. return {};
  8783. case BuiltinProc_atomic_fence_rel:
  8784. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  8785. return {};
  8786. case BuiltinProc_atomic_fence_acqrel:
  8787. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  8788. return {};
  8789. case BuiltinProc_volatile_store:
  8790. case BuiltinProc_atomic_store:
  8791. case BuiltinProc_atomic_store_rel:
  8792. case BuiltinProc_atomic_store_relaxed:
  8793. case BuiltinProc_atomic_store_unordered: {
  8794. lbValue dst = lb_build_expr(p, ce->args[0]);
  8795. lbValue val = lb_build_expr(p, ce->args[1]);
  8796. val = lb_emit_conv(p, val, type_deref(dst.type));
  8797. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  8798. switch (id) {
  8799. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  8800. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  8801. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  8802. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  8803. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  8804. }
  8805. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  8806. return {};
  8807. }
  8808. case BuiltinProc_volatile_load:
  8809. case BuiltinProc_atomic_load:
  8810. case BuiltinProc_atomic_load_acq:
  8811. case BuiltinProc_atomic_load_relaxed:
  8812. case BuiltinProc_atomic_load_unordered: {
  8813. lbValue dst = lb_build_expr(p, ce->args[0]);
  8814. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  8815. switch (id) {
  8816. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  8817. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  8818. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  8819. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  8820. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  8821. }
  8822. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  8823. lbValue res = {};
  8824. res.value = instr;
  8825. res.type = type_deref(dst.type);
  8826. return res;
  8827. }
  8828. case BuiltinProc_atomic_add:
  8829. case BuiltinProc_atomic_add_acq:
  8830. case BuiltinProc_atomic_add_rel:
  8831. case BuiltinProc_atomic_add_acqrel:
  8832. case BuiltinProc_atomic_add_relaxed:
  8833. case BuiltinProc_atomic_sub:
  8834. case BuiltinProc_atomic_sub_acq:
  8835. case BuiltinProc_atomic_sub_rel:
  8836. case BuiltinProc_atomic_sub_acqrel:
  8837. case BuiltinProc_atomic_sub_relaxed:
  8838. case BuiltinProc_atomic_and:
  8839. case BuiltinProc_atomic_and_acq:
  8840. case BuiltinProc_atomic_and_rel:
  8841. case BuiltinProc_atomic_and_acqrel:
  8842. case BuiltinProc_atomic_and_relaxed:
  8843. case BuiltinProc_atomic_nand:
  8844. case BuiltinProc_atomic_nand_acq:
  8845. case BuiltinProc_atomic_nand_rel:
  8846. case BuiltinProc_atomic_nand_acqrel:
  8847. case BuiltinProc_atomic_nand_relaxed:
  8848. case BuiltinProc_atomic_or:
  8849. case BuiltinProc_atomic_or_acq:
  8850. case BuiltinProc_atomic_or_rel:
  8851. case BuiltinProc_atomic_or_acqrel:
  8852. case BuiltinProc_atomic_or_relaxed:
  8853. case BuiltinProc_atomic_xor:
  8854. case BuiltinProc_atomic_xor_acq:
  8855. case BuiltinProc_atomic_xor_rel:
  8856. case BuiltinProc_atomic_xor_acqrel:
  8857. case BuiltinProc_atomic_xor_relaxed:
  8858. case BuiltinProc_atomic_xchg:
  8859. case BuiltinProc_atomic_xchg_acq:
  8860. case BuiltinProc_atomic_xchg_rel:
  8861. case BuiltinProc_atomic_xchg_acqrel:
  8862. case BuiltinProc_atomic_xchg_relaxed: {
  8863. lbValue dst = lb_build_expr(p, ce->args[0]);
  8864. lbValue val = lb_build_expr(p, ce->args[1]);
  8865. val = lb_emit_conv(p, val, type_deref(dst.type));
  8866. LLVMAtomicRMWBinOp op = {};
  8867. LLVMAtomicOrdering ordering = {};
  8868. switch (id) {
  8869. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8870. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  8871. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  8872. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8873. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  8874. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8875. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  8876. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  8877. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8878. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  8879. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8880. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  8881. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  8882. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8883. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  8884. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8885. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  8886. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  8887. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8888. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  8889. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8890. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  8891. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  8892. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8893. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  8894. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8895. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  8896. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  8897. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8898. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  8899. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  8900. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  8901. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  8902. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  8903. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  8904. }
  8905. lbValue res = {};
  8906. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  8907. res.type = tv.type;
  8908. return res;
  8909. }
  8910. case BuiltinProc_atomic_cxchg:
  8911. case BuiltinProc_atomic_cxchg_acq:
  8912. case BuiltinProc_atomic_cxchg_rel:
  8913. case BuiltinProc_atomic_cxchg_acqrel:
  8914. case BuiltinProc_atomic_cxchg_relaxed:
  8915. case BuiltinProc_atomic_cxchg_failrelaxed:
  8916. case BuiltinProc_atomic_cxchg_failacq:
  8917. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  8918. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  8919. case BuiltinProc_atomic_cxchgweak:
  8920. case BuiltinProc_atomic_cxchgweak_acq:
  8921. case BuiltinProc_atomic_cxchgweak_rel:
  8922. case BuiltinProc_atomic_cxchgweak_acqrel:
  8923. case BuiltinProc_atomic_cxchgweak_relaxed:
  8924. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  8925. case BuiltinProc_atomic_cxchgweak_failacq:
  8926. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  8927. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  8928. Type *type = expr->tav.type;
  8929. lbValue address = lb_build_expr(p, ce->args[0]);
  8930. Type *elem = type_deref(address.type);
  8931. lbValue old_value = lb_build_expr(p, ce->args[1]);
  8932. lbValue new_value = lb_build_expr(p, ce->args[2]);
  8933. old_value = lb_emit_conv(p, old_value, elem);
  8934. new_value = lb_emit_conv(p, new_value, elem);
  8935. LLVMAtomicOrdering success_ordering = {};
  8936. LLVMAtomicOrdering failure_ordering = {};
  8937. LLVMBool weak = false;
  8938. switch (id) {
  8939. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8940. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8941. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8942. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8943. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8944. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8945. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  8946. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8947. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  8948. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  8949. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8950. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8951. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  8952. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8953. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8954. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  8955. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8956. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  8957. }
  8958. // TODO(bill): Figure out how to make it weak
  8959. LLVMBool single_threaded = weak;
  8960. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  8961. p->builder, address.value,
  8962. old_value.value, new_value.value,
  8963. success_ordering,
  8964. failure_ordering,
  8965. single_threaded
  8966. );
  8967. if (tv.type->kind == Type_Tuple) {
  8968. Type *fix_typed = alloc_type_tuple();
  8969. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  8970. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  8971. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  8972. lbValue res = {};
  8973. res.value = value;
  8974. res.type = fix_typed;
  8975. return res;
  8976. } else {
  8977. lbValue res = {};
  8978. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  8979. res.type = tv.type;
  8980. return res;
  8981. }
  8982. }
  8983. case BuiltinProc_type_equal_proc:
  8984. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  8985. case BuiltinProc_type_hasher_proc:
  8986. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  8987. case BuiltinProc_fixed_point_mul:
  8988. case BuiltinProc_fixed_point_div:
  8989. case BuiltinProc_fixed_point_mul_sat:
  8990. case BuiltinProc_fixed_point_div_sat:
  8991. {
  8992. bool do_bswap = is_type_different_to_arch_endianness(tv.type);
  8993. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  8994. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  8995. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  8996. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  8997. char const *name = nullptr;
  8998. if (is_type_unsigned(tv.type)) {
  8999. switch (id) {
  9000. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  9001. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  9002. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  9003. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  9004. }
  9005. } else {
  9006. switch (id) {
  9007. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  9008. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  9009. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  9010. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  9011. }
  9012. }
  9013. GB_ASSERT(name != nullptr);
  9014. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  9015. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9016. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9017. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9018. lbValue res = {};
  9019. LLVMValueRef args[3] = {};
  9020. args[0] = x.value;
  9021. args[1] = y.value;
  9022. args[2] = scale.value;
  9023. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9024. res.type = platform_type;
  9025. return lb_emit_conv(p, res, tv.type);
  9026. }
  9027. case BuiltinProc_expect:
  9028. {
  9029. Type *t = default_type(tv.type);
  9030. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  9031. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  9032. char const *name = "llvm.expect";
  9033. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  9034. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9035. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9036. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9037. lbValue res = {};
  9038. LLVMValueRef args[2] = {};
  9039. args[0] = x.value;
  9040. args[1] = y.value;
  9041. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9042. res.type = t;
  9043. return lb_emit_conv(p, res, t);
  9044. }
  9045. }
  9046. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  9047. return {};
  9048. }
  9049. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  9050. switch (param_value.kind) {
  9051. case ParameterValue_Constant:
  9052. if (is_type_constant_type(parameter_type)) {
  9053. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  9054. return res;
  9055. } else {
  9056. ExactValue ev = param_value.value;
  9057. lbValue arg = {};
  9058. Type *type = type_of_expr(param_value.original_ast_expr);
  9059. if (type != nullptr) {
  9060. arg = lb_const_value(p->module, type, ev);
  9061. } else {
  9062. arg = lb_const_value(p->module, parameter_type, param_value.value);
  9063. }
  9064. return lb_emit_conv(p, arg, parameter_type);
  9065. }
  9066. case ParameterValue_Nil:
  9067. return lb_const_nil(p->module, parameter_type);
  9068. case ParameterValue_Location:
  9069. {
  9070. String proc_name = {};
  9071. if (p->entity != nullptr) {
  9072. proc_name = p->entity->token.string;
  9073. }
  9074. return lb_emit_source_code_location(p, proc_name, pos);
  9075. }
  9076. case ParameterValue_Value:
  9077. return lb_build_expr(p, param_value.ast_value);
  9078. }
  9079. return lb_const_nil(p->module, parameter_type);
  9080. }
  9081. lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr);
  9082. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  9083. expr = unparen_expr(expr);
  9084. ast_node(ce, CallExpr, expr);
  9085. if (ce->sce_temp_data) {
  9086. return *(lbValue *)ce->sce_temp_data;
  9087. }
  9088. lbValue res = lb_build_call_expr_internal(p, expr);
  9089. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  9090. GB_ASSERT(is_type_tuple(res.type));
  9091. GB_ASSERT(res.type->Tuple.variables.count == 2);
  9092. return lb_emit_struct_ev(p, res, 0);
  9093. }
  9094. return res;
  9095. }
  9096. lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr) {
  9097. lbModule *m = p->module;
  9098. TypeAndValue tv = type_and_value_of_expr(expr);
  9099. ast_node(ce, CallExpr, expr);
  9100. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  9101. AddressingMode proc_mode = proc_tv.mode;
  9102. if (proc_mode == Addressing_Type) {
  9103. GB_ASSERT(ce->args.count == 1);
  9104. lbValue x = lb_build_expr(p, ce->args[0]);
  9105. lbValue y = lb_emit_conv(p, x, tv.type);
  9106. return y;
  9107. }
  9108. Ast *pexpr = unparen_expr(ce->proc);
  9109. if (proc_mode == Addressing_Builtin) {
  9110. Entity *e = entity_of_node(pexpr);
  9111. BuiltinProcId id = BuiltinProc_Invalid;
  9112. if (e != nullptr) {
  9113. id = cast(BuiltinProcId)e->Builtin.id;
  9114. } else {
  9115. id = BuiltinProc_DIRECTIVE;
  9116. }
  9117. return lb_build_builtin_proc(p, expr, tv, id);
  9118. }
  9119. // NOTE(bill): Regular call
  9120. lbValue value = {};
  9121. Ast *proc_expr = unparen_expr(ce->proc);
  9122. if (proc_expr->tav.mode == Addressing_Constant) {
  9123. ExactValue v = proc_expr->tav.value;
  9124. switch (v.kind) {
  9125. case ExactValue_Integer:
  9126. {
  9127. u64 u = big_int_to_u64(&v.value_integer);
  9128. lbValue x = {};
  9129. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  9130. x.type = t_uintptr;
  9131. x = lb_emit_conv(p, x, t_rawptr);
  9132. value = lb_emit_conv(p, x, proc_expr->tav.type);
  9133. break;
  9134. }
  9135. case ExactValue_Pointer:
  9136. {
  9137. u64 u = cast(u64)v.value_pointer;
  9138. lbValue x = {};
  9139. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  9140. x.type = t_uintptr;
  9141. x = lb_emit_conv(p, x, t_rawptr);
  9142. value = lb_emit_conv(p, x, proc_expr->tav.type);
  9143. break;
  9144. }
  9145. }
  9146. }
  9147. Entity *proc_entity = entity_of_node(proc_expr);
  9148. if (proc_entity != nullptr) {
  9149. if (proc_entity->flags & EntityFlag_Disabled) {
  9150. return {};
  9151. }
  9152. }
  9153. if (value.value == nullptr) {
  9154. value = lb_build_expr(p, proc_expr);
  9155. }
  9156. GB_ASSERT(value.value != nullptr);
  9157. Type *proc_type_ = base_type(value.type);
  9158. GB_ASSERT(proc_type_->kind == Type_Proc);
  9159. TypeProc *pt = &proc_type_->Proc;
  9160. if (is_call_expr_field_value(ce)) {
  9161. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  9162. for_array(arg_index, ce->args) {
  9163. Ast *arg = ce->args[arg_index];
  9164. ast_node(fv, FieldValue, arg);
  9165. GB_ASSERT(fv->field->kind == Ast_Ident);
  9166. String name = fv->field->Ident.token.string;
  9167. isize index = lookup_procedure_parameter(pt, name);
  9168. GB_ASSERT(index >= 0);
  9169. TypeAndValue tav = type_and_value_of_expr(fv->value);
  9170. if (tav.mode == Addressing_Type) {
  9171. args[index] = lb_const_nil(m, tav.type);
  9172. } else {
  9173. args[index] = lb_build_expr(p, fv->value);
  9174. }
  9175. }
  9176. TypeTuple *params = &pt->params->Tuple;
  9177. for (isize i = 0; i < args.count; i++) {
  9178. Entity *e = params->variables[i];
  9179. if (e->kind == Entity_TypeName) {
  9180. args[i] = lb_const_nil(m, e->type);
  9181. } else if (e->kind == Entity_Constant) {
  9182. continue;
  9183. } else {
  9184. GB_ASSERT(e->kind == Entity_Variable);
  9185. if (args[i].value == nullptr) {
  9186. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  9187. } else {
  9188. args[i] = lb_emit_conv(p, args[i], e->type);
  9189. }
  9190. }
  9191. }
  9192. for (isize i = 0; i < args.count; i++) {
  9193. Entity *e = params->variables[i];
  9194. if (args[i].type == nullptr) {
  9195. continue;
  9196. } else if (is_type_untyped_nil(args[i].type)) {
  9197. args[i] = lb_const_nil(m, e->type);
  9198. } else if (is_type_untyped_undef(args[i].type)) {
  9199. args[i] = lb_const_undef(m, e->type);
  9200. }
  9201. }
  9202. return lb_emit_call(p, value, args, ce->inlining, p->copy_elision_hint.ast == expr);
  9203. }
  9204. isize arg_index = 0;
  9205. isize arg_count = 0;
  9206. for_array(i, ce->args) {
  9207. Ast *arg = ce->args[i];
  9208. TypeAndValue tav = type_and_value_of_expr(arg);
  9209. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  9210. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  9211. Type *at = tav.type;
  9212. if (at->kind == Type_Tuple) {
  9213. arg_count += at->Tuple.variables.count;
  9214. } else {
  9215. arg_count++;
  9216. }
  9217. }
  9218. isize param_count = 0;
  9219. if (pt->params) {
  9220. GB_ASSERT(pt->params->kind == Type_Tuple);
  9221. param_count = pt->params->Tuple.variables.count;
  9222. }
  9223. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  9224. isize variadic_index = pt->variadic_index;
  9225. bool variadic = pt->variadic && variadic_index >= 0;
  9226. bool vari_expand = ce->ellipsis.pos.line != 0;
  9227. bool is_c_vararg = pt->c_vararg;
  9228. String proc_name = {};
  9229. if (p->entity != nullptr) {
  9230. proc_name = p->entity->token.string;
  9231. }
  9232. TokenPos pos = ast_token(ce->proc).pos;
  9233. TypeTuple *param_tuple = nullptr;
  9234. if (pt->params) {
  9235. GB_ASSERT(pt->params->kind == Type_Tuple);
  9236. param_tuple = &pt->params->Tuple;
  9237. }
  9238. for_array(i, ce->args) {
  9239. Ast *arg = ce->args[i];
  9240. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  9241. if (arg_tv.mode == Addressing_Type) {
  9242. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  9243. } else {
  9244. lbValue a = lb_build_expr(p, arg);
  9245. Type *at = a.type;
  9246. if (at->kind == Type_Tuple) {
  9247. for_array(i, at->Tuple.variables) {
  9248. Entity *e = at->Tuple.variables[i];
  9249. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  9250. args[arg_index++] = v;
  9251. }
  9252. } else {
  9253. args[arg_index++] = a;
  9254. }
  9255. }
  9256. }
  9257. if (param_count > 0) {
  9258. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  9259. GB_ASSERT(param_count < 1000000);
  9260. if (arg_count < param_count) {
  9261. isize end = cast(isize)param_count;
  9262. if (variadic) {
  9263. end = variadic_index;
  9264. }
  9265. while (arg_index < end) {
  9266. Entity *e = param_tuple->variables[arg_index];
  9267. GB_ASSERT(e->kind == Entity_Variable);
  9268. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  9269. }
  9270. }
  9271. if (is_c_vararg) {
  9272. GB_ASSERT(variadic);
  9273. GB_ASSERT(!vari_expand);
  9274. isize i = 0;
  9275. for (; i < variadic_index; i++) {
  9276. Entity *e = param_tuple->variables[i];
  9277. if (e->kind == Entity_Variable) {
  9278. args[i] = lb_emit_conv(p, args[i], e->type);
  9279. }
  9280. }
  9281. Type *variadic_type = param_tuple->variables[i]->type;
  9282. GB_ASSERT(is_type_slice(variadic_type));
  9283. variadic_type = base_type(variadic_type)->Slice.elem;
  9284. if (!is_type_any(variadic_type)) {
  9285. for (; i < arg_count; i++) {
  9286. args[i] = lb_emit_conv(p, args[i], variadic_type);
  9287. }
  9288. } else {
  9289. for (; i < arg_count; i++) {
  9290. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  9291. }
  9292. }
  9293. } else if (variadic) {
  9294. isize i = 0;
  9295. for (; i < variadic_index; i++) {
  9296. Entity *e = param_tuple->variables[i];
  9297. if (e->kind == Entity_Variable) {
  9298. args[i] = lb_emit_conv(p, args[i], e->type);
  9299. }
  9300. }
  9301. if (!vari_expand) {
  9302. Type *variadic_type = param_tuple->variables[i]->type;
  9303. GB_ASSERT(is_type_slice(variadic_type));
  9304. variadic_type = base_type(variadic_type)->Slice.elem;
  9305. for (; i < arg_count; i++) {
  9306. args[i] = lb_emit_conv(p, args[i], variadic_type);
  9307. }
  9308. }
  9309. } else {
  9310. for (isize i = 0; i < param_count; i++) {
  9311. Entity *e = param_tuple->variables[i];
  9312. if (e->kind == Entity_Variable) {
  9313. if (args[i].value == nullptr) {
  9314. continue;
  9315. }
  9316. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  9317. args[i] = lb_emit_conv(p, args[i], e->type);
  9318. }
  9319. }
  9320. }
  9321. if (variadic && !vari_expand && !is_c_vararg) {
  9322. // variadic call argument generation
  9323. Type *slice_type = param_tuple->variables[variadic_index]->type;
  9324. Type *elem_type = base_type(slice_type)->Slice.elem;
  9325. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  9326. isize slice_len = arg_count+1 - (variadic_index+1);
  9327. if (slice_len > 0) {
  9328. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  9329. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  9330. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  9331. lb_emit_store(p, addr, args[i]);
  9332. }
  9333. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  9334. lbValue len = lb_const_int(m, t_int, slice_len);
  9335. lb_fill_slice(p, slice, base_elem, len);
  9336. }
  9337. arg_count = param_count;
  9338. args[variadic_index] = lb_addr_load(p, slice);
  9339. }
  9340. }
  9341. if (variadic && variadic_index+1 < param_count) {
  9342. for (isize i = variadic_index+1; i < param_count; i++) {
  9343. Entity *e = param_tuple->variables[i];
  9344. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  9345. }
  9346. }
  9347. isize final_count = param_count;
  9348. if (is_c_vararg) {
  9349. final_count = arg_count;
  9350. }
  9351. if (param_tuple != nullptr) {
  9352. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  9353. Entity *e = param_tuple->variables[i];
  9354. if (args[i].type == nullptr) {
  9355. continue;
  9356. } else if (is_type_untyped_nil(args[i].type)) {
  9357. args[i] = lb_const_nil(m, e->type);
  9358. } else if (is_type_untyped_undef(args[i].type)) {
  9359. args[i] = lb_const_undef(m, e->type);
  9360. }
  9361. }
  9362. }
  9363. auto call_args = array_slice(args, 0, final_count);
  9364. return lb_emit_call(p, value, call_args, ce->inlining, p->copy_elision_hint.ast == expr);
  9365. }
  9366. bool lb_is_const(lbValue value) {
  9367. LLVMValueRef v = value.value;
  9368. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  9369. // TODO(bill): Is this correct behaviour?
  9370. return true;
  9371. }
  9372. if (LLVMIsConstant(v)) {
  9373. return true;
  9374. }
  9375. return false;
  9376. }
  9377. bool lb_is_const_or_global(lbValue value) {
  9378. if (lb_is_const(value)) {
  9379. return true;
  9380. }
  9381. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  9382. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  9383. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  9384. return false;
  9385. }
  9386. LLVMTypeRef elem = LLVMGetElementType(t);
  9387. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  9388. }
  9389. return false;
  9390. }
  9391. bool lb_is_const_nil(lbValue value) {
  9392. LLVMValueRef v = value.value;
  9393. if (LLVMIsConstant(v)) {
  9394. if (LLVMIsAConstantAggregateZero(v)) {
  9395. return true;
  9396. } else if (LLVMIsAConstantPointerNull(v)) {
  9397. return true;
  9398. }
  9399. }
  9400. return false;
  9401. }
  9402. String lb_get_const_string(lbModule *m, lbValue value) {
  9403. GB_ASSERT(lb_is_const(value));
  9404. GB_ASSERT(LLVMIsConstant(value.value));
  9405. Type *t = base_type(value.type);
  9406. GB_ASSERT(are_types_identical(t, t_string));
  9407. unsigned ptr_indices[1] = {0};
  9408. unsigned len_indices[1] = {1};
  9409. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  9410. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  9411. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  9412. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  9413. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  9414. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  9415. size_t length = 0;
  9416. char const *text = LLVMGetAsString(underlying_ptr, &length);
  9417. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  9418. return make_string(cast(u8 const *)text, real_length);
  9419. }
  9420. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  9421. GB_ASSERT(is_type_pointer(addr.type));
  9422. Type *type = type_deref(addr.type);
  9423. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  9424. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  9425. }
  9426. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  9427. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  9428. if (type_size_of(value.type) < 2) {
  9429. return value;
  9430. }
  9431. Type *original_type = value.type;
  9432. if (is_type_float(original_type)) {
  9433. i64 sz = type_size_of(original_type);
  9434. Type *integer_type = nullptr;
  9435. switch (sz) {
  9436. case 2: integer_type = t_u16; break;
  9437. case 4: integer_type = t_u32; break;
  9438. case 8: integer_type = t_u64; break;
  9439. }
  9440. GB_ASSERT(integer_type != nullptr);
  9441. value = lb_emit_transmute(p, value, integer_type);
  9442. }
  9443. char const *name = "llvm.bswap";
  9444. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  9445. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9446. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9447. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9448. LLVMValueRef args[1] = {};
  9449. args[0] = value.value;
  9450. lbValue res = {};
  9451. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9452. res.type = value.type;
  9453. if (is_type_float(original_type)) {
  9454. res = lb_emit_transmute(p, res, original_type);
  9455. }
  9456. res.type = end_type;
  9457. return res;
  9458. }
  9459. lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  9460. x = lb_emit_conv(p, x, type);
  9461. char const *name = "llvm.ctpop";
  9462. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9463. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9464. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9465. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9466. LLVMValueRef args[1] = {};
  9467. args[0] = x.value;
  9468. lbValue res = {};
  9469. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9470. res.type = type;
  9471. return res;
  9472. }
  9473. lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  9474. i64 sz = 8*type_size_of(type);
  9475. lbValue size = lb_const_int(p->module, type, cast(u64)sz);
  9476. lbValue count = lb_emit_count_ones(p, x, type);
  9477. return lb_emit_arith(p, Token_Sub, size, count, type);
  9478. }
  9479. lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  9480. x = lb_emit_conv(p, x, type);
  9481. char const *name = "llvm.cttz";
  9482. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9483. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9484. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9485. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9486. LLVMValueRef args[2] = {};
  9487. args[0] = x.value;
  9488. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  9489. lbValue res = {};
  9490. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9491. res.type = type;
  9492. return res;
  9493. }
  9494. lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  9495. x = lb_emit_conv(p, x, type);
  9496. char const *name = "llvm.ctlz";
  9497. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9498. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9499. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9500. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9501. LLVMValueRef args[2] = {};
  9502. args[0] = x.value;
  9503. args[1] = LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx));
  9504. lbValue res = {};
  9505. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9506. res.type = type;
  9507. return res;
  9508. }
  9509. lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  9510. x = lb_emit_conv(p, x, type);
  9511. char const *name = "llvm.bitreverse";
  9512. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  9513. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  9514. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  9515. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  9516. LLVMValueRef args[1] = {};
  9517. args[0] = x.value;
  9518. lbValue res = {};
  9519. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  9520. res.type = type;
  9521. return res;
  9522. }
  9523. lbValue lb_emit_bit_set_card(lbProcedure *p, lbValue x) {
  9524. GB_ASSERT(is_type_bit_set(x.type));
  9525. Type *underlying = bit_set_to_int(x.type);
  9526. lbValue card = lb_emit_count_ones(p, x, underlying);
  9527. return lb_emit_conv(p, card, t_int);
  9528. }
  9529. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  9530. lbLoopData data = {};
  9531. lbValue max = lb_const_int(p->module, t_int, count);
  9532. data.idx_addr = lb_add_local_generated(p, index_type, true);
  9533. data.body = lb_create_block(p, "loop.body");
  9534. data.done = lb_create_block(p, "loop.done");
  9535. data.loop = lb_create_block(p, "loop.loop");
  9536. lb_emit_jump(p, data.loop);
  9537. lb_start_block(p, data.loop);
  9538. data.idx = lb_addr_load(p, data.idx_addr);
  9539. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  9540. lb_emit_if(p, cond, data.body, data.done);
  9541. lb_start_block(p, data.body);
  9542. return data;
  9543. }
  9544. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  9545. if (data.idx_addr.addr.value != nullptr) {
  9546. lb_emit_increment(p, data.idx_addr.addr);
  9547. lb_emit_jump(p, data.loop);
  9548. lb_start_block(p, data.done);
  9549. }
  9550. }
  9551. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  9552. lbValue res = {};
  9553. res.type = t_llvm_bool;
  9554. Type *t = x.type;
  9555. if (is_type_enum(t)) {
  9556. if (op_kind == Token_CmpEq) {
  9557. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  9558. } else if (op_kind == Token_NotEq) {
  9559. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  9560. }
  9561. return res;
  9562. } else if (is_type_pointer(t)) {
  9563. if (op_kind == Token_CmpEq) {
  9564. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  9565. } else if (op_kind == Token_NotEq) {
  9566. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  9567. }
  9568. return res;
  9569. } else if (is_type_cstring(t)) {
  9570. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  9571. if (op_kind == Token_CmpEq) {
  9572. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  9573. } else if (op_kind == Token_NotEq) {
  9574. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  9575. }
  9576. return res;
  9577. } else if (is_type_proc(t)) {
  9578. if (op_kind == Token_CmpEq) {
  9579. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  9580. } else if (op_kind == Token_NotEq) {
  9581. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  9582. }
  9583. return res;
  9584. } else if (is_type_any(t)) {
  9585. // TODO(bill): is this correct behaviour for nil comparison for any?
  9586. lbValue data = lb_emit_struct_ev(p, x, 0);
  9587. lbValue ti = lb_emit_struct_ev(p, x, 1);
  9588. if (op_kind == Token_CmpEq) {
  9589. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  9590. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  9591. res.value = LLVMBuildOr(p->builder, a, b, "");
  9592. return res;
  9593. } else if (op_kind == Token_NotEq) {
  9594. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  9595. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  9596. res.value = LLVMBuildAnd(p->builder, a, b, "");
  9597. return res;
  9598. }
  9599. } else if (is_type_slice(t)) {
  9600. lbValue data = lb_emit_struct_ev(p, x, 0);
  9601. if (op_kind == Token_CmpEq) {
  9602. res.value = LLVMBuildIsNull(p->builder, data.value, "");
  9603. return res;
  9604. } else if (op_kind == Token_NotEq) {
  9605. res.value = LLVMBuildIsNotNull(p->builder, data.value, "");
  9606. return res;
  9607. }
  9608. } else if (is_type_dynamic_array(t)) {
  9609. lbValue data = lb_emit_struct_ev(p, x, 0);
  9610. if (op_kind == Token_CmpEq) {
  9611. res.value = LLVMBuildIsNull(p->builder, data.value, "");
  9612. return res;
  9613. } else if (op_kind == Token_NotEq) {
  9614. res.value = LLVMBuildIsNotNull(p->builder, data.value, "");
  9615. return res;
  9616. }
  9617. } else if (is_type_map(t)) {
  9618. lbValue hashes = lb_emit_struct_ev(p, x, 0);
  9619. lbValue data = lb_emit_struct_ev(p, hashes, 0);
  9620. return lb_emit_comp(p, op_kind, data, lb_zero(p->module, data.type));
  9621. } else if (is_type_union(t)) {
  9622. if (type_size_of(t) == 0) {
  9623. if (op_kind == Token_CmpEq) {
  9624. return lb_const_bool(p->module, t_llvm_bool, true);
  9625. } else if (op_kind == Token_NotEq) {
  9626. return lb_const_bool(p->module, t_llvm_bool, false);
  9627. }
  9628. } else if (is_type_union_maybe_pointer(t)) {
  9629. lbValue tag = lb_emit_transmute(p, x, t_rawptr);
  9630. return lb_emit_comp_against_nil(p, op_kind, tag);
  9631. } else {
  9632. lbValue tag = lb_emit_union_tag_value(p, x);
  9633. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  9634. }
  9635. } else if (is_type_typeid(t)) {
  9636. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  9637. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  9638. } else if (is_type_soa_struct(t)) {
  9639. Type *bt = base_type(t);
  9640. if (bt->Struct.soa_kind == StructSoa_Slice) {
  9641. LLVMValueRef the_value = {};
  9642. if (bt->Struct.fields.count == 0) {
  9643. lbValue len = lb_soa_struct_len(p, x);
  9644. the_value = len.value;
  9645. } else {
  9646. lbValue first_field = lb_emit_struct_ev(p, x, 0);
  9647. the_value = first_field.value;
  9648. }
  9649. if (op_kind == Token_CmpEq) {
  9650. res.value = LLVMBuildIsNull(p->builder, the_value, "");
  9651. return res;
  9652. } else if (op_kind == Token_NotEq) {
  9653. res.value = LLVMBuildIsNotNull(p->builder, the_value, "");
  9654. return res;
  9655. }
  9656. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  9657. LLVMValueRef the_value = {};
  9658. if (bt->Struct.fields.count == 0) {
  9659. lbValue cap = lb_soa_struct_cap(p, x);
  9660. the_value = cap.value;
  9661. } else {
  9662. lbValue first_field = lb_emit_struct_ev(p, x, 0);
  9663. the_value = first_field.value;
  9664. }
  9665. if (op_kind == Token_CmpEq) {
  9666. res.value = LLVMBuildIsNull(p->builder, the_value, "");
  9667. return res;
  9668. } else if (op_kind == Token_NotEq) {
  9669. res.value = LLVMBuildIsNotNull(p->builder, the_value, "");
  9670. return res;
  9671. }
  9672. }
  9673. } else if (is_type_struct(t) && type_has_nil(t)) {
  9674. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9675. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  9676. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  9677. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  9678. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  9679. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  9680. return res;
  9681. }
  9682. return {};
  9683. }
  9684. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  9685. Type *original_type = type;
  9686. type = base_type(type);
  9687. GB_ASSERT(is_type_comparable(type));
  9688. Type *pt = alloc_type_pointer(type);
  9689. LLVMTypeRef ptr_type = lb_type(m, pt);
  9690. auto key = hash_type(type);
  9691. lbProcedure **found = map_get(&m->equal_procs, key);
  9692. lbProcedure *compare_proc = nullptr;
  9693. if (found) {
  9694. compare_proc = *found;
  9695. GB_ASSERT(compare_proc != nullptr);
  9696. return {compare_proc->value, compare_proc->type};
  9697. }
  9698. static u32 proc_index = 0;
  9699. char buf[16] = {};
  9700. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  9701. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  9702. String proc_name = make_string_c(str);
  9703. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  9704. map_set(&m->equal_procs, key, p);
  9705. lb_begin_procedure_body(p);
  9706. LLVMValueRef x = LLVMGetParam(p->value, 0);
  9707. LLVMValueRef y = LLVMGetParam(p->value, 1);
  9708. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  9709. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  9710. lbValue lhs = {x, pt};
  9711. lbValue rhs = {y, pt};
  9712. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  9713. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  9714. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  9715. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  9716. lb_start_block(p, block_same_ptr);
  9717. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  9718. lb_start_block(p, block_diff_ptr);
  9719. if (type->kind == Type_Struct) {
  9720. type_set_offsets(type);
  9721. lbBlock *block_false = lb_create_block(p, "bfalse");
  9722. lbValue res = lb_const_bool(m, t_bool, true);
  9723. for_array(i, type->Struct.fields) {
  9724. lbBlock *next_block = lb_create_block(p, "btrue");
  9725. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  9726. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  9727. lbValue left = lb_emit_load(p, pleft);
  9728. lbValue right = lb_emit_load(p, pright);
  9729. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9730. lb_emit_if(p, ok, next_block, block_false);
  9731. lb_emit_jump(p, next_block);
  9732. lb_start_block(p, next_block);
  9733. }
  9734. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  9735. lb_start_block(p, block_false);
  9736. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  9737. } else if (type->kind == Type_Union) {
  9738. if (is_type_union_maybe_pointer(type)) {
  9739. Type *v = type->Union.variants[0];
  9740. Type *pv = alloc_type_pointer(v);
  9741. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  9742. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  9743. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9744. ok = lb_emit_conv(p, ok, t_bool);
  9745. LLVMBuildRet(p->builder, ok.value);
  9746. } else {
  9747. lbBlock *block_false = lb_create_block(p, "bfalse");
  9748. lbBlock *block_switch = lb_create_block(p, "bswitch");
  9749. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  9750. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  9751. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  9752. lb_emit_if(p, tag_eq, block_switch, block_false);
  9753. lb_start_block(p, block_switch);
  9754. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, cast(unsigned)type->Union.variants.count);
  9755. for_array(i, type->Union.variants) {
  9756. lbBlock *case_block = lb_create_block(p, "bcase");
  9757. lb_start_block(p, case_block);
  9758. Type *v = type->Union.variants[i];
  9759. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  9760. Type *vp = alloc_type_pointer(v);
  9761. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  9762. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  9763. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9764. ok = lb_emit_conv(p, ok, t_bool);
  9765. LLVMBuildRet(p->builder, ok.value);
  9766. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  9767. }
  9768. lb_start_block(p, block_false);
  9769. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  9770. }
  9771. } else {
  9772. lbValue left = lb_emit_load(p, lhs);
  9773. lbValue right = lb_emit_load(p, rhs);
  9774. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  9775. ok = lb_emit_conv(p, ok, t_bool);
  9776. LLVMBuildRet(p->builder, ok.value);
  9777. }
  9778. lb_end_procedure_body(p);
  9779. compare_proc = p;
  9780. return {compare_proc->value, compare_proc->type};
  9781. }
  9782. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  9783. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  9784. i64 sz = type_size_of(type);
  9785. if (1 <= sz && sz <= 16) {
  9786. char name[20] = {};
  9787. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  9788. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9789. args[0] = data;
  9790. args[1] = seed;
  9791. return lb_emit_runtime_call(p, name, args);
  9792. }
  9793. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9794. args[0] = data;
  9795. args[1] = seed;
  9796. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  9797. return lb_emit_runtime_call(p, "default_hasher_n", args);
  9798. }
  9799. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  9800. Type *original_type = type;
  9801. type = core_type(type);
  9802. GB_ASSERT(is_type_valid_for_keys(type));
  9803. Type *pt = alloc_type_pointer(type);
  9804. LLVMTypeRef ptr_type = lb_type(m, pt);
  9805. auto key = hash_type(type);
  9806. lbProcedure **found = map_get(&m->hasher_procs, key);
  9807. if (found) {
  9808. GB_ASSERT(*found != nullptr);
  9809. return {(*found)->value, (*found)->type};
  9810. }
  9811. static u32 proc_index = 0;
  9812. char buf[16] = {};
  9813. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  9814. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  9815. String proc_name = make_string_c(str);
  9816. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  9817. map_set(&m->hasher_procs, key, p);
  9818. lb_begin_procedure_body(p);
  9819. defer (lb_end_procedure_body(p));
  9820. LLVMValueRef x = LLVMGetParam(p->value, 0);
  9821. LLVMValueRef y = LLVMGetParam(p->value, 1);
  9822. lbValue data = {x, t_rawptr};
  9823. lbValue seed = {y, t_uintptr};
  9824. LLVMAttributeRef nonnull_attr = lb_create_enum_attribute(m->ctx, "nonnull");
  9825. LLVMAddAttributeAtIndex(p->value, 1+0, nonnull_attr);
  9826. if (is_type_simple_compare(type)) {
  9827. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  9828. LLVMBuildRet(p->builder, res.value);
  9829. return {p->value, p->type};
  9830. }
  9831. if (type->kind == Type_Struct) {
  9832. type_set_offsets(type);
  9833. data = lb_emit_conv(p, data, t_u8_ptr);
  9834. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9835. for_array(i, type->Struct.fields) {
  9836. i64 offset = type->Struct.offsets[i];
  9837. Entity *field = type->Struct.fields[i];
  9838. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  9839. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  9840. args[0] = ptr;
  9841. args[1] = seed;
  9842. seed = lb_emit_call(p, field_hasher, args);
  9843. }
  9844. LLVMBuildRet(p->builder, seed.value);
  9845. } else if (type->kind == Type_Union) {
  9846. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9847. if (is_type_union_maybe_pointer(type)) {
  9848. Type *v = type->Union.variants[0];
  9849. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  9850. args[0] = data;
  9851. args[1] = seed;
  9852. lbValue res = lb_emit_call(p, variant_hasher, args);
  9853. LLVMBuildRet(p->builder, res.value);
  9854. }
  9855. lbBlock *end_block = lb_create_block(p, "bend");
  9856. data = lb_emit_conv(p, data, pt);
  9857. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  9858. lbValue tag = lb_emit_load(p, tag_ptr);
  9859. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  9860. for_array(i, type->Union.variants) {
  9861. lbBlock *case_block = lb_create_block(p, "bcase");
  9862. lb_start_block(p, case_block);
  9863. Type *v = type->Union.variants[i];
  9864. Type *vp = alloc_type_pointer(v);
  9865. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  9866. lbValue variant_hasher = lb_get_hasher_proc_for_type(m, v);
  9867. args[0] = data;
  9868. args[1] = seed;
  9869. lbValue res = lb_emit_call(p, variant_hasher, args);
  9870. LLVMBuildRet(p->builder, res.value);
  9871. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  9872. }
  9873. lb_start_block(p, end_block);
  9874. LLVMBuildRet(p->builder, seed.value);
  9875. } else if (type->kind == Type_Array) {
  9876. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  9877. lb_addr_store(p, pres, seed);
  9878. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9879. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  9880. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  9881. data = lb_emit_conv(p, data, pt);
  9882. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  9883. args[0] = ptr;
  9884. args[1] = lb_addr_load(p, pres);
  9885. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  9886. lb_addr_store(p, pres, new_seed);
  9887. lb_loop_end(p, loop_data);
  9888. lbValue res = lb_addr_load(p, pres);
  9889. LLVMBuildRet(p->builder, res.value);
  9890. } else if (type->kind == Type_EnumeratedArray) {
  9891. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  9892. lb_addr_store(p, res, seed);
  9893. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9894. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  9895. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  9896. data = lb_emit_conv(p, data, pt);
  9897. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  9898. args[0] = ptr;
  9899. args[1] = lb_addr_load(p, res);
  9900. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  9901. lb_addr_store(p, res, new_seed);
  9902. lb_loop_end(p, loop_data);
  9903. lbValue vres = lb_addr_load(p, res);
  9904. LLVMBuildRet(p->builder, vres.value);
  9905. } else if (is_type_cstring(type)) {
  9906. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9907. args[0] = data;
  9908. args[1] = seed;
  9909. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  9910. LLVMBuildRet(p->builder, res.value);
  9911. } else if (is_type_string(type)) {
  9912. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9913. args[0] = data;
  9914. args[1] = seed;
  9915. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  9916. LLVMBuildRet(p->builder, res.value);
  9917. } else {
  9918. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  9919. }
  9920. return {p->value, p->type};
  9921. }
  9922. lbValue lb_compare_records(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right, Type *type) {
  9923. GB_ASSERT((is_type_struct(type) || is_type_union(type)) && is_type_comparable(type));
  9924. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  9925. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  9926. lbValue res = {};
  9927. if (is_type_simple_compare(type)) {
  9928. // TODO(bill): Test to see if this is actually faster!!!!
  9929. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9930. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9931. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9932. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  9933. res = lb_emit_runtime_call(p, "memory_equal", args);
  9934. } else {
  9935. lbValue value = lb_get_equal_proc_for_type(p->module, type);
  9936. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9937. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  9938. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  9939. res = lb_emit_call(p, value, args);
  9940. }
  9941. if (op_kind == Token_NotEq) {
  9942. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  9943. }
  9944. return res;
  9945. }
  9946. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  9947. Type *a = core_type(left.type);
  9948. Type *b = core_type(right.type);
  9949. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  9950. lbValue nil_check = {};
  9951. if (is_type_untyped_nil(left.type)) {
  9952. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  9953. } else if (is_type_untyped_nil(right.type)) {
  9954. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  9955. }
  9956. if (nil_check.value != nullptr) {
  9957. return nil_check;
  9958. }
  9959. if (are_types_identical(a, b)) {
  9960. // NOTE(bill): No need for a conversion
  9961. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  9962. left = lb_emit_conv(p, left, right.type);
  9963. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  9964. right = lb_emit_conv(p, right, left.type);
  9965. } else {
  9966. Type *lt = left.type;
  9967. Type *rt = right.type;
  9968. lt = left.type;
  9969. rt = right.type;
  9970. i64 ls = type_size_of(lt);
  9971. i64 rs = type_size_of(rt);
  9972. // NOTE(bill): Quick heuristic, larger types are usually the target type
  9973. if (ls < rs) {
  9974. left = lb_emit_conv(p, left, rt);
  9975. } else if (ls > rs) {
  9976. right = lb_emit_conv(p, right, lt);
  9977. } else {
  9978. if (is_type_union(rt)) {
  9979. left = lb_emit_conv(p, left, rt);
  9980. } else {
  9981. right = lb_emit_conv(p, right, lt);
  9982. }
  9983. }
  9984. }
  9985. if (is_type_array(a) || is_type_enumerated_array(a)) {
  9986. Type *tl = base_type(a);
  9987. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  9988. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  9989. TokenKind cmp_op = Token_And;
  9990. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  9991. if (op_kind == Token_NotEq) {
  9992. res = lb_const_bool(p->module, t_llvm_bool, false);
  9993. cmp_op = Token_Or;
  9994. } else if (op_kind == Token_CmpEq) {
  9995. res = lb_const_bool(p->module, t_llvm_bool, true);
  9996. cmp_op = Token_And;
  9997. }
  9998. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  9999. i32 count = 0;
  10000. switch (tl->kind) {
  10001. case Type_Array: count = cast(i32)tl->Array.count; break;
  10002. case Type_EnumeratedArray: count = cast(i32)tl->EnumeratedArray.count; break;
  10003. }
  10004. if (inline_array_arith) {
  10005. // inline
  10006. lbAddr val = lb_add_local_generated(p, t_bool, false);
  10007. lb_addr_store(p, val, res);
  10008. for (i32 i = 0; i < count; i++) {
  10009. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  10010. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  10011. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  10012. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  10013. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  10014. }
  10015. return lb_addr_load(p, val);
  10016. } else {
  10017. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  10018. // TODO(bill): Test to see if this is actually faster!!!!
  10019. auto args = array_make<lbValue>(permanent_allocator(), 3);
  10020. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  10021. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  10022. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  10023. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  10024. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  10025. return lb_emit_conv(p, res, t_bool);
  10026. } else {
  10027. lbAddr val = lb_add_local_generated(p, t_bool, false);
  10028. lb_addr_store(p, val, res);
  10029. auto loop_data = lb_loop_start(p, count, t_i32);
  10030. {
  10031. lbValue i = loop_data.idx;
  10032. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  10033. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  10034. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  10035. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  10036. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  10037. }
  10038. lb_loop_end(p, loop_data);
  10039. return lb_addr_load(p, val);
  10040. }
  10041. }
  10042. }
  10043. if ((is_type_struct(a) || is_type_union(a)) && is_type_comparable(a)) {
  10044. return lb_compare_records(p, op_kind, left, right, a);
  10045. }
  10046. if ((is_type_struct(b) || is_type_union(b)) && is_type_comparable(b)) {
  10047. return lb_compare_records(p, op_kind, left, right, b);
  10048. }
  10049. if (is_type_string(a)) {
  10050. if (is_type_cstring(a)) {
  10051. left = lb_emit_conv(p, left, t_string);
  10052. right = lb_emit_conv(p, right, t_string);
  10053. }
  10054. char const *runtime_procedure = nullptr;
  10055. switch (op_kind) {
  10056. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  10057. case Token_NotEq: runtime_procedure = "string_ne"; break;
  10058. case Token_Lt: runtime_procedure = "string_lt"; break;
  10059. case Token_Gt: runtime_procedure = "string_gt"; break;
  10060. case Token_LtEq: runtime_procedure = "string_le"; break;
  10061. case Token_GtEq: runtime_procedure = "string_gt"; break;
  10062. }
  10063. GB_ASSERT(runtime_procedure != nullptr);
  10064. auto args = array_make<lbValue>(permanent_allocator(), 2);
  10065. args[0] = left;
  10066. args[1] = right;
  10067. return lb_emit_runtime_call(p, runtime_procedure, args);
  10068. }
  10069. if (is_type_complex(a)) {
  10070. char const *runtime_procedure = "";
  10071. i64 sz = 8*type_size_of(a);
  10072. switch (sz) {
  10073. case 32:
  10074. switch (op_kind) {
  10075. case Token_CmpEq: runtime_procedure = "complex32_eq"; break;
  10076. case Token_NotEq: runtime_procedure = "complex32_ne"; break;
  10077. }
  10078. break;
  10079. case 64:
  10080. switch (op_kind) {
  10081. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  10082. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  10083. }
  10084. break;
  10085. case 128:
  10086. switch (op_kind) {
  10087. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  10088. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  10089. }
  10090. break;
  10091. }
  10092. GB_ASSERT(runtime_procedure != nullptr);
  10093. auto args = array_make<lbValue>(permanent_allocator(), 2);
  10094. args[0] = left;
  10095. args[1] = right;
  10096. return lb_emit_runtime_call(p, runtime_procedure, args);
  10097. }
  10098. if (is_type_quaternion(a)) {
  10099. char const *runtime_procedure = "";
  10100. i64 sz = 8*type_size_of(a);
  10101. switch (sz) {
  10102. case 64:
  10103. switch (op_kind) {
  10104. case Token_CmpEq: runtime_procedure = "quaternion64_eq"; break;
  10105. case Token_NotEq: runtime_procedure = "quaternion64_ne"; break;
  10106. }
  10107. break;
  10108. case 128:
  10109. switch (op_kind) {
  10110. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  10111. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  10112. }
  10113. break;
  10114. case 256:
  10115. switch (op_kind) {
  10116. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  10117. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  10118. }
  10119. break;
  10120. }
  10121. GB_ASSERT(runtime_procedure != nullptr);
  10122. auto args = array_make<lbValue>(permanent_allocator(), 2);
  10123. args[0] = left;
  10124. args[1] = right;
  10125. return lb_emit_runtime_call(p, runtime_procedure, args);
  10126. }
  10127. if (is_type_bit_set(a)) {
  10128. switch (op_kind) {
  10129. case Token_Lt:
  10130. case Token_LtEq:
  10131. case Token_Gt:
  10132. case Token_GtEq:
  10133. {
  10134. Type *it = bit_set_to_int(a);
  10135. lbValue lhs = lb_emit_transmute(p, left, it);
  10136. lbValue rhs = lb_emit_transmute(p, right, it);
  10137. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  10138. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  10139. // (lhs & rhs) == lhs
  10140. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  10141. res.type = t_llvm_bool;
  10142. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  10143. // (lhs & rhs) == rhs
  10144. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  10145. res.type = t_llvm_bool;
  10146. }
  10147. // NOTE(bill): Strict subsets
  10148. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  10149. // res &~ (lhs == rhs)
  10150. lbValue eq = {};
  10151. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  10152. eq.type = t_llvm_bool;
  10153. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  10154. }
  10155. return res;
  10156. }
  10157. case Token_CmpEq:
  10158. case Token_NotEq:
  10159. {
  10160. LLVMIntPredicate pred = {};
  10161. switch (op_kind) {
  10162. case Token_CmpEq: pred = LLVMIntEQ; break;
  10163. case Token_NotEq: pred = LLVMIntNE; break;
  10164. }
  10165. lbValue res = {};
  10166. res.type = t_llvm_bool;
  10167. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  10168. return res;
  10169. }
  10170. }
  10171. }
  10172. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  10173. Type *t = left.type;
  10174. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  10175. Type *platform_type = integer_endian_type_to_platform_type(t);
  10176. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  10177. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  10178. left = x;
  10179. right = y;
  10180. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  10181. Type *platform_type = integer_endian_type_to_platform_type(t);
  10182. lbValue x = lb_emit_conv(p, left, platform_type);
  10183. lbValue y = lb_emit_conv(p, right, platform_type);
  10184. left = x;
  10185. right = y;
  10186. }
  10187. }
  10188. a = core_type(left.type);
  10189. b = core_type(right.type);
  10190. lbValue res = {};
  10191. res.type = t_llvm_bool;
  10192. if (is_type_integer(a) ||
  10193. is_type_boolean(a) ||
  10194. is_type_pointer(a) ||
  10195. is_type_proc(a) ||
  10196. is_type_enum(a)) {
  10197. LLVMIntPredicate pred = {};
  10198. if (is_type_unsigned(left.type)) {
  10199. switch (op_kind) {
  10200. case Token_Gt: pred = LLVMIntUGT; break;
  10201. case Token_GtEq: pred = LLVMIntUGE; break;
  10202. case Token_Lt: pred = LLVMIntULT; break;
  10203. case Token_LtEq: pred = LLVMIntULE; break;
  10204. }
  10205. } else {
  10206. switch (op_kind) {
  10207. case Token_Gt: pred = LLVMIntSGT; break;
  10208. case Token_GtEq: pred = LLVMIntSGE; break;
  10209. case Token_Lt: pred = LLVMIntSLT; break;
  10210. case Token_LtEq: pred = LLVMIntSLE; break;
  10211. }
  10212. }
  10213. switch (op_kind) {
  10214. case Token_CmpEq: pred = LLVMIntEQ; break;
  10215. case Token_NotEq: pred = LLVMIntNE; break;
  10216. }
  10217. LLVMValueRef lhs = left.value;
  10218. LLVMValueRef rhs = right.value;
  10219. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  10220. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  10221. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  10222. }
  10223. }
  10224. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  10225. } else if (is_type_float(a)) {
  10226. LLVMRealPredicate pred = {};
  10227. switch (op_kind) {
  10228. case Token_CmpEq: pred = LLVMRealOEQ; break;
  10229. case Token_Gt: pred = LLVMRealOGT; break;
  10230. case Token_GtEq: pred = LLVMRealOGE; break;
  10231. case Token_Lt: pred = LLVMRealOLT; break;
  10232. case Token_LtEq: pred = LLVMRealOLE; break;
  10233. case Token_NotEq: pred = LLVMRealONE; break;
  10234. }
  10235. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  10236. } else if (is_type_typeid(a)) {
  10237. LLVMIntPredicate pred = {};
  10238. switch (op_kind) {
  10239. case Token_Gt: pred = LLVMIntUGT; break;
  10240. case Token_GtEq: pred = LLVMIntUGE; break;
  10241. case Token_Lt: pred = LLVMIntULT; break;
  10242. case Token_LtEq: pred = LLVMIntULE; break;
  10243. case Token_CmpEq: pred = LLVMIntEQ; break;
  10244. case Token_NotEq: pred = LLVMIntNE; break;
  10245. }
  10246. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  10247. } else {
  10248. 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)));
  10249. }
  10250. return res;
  10251. }
  10252. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  10253. lbProcedure **found = map_get(&m->gen->anonymous_proc_lits, hash_pointer(expr));
  10254. if (found) {
  10255. return lb_find_procedure_value_from_entity(m, (*found)->entity);
  10256. }
  10257. ast_node(pl, ProcLit, expr);
  10258. // NOTE(bill): Generate a new name
  10259. // parent$count
  10260. isize name_len = prefix_name.len + 1 + 8 + 1;
  10261. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  10262. i32 name_id = cast(i32)m->gen->anonymous_proc_lits.entries.count;
  10263. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  10264. String name = make_string((u8 *)name_text, name_len-1);
  10265. Type *type = type_of_expr(expr);
  10266. Token token = {};
  10267. token.pos = ast_token(expr).pos;
  10268. token.kind = Token_Ident;
  10269. token.string = name;
  10270. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  10271. e->file = expr->file;
  10272. e->decl_info = pl->decl;
  10273. e->code_gen_module = m;
  10274. lbProcedure *p = lb_create_procedure(m, e);
  10275. lbValue value = {};
  10276. value.value = p->value;
  10277. value.type = p->type;
  10278. array_add(&m->procedures_to_generate, p);
  10279. if (parent != nullptr) {
  10280. array_add(&parent->children, p);
  10281. } else {
  10282. string_map_set(&m->members, name, value);
  10283. }
  10284. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  10285. map_set(&m->gen->anonymous_proc_lits, hash_pointer(expr), p);
  10286. return value;
  10287. }
  10288. lbValue lb_emit_union_cast_only_ok_check(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  10289. GB_ASSERT(is_type_tuple(type));
  10290. lbModule *m = p->module;
  10291. Type *src_type = value.type;
  10292. bool is_ptr = is_type_pointer(src_type);
  10293. // IMPORTANT NOTE(bill): This assumes that the value is completely ignored
  10294. // so when it does an assignment, it complete ignores the value.
  10295. // Just make it two booleans and ignore the first one
  10296. //
  10297. // _, ok := x.(T);
  10298. //
  10299. Type *ok_type = type->Tuple.variables[1]->type;
  10300. Type *gen_tuple_types[2] = {};
  10301. gen_tuple_types[0] = ok_type;
  10302. gen_tuple_types[1] = ok_type;
  10303. Type *gen_tuple = alloc_type_tuple_from_field_types(gen_tuple_types, gb_count_of(gen_tuple_types), false, true);
  10304. lbAddr v = lb_add_local_generated(p, gen_tuple, false);
  10305. if (is_ptr) {
  10306. value = lb_emit_load(p, value);
  10307. }
  10308. Type *src = base_type(type_deref(src_type));
  10309. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  10310. Type *dst = type->Tuple.variables[0]->type;
  10311. lbValue cond = {};
  10312. if (is_type_union_maybe_pointer(src)) {
  10313. lbValue data = lb_emit_transmute(p, value, dst);
  10314. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  10315. } else {
  10316. lbValue tag = lb_emit_union_tag_value(p, value);
  10317. lbValue dst_tag = lb_const_union_tag(m, src, dst);
  10318. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  10319. }
  10320. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  10321. lb_emit_store(p, gep1, cond);
  10322. return lb_addr_load(p, v);
  10323. }
  10324. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  10325. lbModule *m = p->module;
  10326. Type *src_type = value.type;
  10327. bool is_ptr = is_type_pointer(src_type);
  10328. bool is_tuple = true;
  10329. Type *tuple = type;
  10330. if (type->kind != Type_Tuple) {
  10331. is_tuple = false;
  10332. tuple = make_optional_ok_type(type);
  10333. }
  10334. lbAddr v = lb_add_local_generated(p, tuple, true);
  10335. if (is_ptr) {
  10336. value = lb_emit_load(p, value);
  10337. }
  10338. Type *src = base_type(type_deref(src_type));
  10339. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  10340. Type *dst = tuple->Tuple.variables[0]->type;
  10341. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  10342. lbValue tag = {};
  10343. lbValue dst_tag = {};
  10344. lbValue cond = {};
  10345. lbValue data = {};
  10346. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  10347. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  10348. if (is_type_union_maybe_pointer(src)) {
  10349. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  10350. } else {
  10351. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  10352. dst_tag = lb_const_union_tag(m, src, dst);
  10353. }
  10354. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  10355. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  10356. if (data.value != nullptr) {
  10357. GB_ASSERT(is_type_union_maybe_pointer(src));
  10358. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  10359. } else {
  10360. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  10361. }
  10362. lb_emit_if(p, cond, ok_block, end_block);
  10363. lb_start_block(p, ok_block);
  10364. if (data.value == nullptr) {
  10365. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  10366. }
  10367. lb_emit_store(p, gep0, data);
  10368. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  10369. lb_emit_jump(p, end_block);
  10370. lb_start_block(p, end_block);
  10371. if (!is_tuple) {
  10372. {
  10373. // NOTE(bill): Panic on invalid conversion
  10374. Type *dst_type = tuple->Tuple.variables[0]->type;
  10375. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  10376. auto args = array_make<lbValue>(permanent_allocator(), 7);
  10377. args[0] = ok;
  10378. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  10379. args[2] = lb_const_int(m, t_i32, pos.line);
  10380. args[3] = lb_const_int(m, t_i32, pos.column);
  10381. args[4] = lb_typeid(m, src_type);
  10382. args[5] = lb_typeid(m, dst_type);
  10383. args[6] = lb_emit_conv(p, value_, t_rawptr);
  10384. lb_emit_runtime_call(p, "type_assertion_check2", args);
  10385. }
  10386. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  10387. }
  10388. return lb_addr_load(p, v);
  10389. }
  10390. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  10391. lbModule *m = p->module;
  10392. Type *src_type = value.type;
  10393. if (is_type_pointer(src_type)) {
  10394. value = lb_emit_load(p, value);
  10395. }
  10396. bool is_tuple = true;
  10397. Type *tuple = type;
  10398. if (type->kind != Type_Tuple) {
  10399. is_tuple = false;
  10400. tuple = make_optional_ok_type(type);
  10401. }
  10402. Type *dst_type = tuple->Tuple.variables[0]->type;
  10403. lbAddr v = lb_add_local_generated(p, tuple, true);
  10404. lbValue dst_typeid = lb_typeid(m, dst_type);
  10405. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  10406. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  10407. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  10408. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  10409. lb_emit_if(p, cond, ok_block, end_block);
  10410. lb_start_block(p, ok_block);
  10411. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  10412. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  10413. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  10414. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  10415. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  10416. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  10417. lb_emit_jump(p, end_block);
  10418. lb_start_block(p, end_block);
  10419. if (!is_tuple) {
  10420. // NOTE(bill): Panic on invalid conversion
  10421. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  10422. auto args = array_make<lbValue>(permanent_allocator(), 7);
  10423. args[0] = ok;
  10424. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  10425. args[2] = lb_const_int(m, t_i32, pos.line);
  10426. args[3] = lb_const_int(m, t_i32, pos.column);
  10427. args[4] = any_typeid;
  10428. args[5] = dst_typeid;
  10429. args[6] = lb_emit_struct_ev(p, value, 0);;
  10430. lb_emit_runtime_call(p, "type_assertion_check2", args);
  10431. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  10432. }
  10433. return v;
  10434. }
  10435. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  10436. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  10437. }
  10438. lbValue lb_find_ident(lbProcedure *p, lbModule *m, Entity *e, Ast *expr) {
  10439. auto *found = map_get(&m->values, hash_entity(e));
  10440. if (found) {
  10441. auto v = *found;
  10442. // NOTE(bill): This is because pointers are already pointers in LLVM
  10443. if (is_type_proc(v.type)) {
  10444. return v;
  10445. }
  10446. return lb_emit_load(p, v);
  10447. } else if (e != nullptr && e->kind == Entity_Variable) {
  10448. return lb_addr_load(p, lb_build_addr(p, expr));
  10449. }
  10450. if (e->kind == Entity_Procedure) {
  10451. return lb_find_procedure_value_from_entity(m, e);
  10452. }
  10453. if (USE_SEPARTE_MODULES) {
  10454. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  10455. if (other_module != m) {
  10456. String name = lb_get_entity_name(other_module, e);
  10457. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  10458. lbValue g = {};
  10459. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  10460. g.type = alloc_type_pointer(e->type);
  10461. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  10462. lb_add_entity(m, e, g);
  10463. lb_add_member(m, name, g);
  10464. return lb_emit_load(p, g);
  10465. }
  10466. }
  10467. String pkg = {};
  10468. if (e->pkg) {
  10469. pkg = e->pkg->name;
  10470. }
  10471. gb_printf_err("Error in: %s\n", token_pos_to_string(ast_token(expr).pos));
  10472. 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);
  10473. return {};
  10474. }
  10475. bool lb_is_expr_constant_zero(Ast *expr) {
  10476. GB_ASSERT(expr != nullptr);
  10477. auto v = exact_value_to_integer(expr->tav.value);
  10478. if (v.kind == ExactValue_Integer) {
  10479. return big_int_cmp_zero(&v.value_integer) == 0;
  10480. }
  10481. return false;
  10482. }
  10483. lbValue lb_build_unary_and(lbProcedure *p, Ast *expr) {
  10484. ast_node(ue, UnaryExpr, expr);
  10485. auto tv = type_and_value_of_expr(expr);
  10486. Ast *ue_expr = unparen_expr(ue->expr);
  10487. if (ue_expr->kind == Ast_IndexExpr && tv.mode == Addressing_OptionalOkPtr && is_type_tuple(tv.type)) {
  10488. Type *tuple = tv.type;
  10489. Type *map_type = type_of_expr(ue_expr->IndexExpr.expr);
  10490. Type *ot = base_type(map_type);
  10491. Type *t = base_type(type_deref(ot));
  10492. bool deref = t != ot;
  10493. GB_ASSERT(t->kind == Type_Map);
  10494. ast_node(ie, IndexExpr, ue_expr);
  10495. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  10496. if (deref) {
  10497. map_val = lb_emit_load(p, map_val);
  10498. }
  10499. lbValue key = lb_build_expr(p, ie->index);
  10500. key = lb_emit_conv(p, key, t->Map.key);
  10501. Type *result_type = type_of_expr(expr);
  10502. lbAddr addr = lb_addr_map(map_val, key, t, alloc_type_pointer(t->Map.value));
  10503. lbValue ptr = lb_addr_get_ptr(p, addr);
  10504. lbValue ok = lb_emit_comp_against_nil(p, Token_NotEq, ptr);
  10505. ok = lb_emit_conv(p, ok, tuple->Tuple.variables[1]->type);
  10506. lbAddr res = lb_add_local_generated(p, tuple, false);
  10507. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  10508. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  10509. lb_emit_store(p, gep0, ptr);
  10510. lb_emit_store(p, gep1, ok);
  10511. return lb_addr_load(p, res);
  10512. } if (ue_expr->kind == Ast_CompoundLit) {
  10513. lbValue v = lb_build_expr(p, ue->expr);
  10514. Type *type = v.type;
  10515. lbAddr addr = {};
  10516. if (p->is_startup) {
  10517. addr = lb_add_global_generated(p->module, type, v);
  10518. } else {
  10519. addr = lb_add_local_generated(p, type, false);
  10520. }
  10521. lb_addr_store(p, addr, v);
  10522. return addr.addr;
  10523. } else if (ue_expr->kind == Ast_TypeAssertion) {
  10524. if (is_type_tuple(tv.type)) {
  10525. Type *tuple = tv.type;
  10526. Type *ptr_type = tuple->Tuple.variables[0]->type;
  10527. Type *ok_type = tuple->Tuple.variables[1]->type;
  10528. ast_node(ta, TypeAssertion, ue_expr);
  10529. TokenPos pos = ast_token(expr).pos;
  10530. Type *type = type_of_expr(ue_expr);
  10531. GB_ASSERT(!is_type_tuple(type));
  10532. lbValue e = lb_build_expr(p, ta->expr);
  10533. Type *t = type_deref(e.type);
  10534. if (is_type_union(t)) {
  10535. lbValue v = e;
  10536. if (!is_type_pointer(v.type)) {
  10537. v = lb_address_from_load_or_generate_local(p, v);
  10538. }
  10539. Type *src_type = type_deref(v.type);
  10540. Type *dst_type = type;
  10541. lbValue src_tag = {};
  10542. lbValue dst_tag = {};
  10543. if (is_type_union_maybe_pointer(src_type)) {
  10544. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  10545. dst_tag = lb_const_bool(p->module, t_bool, true);
  10546. } else {
  10547. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  10548. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  10549. }
  10550. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  10551. lbValue data_ptr = lb_emit_conv(p, v, ptr_type);
  10552. lbAddr res = lb_add_local_generated(p, tuple, true);
  10553. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  10554. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  10555. lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type)));
  10556. lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type));
  10557. return lb_addr_load(p, res);
  10558. } else if (is_type_any(t)) {
  10559. lbValue v = e;
  10560. if (is_type_pointer(v.type)) {
  10561. v = lb_emit_load(p, v);
  10562. }
  10563. lbValue data_ptr = lb_emit_conv(p, lb_emit_struct_ev(p, v, 0), ptr_type);
  10564. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  10565. lbValue id = lb_typeid(p->module, type);
  10566. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  10567. lbAddr res = lb_add_local_generated(p, tuple, false);
  10568. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  10569. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  10570. lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type)));
  10571. lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type));
  10572. return lb_addr_load(p, res);
  10573. } else {
  10574. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  10575. }
  10576. } else {
  10577. GB_ASSERT(is_type_pointer(tv.type));
  10578. ast_node(ta, TypeAssertion, ue_expr);
  10579. TokenPos pos = ast_token(expr).pos;
  10580. Type *type = type_of_expr(ue_expr);
  10581. GB_ASSERT(!is_type_tuple(type));
  10582. lbValue e = lb_build_expr(p, ta->expr);
  10583. Type *t = type_deref(e.type);
  10584. if (is_type_union(t)) {
  10585. lbValue v = e;
  10586. if (!is_type_pointer(v.type)) {
  10587. v = lb_address_from_load_or_generate_local(p, v);
  10588. }
  10589. Type *src_type = type_deref(v.type);
  10590. Type *dst_type = type;
  10591. lbValue src_tag = {};
  10592. lbValue dst_tag = {};
  10593. if (is_type_union_maybe_pointer(src_type)) {
  10594. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  10595. dst_tag = lb_const_bool(p->module, t_bool, true);
  10596. } else {
  10597. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  10598. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  10599. }
  10600. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  10601. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10602. args[0] = ok;
  10603. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  10604. args[2] = lb_const_int(p->module, t_i32, pos.line);
  10605. args[3] = lb_const_int(p->module, t_i32, pos.column);
  10606. args[4] = lb_typeid(p->module, src_type);
  10607. args[5] = lb_typeid(p->module, dst_type);
  10608. lb_emit_runtime_call(p, "type_assertion_check", args);
  10609. lbValue data_ptr = v;
  10610. return lb_emit_conv(p, data_ptr, tv.type);
  10611. } else if (is_type_any(t)) {
  10612. lbValue v = e;
  10613. if (is_type_pointer(v.type)) {
  10614. v = lb_emit_load(p, v);
  10615. }
  10616. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  10617. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  10618. lbValue id = lb_typeid(p->module, type);
  10619. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  10620. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10621. args[0] = ok;
  10622. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  10623. args[2] = lb_const_int(p->module, t_i32, pos.line);
  10624. args[3] = lb_const_int(p->module, t_i32, pos.column);
  10625. args[4] = any_id;
  10626. args[5] = id;
  10627. lb_emit_runtime_call(p, "type_assertion_check", args);
  10628. return lb_emit_conv(p, data_ptr, tv.type);
  10629. } else {
  10630. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  10631. }
  10632. }
  10633. }
  10634. return lb_build_addr_ptr(p, ue->expr);
  10635. }
  10636. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  10637. lbModule *m = p->module;
  10638. u16 prev_state_flags = p->state_flags;
  10639. defer (p->state_flags = prev_state_flags);
  10640. if (expr->state_flags != 0) {
  10641. u16 in = expr->state_flags;
  10642. u16 out = p->state_flags;
  10643. if (in & StateFlag_bounds_check) {
  10644. out |= StateFlag_bounds_check;
  10645. out &= ~StateFlag_no_bounds_check;
  10646. } else if (in & StateFlag_no_bounds_check) {
  10647. out |= StateFlag_no_bounds_check;
  10648. out &= ~StateFlag_bounds_check;
  10649. }
  10650. p->state_flags = out;
  10651. }
  10652. expr = unparen_expr(expr);
  10653. TokenPos expr_pos = ast_token(expr).pos;
  10654. TypeAndValue tv = type_and_value_of_expr(expr);
  10655. 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));
  10656. if (tv.value.kind != ExactValue_Invalid) {
  10657. // NOTE(bill): The commented out code below is just for debug purposes only
  10658. // 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));
  10659. // if (is_type_untyped(tv.type)) {
  10660. // gb_printf_err("%s %s\n", token_pos_to_string(expr_pos), expr_to_string(expr));
  10661. // }
  10662. // NOTE(bill): Short on constant values
  10663. return lb_const_value(p->module, tv.type, tv.value);
  10664. }
  10665. #if 0
  10666. LLVMMetadataRef prev_debug_location = nullptr;
  10667. if (p->debug_info != nullptr) {
  10668. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  10669. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  10670. }
  10671. defer (if (prev_debug_location != nullptr) {
  10672. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  10673. });
  10674. #endif
  10675. switch (expr->kind) {
  10676. case_ast_node(bl, BasicLit, expr);
  10677. TokenPos pos = bl->token.pos;
  10678. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  10679. case_end;
  10680. case_ast_node(bd, BasicDirective, expr);
  10681. TokenPos pos = bd->token.pos;
  10682. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name.string));
  10683. case_end;
  10684. case_ast_node(i, Implicit, expr);
  10685. return lb_addr_load(p, lb_build_addr(p, expr));
  10686. case_end;
  10687. case_ast_node(u, Undef, expr)
  10688. lbValue res = {};
  10689. if (is_type_untyped(tv.type)) {
  10690. res.value = nullptr;
  10691. res.type = t_untyped_undef;
  10692. } else {
  10693. res.value = LLVMGetUndef(lb_type(m, tv.type));
  10694. res.type = tv.type;
  10695. }
  10696. return res;
  10697. case_end;
  10698. case_ast_node(i, Ident, expr);
  10699. Entity *e = entity_from_expr(expr);
  10700. e = strip_entity_wrapping(e);
  10701. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  10702. if (e->kind == Entity_Builtin) {
  10703. Token token = ast_token(expr);
  10704. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  10705. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  10706. token_pos_to_string(token.pos));
  10707. return {};
  10708. } else if (e->kind == Entity_Nil) {
  10709. lbValue res = {};
  10710. res.value = nullptr;
  10711. res.type = e->type;
  10712. return res;
  10713. }
  10714. GB_ASSERT(e->kind != Entity_ProcGroup);
  10715. return lb_find_ident(p, m, e, expr);
  10716. case_end;
  10717. case_ast_node(de, DerefExpr, expr);
  10718. return lb_addr_load(p, lb_build_addr(p, expr));
  10719. case_end;
  10720. case_ast_node(se, SelectorExpr, expr);
  10721. TypeAndValue tav = type_and_value_of_expr(expr);
  10722. GB_ASSERT(tav.mode != Addressing_Invalid);
  10723. return lb_addr_load(p, lb_build_addr(p, expr));
  10724. case_end;
  10725. case_ast_node(ise, ImplicitSelectorExpr, expr);
  10726. TypeAndValue tav = type_and_value_of_expr(expr);
  10727. GB_ASSERT(tav.mode == Addressing_Constant);
  10728. return lb_const_value(p->module, tv.type, tv.value);
  10729. case_end;
  10730. case_ast_node(se, SelectorCallExpr, expr);
  10731. GB_ASSERT(se->modified_call);
  10732. TypeAndValue tav = type_and_value_of_expr(expr);
  10733. GB_ASSERT(tav.mode != Addressing_Invalid);
  10734. lbValue res = lb_build_call_expr(p, se->call);
  10735. ast_node(ce, CallExpr, se->call);
  10736. ce->sce_temp_data = gb_alloc_copy(permanent_allocator(), &res, gb_size_of(res));
  10737. return res;
  10738. case_end;
  10739. case_ast_node(te, TernaryIfExpr, expr);
  10740. LLVMValueRef incoming_values[2] = {};
  10741. LLVMBasicBlockRef incoming_blocks[2] = {};
  10742. GB_ASSERT(te->y != nullptr);
  10743. lbBlock *then = lb_create_block(p, "if.then");
  10744. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  10745. lbBlock *else_ = lb_create_block(p, "if.else");
  10746. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  10747. lb_start_block(p, then);
  10748. Type *type = default_type(type_of_expr(expr));
  10749. lb_open_scope(p, nullptr);
  10750. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  10751. lb_close_scope(p, lbDeferExit_Default, nullptr);
  10752. lb_emit_jump(p, done);
  10753. lb_start_block(p, else_);
  10754. lb_open_scope(p, nullptr);
  10755. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  10756. lb_close_scope(p, lbDeferExit_Default, nullptr);
  10757. lb_emit_jump(p, done);
  10758. lb_start_block(p, done);
  10759. lbValue res = {};
  10760. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  10761. res.type = type;
  10762. GB_ASSERT(p->curr_block->preds.count >= 2);
  10763. incoming_blocks[0] = p->curr_block->preds[0]->block;
  10764. incoming_blocks[1] = p->curr_block->preds[1]->block;
  10765. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  10766. return res;
  10767. case_end;
  10768. case_ast_node(te, TernaryWhenExpr, expr);
  10769. TypeAndValue tav = type_and_value_of_expr(te->cond);
  10770. GB_ASSERT(tav.mode == Addressing_Constant);
  10771. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  10772. if (tav.value.value_bool) {
  10773. return lb_build_expr(p, te->x);
  10774. } else {
  10775. return lb_build_expr(p, te->y);
  10776. }
  10777. case_end;
  10778. case_ast_node(ta, TypeAssertion, expr);
  10779. TokenPos pos = ast_token(expr).pos;
  10780. Type *type = tv.type;
  10781. lbValue e = lb_build_expr(p, ta->expr);
  10782. Type *t = type_deref(e.type);
  10783. if (is_type_union(t)) {
  10784. if (ta->ignores[0]) {
  10785. // NOTE(bill): This is not needed for optimization levels other than 0
  10786. return lb_emit_union_cast_only_ok_check(p, e, type, pos);
  10787. }
  10788. return lb_emit_union_cast(p, e, type, pos);
  10789. } else if (is_type_any(t)) {
  10790. return lb_emit_any_cast(p, e, type, pos);
  10791. } else {
  10792. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  10793. }
  10794. case_end;
  10795. case_ast_node(tc, TypeCast, expr);
  10796. lbValue e = lb_build_expr(p, tc->expr);
  10797. switch (tc->token.kind) {
  10798. case Token_cast:
  10799. return lb_emit_conv(p, e, tv.type);
  10800. case Token_transmute:
  10801. return lb_emit_transmute(p, e, tv.type);
  10802. }
  10803. GB_PANIC("Invalid AST TypeCast");
  10804. case_end;
  10805. case_ast_node(ac, AutoCast, expr);
  10806. lbValue value = lb_build_expr(p, ac->expr);
  10807. return lb_emit_conv(p, value, tv.type);
  10808. case_end;
  10809. case_ast_node(ue, UnaryExpr, expr);
  10810. switch (ue->op.kind) {
  10811. case Token_And:
  10812. return lb_build_unary_and(p, expr);
  10813. default:
  10814. {
  10815. lbValue v = lb_build_expr(p, ue->expr);
  10816. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  10817. }
  10818. }
  10819. case_end;
  10820. case_ast_node(be, BinaryExpr, expr);
  10821. return lb_build_binary_expr(p, expr);
  10822. case_end;
  10823. case_ast_node(pl, ProcLit, expr);
  10824. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  10825. case_end;
  10826. case_ast_node(cl, CompoundLit, expr);
  10827. return lb_addr_load(p, lb_build_addr(p, expr));
  10828. case_end;
  10829. case_ast_node(ce, CallExpr, expr);
  10830. return lb_build_call_expr(p, expr);
  10831. case_end;
  10832. case_ast_node(se, SliceExpr, expr);
  10833. if (is_type_slice(type_of_expr(se->expr))) {
  10834. // NOTE(bill): Quick optimization
  10835. if (se->high == nullptr &&
  10836. (se->low == nullptr || lb_is_expr_constant_zero(se->low))) {
  10837. return lb_build_expr(p, se->expr);
  10838. }
  10839. }
  10840. return lb_addr_load(p, lb_build_addr(p, expr));
  10841. case_end;
  10842. case_ast_node(ie, IndexExpr, expr);
  10843. return lb_addr_load(p, lb_build_addr(p, expr));
  10844. case_end;
  10845. case_ast_node(ia, InlineAsmExpr, expr);
  10846. Type *t = type_of_expr(expr);
  10847. GB_ASSERT(is_type_asm_proc(t));
  10848. String asm_string = {};
  10849. String constraints_string = {};
  10850. TypeAndValue tav;
  10851. tav = type_and_value_of_expr(ia->asm_string);
  10852. GB_ASSERT(is_type_string(tav.type));
  10853. GB_ASSERT(tav.value.kind == ExactValue_String);
  10854. asm_string = tav.value.value_string;
  10855. tav = type_and_value_of_expr(ia->constraints_string);
  10856. GB_ASSERT(is_type_string(tav.type));
  10857. GB_ASSERT(tav.value.kind == ExactValue_String);
  10858. constraints_string = tav.value.value_string;
  10859. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  10860. switch (ia->dialect) {
  10861. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  10862. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  10863. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  10864. default: GB_PANIC("Unhandled inline asm dialect"); break;
  10865. }
  10866. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  10867. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  10868. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  10869. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  10870. ia->has_side_effects, ia->is_align_stack, dialect
  10871. );
  10872. GB_ASSERT(the_asm != nullptr);
  10873. return {the_asm, t};
  10874. case_end;
  10875. }
  10876. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  10877. return {};
  10878. }
  10879. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  10880. lbAddr *found = map_get(&p->module->soa_values, hash_entity(e));
  10881. GB_ASSERT(found != nullptr);
  10882. return *found;
  10883. }
  10884. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  10885. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  10886. String name = e->token.string;
  10887. Entity *parent = e->using_parent;
  10888. Selection sel = lookup_field(parent->type, name, false);
  10889. GB_ASSERT(sel.entity != nullptr);
  10890. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  10891. lbValue v = {};
  10892. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  10893. // NOTE(bill): using SOA value (probably from for-in statement)
  10894. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  10895. v = lb_addr_get_ptr(p, parent_addr);
  10896. } else if (pv != nullptr) {
  10897. v = *pv;
  10898. } else {
  10899. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  10900. v = lb_build_addr_ptr(p, e->using_expr);
  10901. }
  10902. GB_ASSERT(v.value != nullptr);
  10903. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  10904. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  10905. if (parent->scope) {
  10906. if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  10907. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  10908. }
  10909. } else {
  10910. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  10911. }
  10912. return ptr;
  10913. }
  10914. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  10915. GB_ASSERT(e != nullptr);
  10916. if (e->kind == Entity_Constant) {
  10917. Type *t = default_type(type_of_expr(expr));
  10918. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  10919. lbAddr g = lb_add_global_generated(p->module, t, v);
  10920. return g;
  10921. }
  10922. lbValue v = {};
  10923. lbValue *found = map_get(&p->module->values, hash_entity(e));
  10924. if (found) {
  10925. v = *found;
  10926. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  10927. // NOTE(bill): Calculate the using variable every time
  10928. v = lb_get_using_variable(p, e);
  10929. } else if (e->flags & EntityFlag_SoaPtrField) {
  10930. return lb_get_soa_variable_addr(p, e);
  10931. }
  10932. if (v.value == nullptr) {
  10933. return lb_addr(lb_find_value_from_entity(p->module, e));
  10934. // error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  10935. // LIT(p->name),
  10936. // LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  10937. // GB_PANIC("Unknown value");
  10938. }
  10939. return lb_addr(v);
  10940. }
  10941. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  10942. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  10943. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  10944. map_type = base_type(map_type);
  10945. GB_ASSERT(map_type->kind == Type_Map);
  10946. Type *key_type = map_type->Map.key;
  10947. Type *val_type = map_type->Map.value;
  10948. // NOTE(bill): Removes unnecessary allocation if split gep
  10949. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  10950. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  10951. lb_emit_store(p, gep0, m);
  10952. i64 entry_size = type_size_of (map_type->Map.entry_type);
  10953. i64 entry_align = type_align_of (map_type->Map.entry_type);
  10954. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  10955. i64 key_size = type_size_of (map_type->Map.key);
  10956. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  10957. i64 value_size = type_size_of (map_type->Map.value);
  10958. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  10959. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  10960. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  10961. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  10962. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  10963. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  10964. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  10965. return lb_addr_load(p, h);
  10966. }
  10967. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  10968. if (true) {
  10969. return {};
  10970. }
  10971. lbValue hashed_key = {};
  10972. if (lb_is_const(key)) {
  10973. u64 hash = 0xcbf29ce484222325;
  10974. if (is_type_cstring(key_type)) {
  10975. size_t length = 0;
  10976. char const *text = LLVMGetAsString(key.value, &length);
  10977. hash = fnv64a(text, cast(isize)length);
  10978. } else if (is_type_string(key_type)) {
  10979. unsigned data_indices[] = {0};
  10980. unsigned len_indices[] = {1};
  10981. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  10982. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  10983. isize length = LLVMConstIntGetSExtValue(len);
  10984. char const *text = nullptr;
  10985. if (false && length != 0) {
  10986. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  10987. return {};
  10988. }
  10989. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  10990. size_t ulength = 0;
  10991. text = LLVMGetAsString(data, &ulength);
  10992. gb_printf_err("%td %td %s\n", length, ulength, text);
  10993. length = gb_min(length, cast(isize)ulength);
  10994. }
  10995. hash = fnv64a(text, cast(isize)length);
  10996. } else {
  10997. return {};
  10998. }
  10999. // TODO(bill): other const hash types
  11000. if (build_context.word_size == 4) {
  11001. hash &= 0xffffffffull;
  11002. }
  11003. hashed_key = lb_const_int(m, t_uintptr, hash);
  11004. }
  11005. return hashed_key;
  11006. }
  11007. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  11008. Type *hash_type = t_u64;
  11009. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  11010. lbValue vp = lb_addr_get_ptr(p, v);
  11011. Type *t = base_type(key.type);
  11012. key = lb_emit_conv(p, key, key_type);
  11013. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  11014. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  11015. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  11016. if (hashed_key.value == nullptr) {
  11017. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  11018. auto args = array_make<lbValue>(permanent_allocator(), 2);
  11019. args[0] = key_ptr;
  11020. args[1] = lb_const_int(p->module, t_uintptr, 0);
  11021. hashed_key = lb_emit_call(p, hasher, args);
  11022. }
  11023. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  11024. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  11025. return lb_addr_load(p, v);
  11026. }
  11027. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  11028. lbValue map_key, lbValue map_value, Ast *node) {
  11029. map_type = base_type(map_type);
  11030. GB_ASSERT(map_type->kind == Type_Map);
  11031. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  11032. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  11033. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  11034. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  11035. lb_addr_store(p, value_addr, v);
  11036. auto args = array_make<lbValue>(permanent_allocator(), 4);
  11037. args[0] = h;
  11038. args[1] = key;
  11039. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  11040. args[3] = lb_emit_source_code_location(p, node);
  11041. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  11042. }
  11043. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  11044. expr = unparen_expr(expr);
  11045. switch (expr->kind) {
  11046. case_ast_node(i, Implicit, expr);
  11047. lbAddr v = {};
  11048. switch (i->kind) {
  11049. case Token_context:
  11050. v = lb_find_or_generate_context_ptr(p);
  11051. break;
  11052. }
  11053. GB_ASSERT(v.addr.value != nullptr);
  11054. return v;
  11055. case_end;
  11056. case_ast_node(i, Ident, expr);
  11057. if (is_blank_ident(expr)) {
  11058. lbAddr val = {};
  11059. return val;
  11060. }
  11061. String name = i->token.string;
  11062. Entity *e = entity_of_node(expr);
  11063. return lb_build_addr_from_entity(p, e, expr);
  11064. case_end;
  11065. case_ast_node(se, SelectorExpr, expr);
  11066. Ast *sel = unparen_expr(se->selector);
  11067. if (sel->kind == Ast_Ident) {
  11068. String selector = sel->Ident.token.string;
  11069. TypeAndValue tav = type_and_value_of_expr(se->expr);
  11070. if (tav.mode == Addressing_Invalid) {
  11071. // NOTE(bill): Imports
  11072. Entity *imp = entity_of_node(se->expr);
  11073. if (imp != nullptr) {
  11074. GB_ASSERT(imp->kind == Entity_ImportName);
  11075. }
  11076. return lb_build_addr(p, unparen_expr(se->selector));
  11077. }
  11078. Type *type = base_type(tav.type);
  11079. if (tav.mode == Addressing_Type) { // Addressing_Type
  11080. GB_PANIC("Unreachable");
  11081. }
  11082. if (se->swizzle_count > 0) {
  11083. Type *array_type = base_type(type_deref(tav.type));
  11084. GB_ASSERT(array_type->kind == Type_Array);
  11085. u8 swizzle_count = se->swizzle_count;
  11086. u8 swizzle_indices_raw = se->swizzle_indices;
  11087. u8 swizzle_indices[4] = {};
  11088. for (u8 i = 0; i < swizzle_count; i++) {
  11089. u8 index = swizzle_indices_raw>>(i*2) & 3;
  11090. swizzle_indices[i] = index;
  11091. }
  11092. lbValue a = {};
  11093. if (is_type_pointer(tav.type)) {
  11094. a = lb_build_expr(p, se->expr);
  11095. } else {
  11096. lbAddr addr = lb_build_addr(p, se->expr);
  11097. a = lb_addr_get_ptr(p, addr);
  11098. }
  11099. GB_ASSERT(is_type_array(expr->tav.type));
  11100. return lb_addr_swizzle(a, expr->tav.type, swizzle_count, swizzle_indices);
  11101. }
  11102. Selection sel = lookup_field(type, selector, false);
  11103. GB_ASSERT(sel.entity != nullptr);
  11104. {
  11105. lbAddr addr = lb_build_addr(p, se->expr);
  11106. if (addr.kind == lbAddr_Map) {
  11107. lbValue v = lb_addr_load(p, addr);
  11108. lbValue a = lb_address_from_load_or_generate_local(p, v);
  11109. a = lb_emit_deep_field_gep(p, a, sel);
  11110. return lb_addr(a);
  11111. } else if (addr.kind == lbAddr_Context) {
  11112. GB_ASSERT(sel.index.count > 0);
  11113. if (addr.ctx.sel.index.count >= 0) {
  11114. sel = selection_combine(addr.ctx.sel, sel);
  11115. }
  11116. addr.ctx.sel = sel;
  11117. addr.kind = lbAddr_Context;
  11118. return addr;
  11119. } else if (addr.kind == lbAddr_SoaVariable) {
  11120. lbValue index = addr.soa.index;
  11121. i32 first_index = sel.index[0];
  11122. Selection sub_sel = sel;
  11123. sub_sel.index.data += 1;
  11124. sub_sel.index.count -= 1;
  11125. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  11126. Type *t = base_type(type_deref(addr.addr.type));
  11127. GB_ASSERT(is_type_soa_struct(t));
  11128. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  11129. lbValue len = lb_soa_struct_len(p, addr.addr);
  11130. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  11131. }
  11132. lbValue item = {};
  11133. if (t->Struct.soa_kind == StructSoa_Fixed) {
  11134. item = lb_emit_array_ep(p, arr, index);
  11135. } else {
  11136. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  11137. }
  11138. if (sub_sel.index.count > 0) {
  11139. item = lb_emit_deep_field_gep(p, item, sub_sel);
  11140. }
  11141. return lb_addr(item);
  11142. } else if (addr.kind == lbAddr_Swizzle) {
  11143. GB_ASSERT(sel.index.count > 0);
  11144. // NOTE(bill): just patch the index in place
  11145. sel.index[0] = addr.swizzle.indices[sel.index[0]];
  11146. }
  11147. lbValue a = lb_addr_get_ptr(p, addr);
  11148. a = lb_emit_deep_field_gep(p, a, sel);
  11149. return lb_addr(a);
  11150. }
  11151. } else {
  11152. GB_PANIC("Unsupported selector expression");
  11153. }
  11154. case_end;
  11155. case_ast_node(se, SelectorCallExpr, expr);
  11156. GB_ASSERT(se->modified_call);
  11157. TypeAndValue tav = type_and_value_of_expr(expr);
  11158. GB_ASSERT(tav.mode != Addressing_Invalid);
  11159. lbValue e = lb_build_expr(p, expr);
  11160. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  11161. case_end;
  11162. case_ast_node(ta, TypeAssertion, expr);
  11163. TokenPos pos = ast_token(expr).pos;
  11164. lbValue e = lb_build_expr(p, ta->expr);
  11165. Type *t = type_deref(e.type);
  11166. if (is_type_union(t)) {
  11167. Type *type = type_of_expr(expr);
  11168. lbAddr v = lb_add_local_generated(p, type, false);
  11169. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  11170. return v;
  11171. } else if (is_type_any(t)) {
  11172. Type *type = type_of_expr(expr);
  11173. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  11174. } else {
  11175. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  11176. }
  11177. case_end;
  11178. case_ast_node(ue, UnaryExpr, expr);
  11179. switch (ue->op.kind) {
  11180. case Token_And:
  11181. return lb_build_addr(p, ue->expr);
  11182. default:
  11183. GB_PANIC("Invalid unary expression for lb_build_addr");
  11184. }
  11185. case_end;
  11186. case_ast_node(be, BinaryExpr, expr);
  11187. lbValue v = lb_build_expr(p, expr);
  11188. Type *t = v.type;
  11189. if (is_type_pointer(t)) {
  11190. return lb_addr(v);
  11191. }
  11192. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  11193. case_end;
  11194. case_ast_node(ie, IndexExpr, expr);
  11195. Type *t = base_type(type_of_expr(ie->expr));
  11196. bool deref = is_type_pointer(t);
  11197. t = base_type(type_deref(t));
  11198. if (is_type_soa_struct(t)) {
  11199. // SOA STRUCTURES!!!!
  11200. lbValue val = lb_build_addr_ptr(p, ie->expr);
  11201. if (deref) {
  11202. val = lb_emit_load(p, val);
  11203. }
  11204. lbValue index = lb_build_expr(p, ie->index);
  11205. return lb_addr_soa_variable(val, index, ie->index);
  11206. }
  11207. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  11208. // SOA Structures for slices/dynamic arrays
  11209. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  11210. lbValue field = lb_build_expr(p, ie->expr);
  11211. lbValue index = lb_build_expr(p, ie->index);
  11212. if (!build_context.no_bounds_check) {
  11213. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  11214. // GB_ASSERT(LLVMIsALoadInst(field.value));
  11215. // lbValue a = {};
  11216. // a.value = LLVMGetOperand(field.value, 0);
  11217. // a.type = alloc_type_pointer(field.type);
  11218. // irInstr *b = &a->Instr;
  11219. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  11220. // lbValue base_struct = b->StructElementPtr.address;
  11221. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  11222. // lbValue len = ir_soa_struct_len(p, base_struct);
  11223. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11224. }
  11225. lbValue val = lb_emit_ptr_offset(p, field, index);
  11226. return lb_addr(val);
  11227. }
  11228. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  11229. if (is_type_map(t)) {
  11230. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  11231. if (deref) {
  11232. map_val = lb_emit_load(p, map_val);
  11233. }
  11234. lbValue key = lb_build_expr(p, ie->index);
  11235. key = lb_emit_conv(p, key, t->Map.key);
  11236. Type *result_type = type_of_expr(expr);
  11237. return lb_addr_map(map_val, key, t, result_type);
  11238. }
  11239. switch (t->kind) {
  11240. case Type_Array: {
  11241. lbValue array = {};
  11242. array = lb_build_addr_ptr(p, ie->expr);
  11243. if (deref) {
  11244. array = lb_emit_load(p, array);
  11245. }
  11246. lbValue index = lb_build_expr(p, ie->index);
  11247. index = lb_emit_conv(p, index, t_int);
  11248. lbValue elem = lb_emit_array_ep(p, array, index);
  11249. auto index_tv = type_and_value_of_expr(ie->index);
  11250. if (index_tv.mode != Addressing_Constant) {
  11251. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  11252. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11253. }
  11254. return lb_addr(elem);
  11255. }
  11256. case Type_EnumeratedArray: {
  11257. lbValue array = {};
  11258. array = lb_build_addr_ptr(p, ie->expr);
  11259. if (deref) {
  11260. array = lb_emit_load(p, array);
  11261. }
  11262. Type *index_type = t->EnumeratedArray.index;
  11263. auto index_tv = type_and_value_of_expr(ie->index);
  11264. lbValue index = {};
  11265. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  11266. if (index_tv.mode == Addressing_Constant) {
  11267. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  11268. index = lb_const_value(p->module, index_type, idx);
  11269. } else {
  11270. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11271. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  11272. }
  11273. } else {
  11274. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11275. }
  11276. lbValue elem = lb_emit_array_ep(p, array, index);
  11277. if (index_tv.mode != Addressing_Constant) {
  11278. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  11279. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11280. }
  11281. return lb_addr(elem);
  11282. }
  11283. case Type_Slice: {
  11284. lbValue slice = {};
  11285. slice = lb_build_expr(p, ie->expr);
  11286. if (deref) {
  11287. slice = lb_emit_load(p, slice);
  11288. }
  11289. lbValue elem = lb_slice_elem(p, slice);
  11290. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11291. lbValue len = lb_slice_len(p, slice);
  11292. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11293. lbValue v = lb_emit_ptr_offset(p, elem, index);
  11294. return lb_addr(v);
  11295. }
  11296. case Type_RelativeSlice: {
  11297. lbAddr slice_addr = {};
  11298. if (deref) {
  11299. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  11300. } else {
  11301. slice_addr = lb_build_addr(p, ie->expr);
  11302. }
  11303. lbValue slice = lb_addr_load(p, slice_addr);
  11304. lbValue elem = lb_slice_elem(p, slice);
  11305. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11306. lbValue len = lb_slice_len(p, slice);
  11307. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11308. lbValue v = lb_emit_ptr_offset(p, elem, index);
  11309. return lb_addr(v);
  11310. }
  11311. case Type_DynamicArray: {
  11312. lbValue dynamic_array = {};
  11313. dynamic_array = lb_build_expr(p, ie->expr);
  11314. if (deref) {
  11315. dynamic_array = lb_emit_load(p, dynamic_array);
  11316. }
  11317. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  11318. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  11319. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11320. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11321. lbValue v = lb_emit_ptr_offset(p, elem, index);
  11322. return lb_addr(v);
  11323. }
  11324. case Type_Basic: { // Basic_string
  11325. lbValue str;
  11326. lbValue elem;
  11327. lbValue len;
  11328. lbValue index;
  11329. str = lb_build_expr(p, ie->expr);
  11330. if (deref) {
  11331. str = lb_emit_load(p, str);
  11332. }
  11333. elem = lb_string_elem(p, str);
  11334. len = lb_string_len(p, str);
  11335. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  11336. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  11337. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  11338. }
  11339. }
  11340. case_end;
  11341. case_ast_node(se, SliceExpr, expr);
  11342. lbValue low = lb_const_int(p->module, t_int, 0);
  11343. lbValue high = {};
  11344. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  11345. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  11346. bool no_indices = se->low == nullptr && se->high == nullptr;
  11347. lbAddr addr = lb_build_addr(p, se->expr);
  11348. lbValue base = lb_addr_load(p, addr);
  11349. Type *type = base_type(base.type);
  11350. if (is_type_pointer(type)) {
  11351. type = base_type(type_deref(type));
  11352. addr = lb_addr(base);
  11353. base = lb_addr_load(p, addr);
  11354. }
  11355. switch (type->kind) {
  11356. case Type_Slice: {
  11357. Type *slice_type = type;
  11358. lbValue len = lb_slice_len(p, base);
  11359. if (high.value == nullptr) high = len;
  11360. if (!no_indices) {
  11361. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11362. }
  11363. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  11364. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11365. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  11366. lb_fill_slice(p, slice, elem, new_len);
  11367. return slice;
  11368. }
  11369. case Type_RelativeSlice:
  11370. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  11371. break;
  11372. case Type_DynamicArray: {
  11373. Type *elem_type = type->DynamicArray.elem;
  11374. Type *slice_type = alloc_type_slice(elem_type);
  11375. lbValue len = lb_dynamic_array_len(p, base);
  11376. if (high.value == nullptr) high = len;
  11377. if (!no_indices) {
  11378. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11379. }
  11380. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  11381. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11382. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  11383. lb_fill_slice(p, slice, elem, new_len);
  11384. return slice;
  11385. }
  11386. case Type_Array: {
  11387. Type *slice_type = alloc_type_slice(type->Array.elem);
  11388. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  11389. if (high.value == nullptr) high = len;
  11390. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  11391. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  11392. if (!low_const || !high_const) {
  11393. if (!no_indices) {
  11394. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11395. }
  11396. }
  11397. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  11398. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11399. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  11400. lb_fill_slice(p, slice, elem, new_len);
  11401. return slice;
  11402. }
  11403. case Type_Basic: {
  11404. GB_ASSERT(type == t_string);
  11405. lbValue len = lb_string_len(p, base);
  11406. if (high.value == nullptr) high = len;
  11407. if (!no_indices) {
  11408. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11409. }
  11410. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  11411. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11412. lbAddr str = lb_add_local_generated(p, t_string, false);
  11413. lb_fill_string(p, str, elem, new_len);
  11414. return str;
  11415. }
  11416. case Type_Struct:
  11417. if (is_type_soa_struct(type)) {
  11418. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  11419. if (high.value == nullptr) high = len;
  11420. if (!no_indices) {
  11421. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  11422. }
  11423. #if 1
  11424. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  11425. if (type->Struct.soa_kind == StructSoa_Fixed) {
  11426. i32 field_count = cast(i32)type->Struct.fields.count;
  11427. for (i32 i = 0; i < field_count; i++) {
  11428. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  11429. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  11430. field_src = lb_emit_array_ep(p, field_src, low);
  11431. lb_emit_store(p, field_dst, field_src);
  11432. }
  11433. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  11434. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11435. lb_emit_store(p, len_dst, new_len);
  11436. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  11437. if (no_indices) {
  11438. lb_addr_store(p, dst, base);
  11439. } else {
  11440. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  11441. for (i32 i = 0; i < field_count; i++) {
  11442. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  11443. lbValue field_src = lb_emit_struct_ev(p, base, i);
  11444. field_src = lb_emit_ptr_offset(p, field_src, low);
  11445. lb_emit_store(p, field_dst, field_src);
  11446. }
  11447. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  11448. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11449. lb_emit_store(p, len_dst, new_len);
  11450. }
  11451. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  11452. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  11453. for (i32 i = 0; i < field_count; i++) {
  11454. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  11455. lbValue field_src = lb_emit_struct_ev(p, base, i);
  11456. field_src = lb_emit_ptr_offset(p, field_src, low);
  11457. lb_emit_store(p, field_dst, field_src);
  11458. }
  11459. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  11460. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  11461. lb_emit_store(p, len_dst, new_len);
  11462. }
  11463. return dst;
  11464. #endif
  11465. }
  11466. break;
  11467. }
  11468. GB_PANIC("Unknown slicable type");
  11469. case_end;
  11470. case_ast_node(de, DerefExpr, expr);
  11471. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  11472. lbAddr addr = lb_build_addr(p, de->expr);
  11473. addr.relative.deref = true;
  11474. return addr;\
  11475. }
  11476. lbValue addr = lb_build_expr(p, de->expr);
  11477. return lb_addr(addr);
  11478. case_end;
  11479. case_ast_node(ce, CallExpr, expr);
  11480. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  11481. lbValue e = lb_build_expr(p, expr);
  11482. #if 1
  11483. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  11484. #else
  11485. lbAddr v = lb_add_local_generated(p, e.type, false);
  11486. lb_addr_store(p, v, e);
  11487. return v;
  11488. #endif
  11489. case_end;
  11490. case_ast_node(cl, CompoundLit, expr);
  11491. Type *type = type_of_expr(expr);
  11492. Type *bt = base_type(type);
  11493. lbAddr v = lb_add_local_generated(p, type, true);
  11494. Type *et = nullptr;
  11495. switch (bt->kind) {
  11496. case Type_Array: et = bt->Array.elem; break;
  11497. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  11498. case Type_Slice: et = bt->Slice.elem; break;
  11499. case Type_BitSet: et = bt->BitSet.elem; break;
  11500. case Type_SimdVector: et = bt->SimdVector.elem; break;
  11501. }
  11502. String proc_name = {};
  11503. if (p->entity) {
  11504. proc_name = p->entity->token.string;
  11505. }
  11506. TokenPos pos = ast_token(expr).pos;
  11507. switch (bt->kind) {
  11508. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  11509. case Type_Struct: {
  11510. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  11511. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  11512. bool is_raw_union = is_type_raw_union(bt);
  11513. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  11514. TypeStruct *st = &bt->Struct;
  11515. if (cl->elems.count > 0) {
  11516. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11517. lbValue comp_lit_ptr = lb_addr_get_ptr(p, v);
  11518. for_array(field_index, cl->elems) {
  11519. Ast *elem = cl->elems[field_index];
  11520. lbValue field_expr = {};
  11521. Entity *field = nullptr;
  11522. isize index = field_index;
  11523. if (elem->kind == Ast_FieldValue) {
  11524. ast_node(fv, FieldValue, elem);
  11525. String name = fv->field->Ident.token.string;
  11526. Selection sel = lookup_field(bt, name, false);
  11527. index = sel.index[0];
  11528. elem = fv->value;
  11529. TypeAndValue tav = type_and_value_of_expr(elem);
  11530. } else {
  11531. TypeAndValue tav = type_and_value_of_expr(elem);
  11532. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  11533. index = sel.index[0];
  11534. }
  11535. field = st->fields[index];
  11536. Type *ft = field->type;
  11537. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  11538. continue;
  11539. }
  11540. field_expr = lb_build_expr(p, elem);
  11541. lbValue gep = {};
  11542. if (is_raw_union) {
  11543. gep = lb_emit_conv(p, comp_lit_ptr, alloc_type_pointer(ft));
  11544. } else {
  11545. gep = lb_emit_struct_ep(p, comp_lit_ptr, cast(i32)index);
  11546. }
  11547. Type *fet = field_expr.type;
  11548. GB_ASSERT(fet->kind != Type_Tuple);
  11549. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  11550. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  11551. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  11552. lb_emit_store_union_variant(p, gep, field_expr, fet);
  11553. } else {
  11554. lbValue fv = lb_emit_conv(p, field_expr, ft);
  11555. lb_emit_store(p, gep, fv);
  11556. }
  11557. }
  11558. }
  11559. break;
  11560. }
  11561. case Type_Map: {
  11562. if (cl->elems.count == 0) {
  11563. break;
  11564. }
  11565. {
  11566. auto args = array_make<lbValue>(permanent_allocator(), 3);
  11567. args[0] = lb_gen_map_header(p, v.addr, type);
  11568. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  11569. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  11570. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  11571. }
  11572. for_array(field_index, cl->elems) {
  11573. Ast *elem = cl->elems[field_index];
  11574. ast_node(fv, FieldValue, elem);
  11575. lbValue key = lb_build_expr(p, fv->field);
  11576. lbValue value = lb_build_expr(p, fv->value);
  11577. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  11578. }
  11579. break;
  11580. }
  11581. case Type_Array: {
  11582. if (cl->elems.count > 0) {
  11583. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11584. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  11585. // NOTE(bill): Separate value, gep, store into their own chunks
  11586. for_array(i, cl->elems) {
  11587. Ast *elem = cl->elems[i];
  11588. if (elem->kind == Ast_FieldValue) {
  11589. ast_node(fv, FieldValue, elem);
  11590. if (lb_is_elem_const(fv->value, et)) {
  11591. continue;
  11592. }
  11593. if (is_ast_range(fv->field)) {
  11594. ast_node(ie, BinaryExpr, fv->field);
  11595. TypeAndValue lo_tav = ie->left->tav;
  11596. TypeAndValue hi_tav = ie->right->tav;
  11597. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11598. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11599. TokenKind op = ie->op.kind;
  11600. i64 lo = exact_value_to_i64(lo_tav.value);
  11601. i64 hi = exact_value_to_i64(hi_tav.value);
  11602. if (op != Token_RangeHalf) {
  11603. hi += 1;
  11604. }
  11605. lbValue value = lb_build_expr(p, fv->value);
  11606. for (i64 k = lo; k < hi; k++) {
  11607. lbCompoundLitElemTempData data = {};
  11608. data.value = value;
  11609. data.elem_index = cast(i32)k;
  11610. array_add(&temp_data, data);
  11611. }
  11612. } else {
  11613. auto tav = fv->field->tav;
  11614. GB_ASSERT(tav.mode == Addressing_Constant);
  11615. i64 index = exact_value_to_i64(tav.value);
  11616. lbValue value = lb_build_expr(p, fv->value);
  11617. lbCompoundLitElemTempData data = {};
  11618. data.value = lb_emit_conv(p, value, et);
  11619. data.expr = fv->value;
  11620. data.elem_index = cast(i32)index;
  11621. array_add(&temp_data, data);
  11622. }
  11623. } else {
  11624. if (lb_is_elem_const(elem, et)) {
  11625. continue;
  11626. }
  11627. lbCompoundLitElemTempData data = {};
  11628. data.expr = elem;
  11629. data.elem_index = cast(i32)i;
  11630. array_add(&temp_data, data);
  11631. }
  11632. }
  11633. for_array(i, temp_data) {
  11634. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  11635. }
  11636. for_array(i, temp_data) {
  11637. lbValue field_expr = temp_data[i].value;
  11638. Ast *expr = temp_data[i].expr;
  11639. auto prev_hint = lb_set_copy_elision_hint(p, lb_addr(temp_data[i].gep), expr);
  11640. if (field_expr.value == nullptr) {
  11641. field_expr = lb_build_expr(p, expr);
  11642. }
  11643. Type *t = field_expr.type;
  11644. GB_ASSERT(t->kind != Type_Tuple);
  11645. lbValue ev = lb_emit_conv(p, field_expr, et);
  11646. if (!p->copy_elision_hint.used) {
  11647. temp_data[i].value = ev;
  11648. }
  11649. lb_reset_copy_elision_hint(p, prev_hint);
  11650. }
  11651. for_array(i, temp_data) {
  11652. if (temp_data[i].value.value != nullptr) {
  11653. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  11654. }
  11655. }
  11656. }
  11657. break;
  11658. }
  11659. case Type_EnumeratedArray: {
  11660. if (cl->elems.count > 0) {
  11661. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11662. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  11663. // NOTE(bill): Separate value, gep, store into their own chunks
  11664. for_array(i, cl->elems) {
  11665. Ast *elem = cl->elems[i];
  11666. if (elem->kind == Ast_FieldValue) {
  11667. ast_node(fv, FieldValue, elem);
  11668. if (lb_is_elem_const(fv->value, et)) {
  11669. continue;
  11670. }
  11671. if (is_ast_range(fv->field)) {
  11672. ast_node(ie, BinaryExpr, fv->field);
  11673. TypeAndValue lo_tav = ie->left->tav;
  11674. TypeAndValue hi_tav = ie->right->tav;
  11675. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11676. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11677. TokenKind op = ie->op.kind;
  11678. i64 lo = exact_value_to_i64(lo_tav.value);
  11679. i64 hi = exact_value_to_i64(hi_tav.value);
  11680. if (op != Token_RangeHalf) {
  11681. hi += 1;
  11682. }
  11683. lbValue value = lb_build_expr(p, fv->value);
  11684. for (i64 k = lo; k < hi; k++) {
  11685. lbCompoundLitElemTempData data = {};
  11686. data.value = value;
  11687. data.elem_index = cast(i32)k;
  11688. array_add(&temp_data, data);
  11689. }
  11690. } else {
  11691. auto tav = fv->field->tav;
  11692. GB_ASSERT(tav.mode == Addressing_Constant);
  11693. i64 index = exact_value_to_i64(tav.value);
  11694. lbValue value = lb_build_expr(p, fv->value);
  11695. lbCompoundLitElemTempData data = {};
  11696. data.value = lb_emit_conv(p, value, et);
  11697. data.expr = fv->value;
  11698. data.elem_index = cast(i32)index;
  11699. array_add(&temp_data, data);
  11700. }
  11701. } else {
  11702. if (lb_is_elem_const(elem, et)) {
  11703. continue;
  11704. }
  11705. lbCompoundLitElemTempData data = {};
  11706. data.expr = elem;
  11707. data.elem_index = cast(i32)i;
  11708. array_add(&temp_data, data);
  11709. }
  11710. }
  11711. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  11712. for_array(i, temp_data) {
  11713. i32 index = temp_data[i].elem_index - index_offset;
  11714. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  11715. }
  11716. for_array(i, temp_data) {
  11717. lbValue field_expr = temp_data[i].value;
  11718. Ast *expr = temp_data[i].expr;
  11719. auto prev_hint = lb_set_copy_elision_hint(p, lb_addr(temp_data[i].gep), expr);
  11720. if (field_expr.value == nullptr) {
  11721. field_expr = lb_build_expr(p, expr);
  11722. }
  11723. Type *t = field_expr.type;
  11724. GB_ASSERT(t->kind != Type_Tuple);
  11725. lbValue ev = lb_emit_conv(p, field_expr, et);
  11726. if (!p->copy_elision_hint.used) {
  11727. temp_data[i].value = ev;
  11728. }
  11729. lb_reset_copy_elision_hint(p, prev_hint);
  11730. }
  11731. for_array(i, temp_data) {
  11732. if (temp_data[i].value.value != nullptr) {
  11733. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  11734. }
  11735. }
  11736. }
  11737. break;
  11738. }
  11739. case Type_Slice: {
  11740. if (cl->elems.count > 0) {
  11741. Type *elem_type = bt->Slice.elem;
  11742. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  11743. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  11744. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  11745. lbValue data = lb_slice_elem(p, slice);
  11746. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  11747. for_array(i, cl->elems) {
  11748. Ast *elem = cl->elems[i];
  11749. if (elem->kind == Ast_FieldValue) {
  11750. ast_node(fv, FieldValue, elem);
  11751. if (lb_is_elem_const(fv->value, et)) {
  11752. continue;
  11753. }
  11754. if (is_ast_range(fv->field)) {
  11755. ast_node(ie, BinaryExpr, fv->field);
  11756. TypeAndValue lo_tav = ie->left->tav;
  11757. TypeAndValue hi_tav = ie->right->tav;
  11758. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11759. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11760. TokenKind op = ie->op.kind;
  11761. i64 lo = exact_value_to_i64(lo_tav.value);
  11762. i64 hi = exact_value_to_i64(hi_tav.value);
  11763. if (op != Token_RangeHalf) {
  11764. hi += 1;
  11765. }
  11766. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  11767. for (i64 k = lo; k < hi; k++) {
  11768. lbCompoundLitElemTempData data = {};
  11769. data.value = value;
  11770. data.elem_index = cast(i32)k;
  11771. array_add(&temp_data, data);
  11772. }
  11773. } else {
  11774. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  11775. i64 index = exact_value_to_i64(fv->field->tav.value);
  11776. lbValue field_expr = lb_build_expr(p, fv->value);
  11777. GB_ASSERT(!is_type_tuple(field_expr.type));
  11778. lbValue ev = lb_emit_conv(p, field_expr, et);
  11779. lbCompoundLitElemTempData data = {};
  11780. data.value = ev;
  11781. data.elem_index = cast(i32)index;
  11782. array_add(&temp_data, data);
  11783. }
  11784. } else {
  11785. if (lb_is_elem_const(elem, et)) {
  11786. continue;
  11787. }
  11788. lbValue field_expr = lb_build_expr(p, elem);
  11789. GB_ASSERT(!is_type_tuple(field_expr.type));
  11790. lbValue ev = lb_emit_conv(p, field_expr, et);
  11791. lbCompoundLitElemTempData data = {};
  11792. data.value = ev;
  11793. data.elem_index = cast(i32)i;
  11794. array_add(&temp_data, data);
  11795. }
  11796. }
  11797. for_array(i, temp_data) {
  11798. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  11799. }
  11800. for_array(i, temp_data) {
  11801. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  11802. }
  11803. {
  11804. lbValue count = {};
  11805. count.type = t_int;
  11806. if (lb_is_const(slice)) {
  11807. unsigned indices[1] = {1};
  11808. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  11809. } else {
  11810. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  11811. }
  11812. lb_fill_slice(p, v, data, count);
  11813. }
  11814. }
  11815. break;
  11816. }
  11817. case Type_DynamicArray: {
  11818. if (cl->elems.count == 0) {
  11819. break;
  11820. }
  11821. Type *et = bt->DynamicArray.elem;
  11822. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  11823. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  11824. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  11825. {
  11826. auto args = array_make<lbValue>(permanent_allocator(), 5);
  11827. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  11828. args[1] = size;
  11829. args[2] = align;
  11830. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  11831. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  11832. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  11833. }
  11834. lbValue items = lb_generate_local_array(p, et, item_count);
  11835. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  11836. for_array(i, cl->elems) {
  11837. Ast *elem = cl->elems[i];
  11838. if (elem->kind == Ast_FieldValue) {
  11839. ast_node(fv, FieldValue, elem);
  11840. if (is_ast_range(fv->field)) {
  11841. ast_node(ie, BinaryExpr, fv->field);
  11842. TypeAndValue lo_tav = ie->left->tav;
  11843. TypeAndValue hi_tav = ie->right->tav;
  11844. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  11845. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  11846. TokenKind op = ie->op.kind;
  11847. i64 lo = exact_value_to_i64(lo_tav.value);
  11848. i64 hi = exact_value_to_i64(hi_tav.value);
  11849. if (op != Token_RangeHalf) {
  11850. hi += 1;
  11851. }
  11852. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  11853. for (i64 k = lo; k < hi; k++) {
  11854. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  11855. lb_emit_store(p, ep, value);
  11856. }
  11857. } else {
  11858. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  11859. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  11860. lbValue ev = lb_build_expr(p, fv->value);
  11861. lbValue value = lb_emit_conv(p, ev, et);
  11862. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  11863. lb_emit_store(p, ep, value);
  11864. }
  11865. } else {
  11866. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  11867. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  11868. lb_emit_store(p, ep, value);
  11869. }
  11870. }
  11871. {
  11872. auto args = array_make<lbValue>(permanent_allocator(), 6);
  11873. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  11874. args[1] = size;
  11875. args[2] = align;
  11876. args[3] = lb_emit_conv(p, items, t_rawptr);
  11877. args[4] = lb_const_int(p->module, t_int, item_count);
  11878. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  11879. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  11880. }
  11881. break;
  11882. }
  11883. case Type_Basic: {
  11884. GB_ASSERT(is_type_any(bt));
  11885. if (cl->elems.count > 0) {
  11886. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11887. String field_names[2] = {
  11888. str_lit("data"),
  11889. str_lit("id"),
  11890. };
  11891. Type *field_types[2] = {
  11892. t_rawptr,
  11893. t_typeid,
  11894. };
  11895. for_array(field_index, cl->elems) {
  11896. Ast *elem = cl->elems[field_index];
  11897. lbValue field_expr = {};
  11898. isize index = field_index;
  11899. if (elem->kind == Ast_FieldValue) {
  11900. ast_node(fv, FieldValue, elem);
  11901. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  11902. index = sel.index[0];
  11903. elem = fv->value;
  11904. } else {
  11905. TypeAndValue tav = type_and_value_of_expr(elem);
  11906. Selection sel = lookup_field(bt, field_names[field_index], false);
  11907. index = sel.index[0];
  11908. }
  11909. field_expr = lb_build_expr(p, elem);
  11910. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  11911. Type *ft = field_types[index];
  11912. lbValue fv = lb_emit_conv(p, field_expr, ft);
  11913. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  11914. lb_emit_store(p, gep, fv);
  11915. }
  11916. }
  11917. break;
  11918. }
  11919. case Type_BitSet: {
  11920. i64 sz = type_size_of(type);
  11921. if (cl->elems.count > 0 && sz > 0) {
  11922. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  11923. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  11924. for_array(i, cl->elems) {
  11925. Ast *elem = cl->elems[i];
  11926. GB_ASSERT(elem->kind != Ast_FieldValue);
  11927. if (lb_is_elem_const(elem, et)) {
  11928. continue;
  11929. }
  11930. lbValue expr = lb_build_expr(p, elem);
  11931. GB_ASSERT(expr.type->kind != Type_Tuple);
  11932. Type *it = bit_set_to_int(bt);
  11933. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  11934. lbValue e = lb_emit_conv(p, expr, it);
  11935. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  11936. e = lb_emit_arith(p, Token_Shl, one, e, it);
  11937. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  11938. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  11939. new_value = lb_emit_transmute(p, new_value, type);
  11940. lb_addr_store(p, v, new_value);
  11941. }
  11942. }
  11943. break;
  11944. }
  11945. }
  11946. return v;
  11947. case_end;
  11948. case_ast_node(tc, TypeCast, expr);
  11949. Type *type = type_of_expr(expr);
  11950. lbValue x = lb_build_expr(p, tc->expr);
  11951. lbValue e = {};
  11952. switch (tc->token.kind) {
  11953. case Token_cast:
  11954. e = lb_emit_conv(p, x, type);
  11955. break;
  11956. case Token_transmute:
  11957. e = lb_emit_transmute(p, x, type);
  11958. break;
  11959. default:
  11960. GB_PANIC("Invalid AST TypeCast");
  11961. }
  11962. lbAddr v = lb_add_local_generated(p, type, false);
  11963. lb_addr_store(p, v, e);
  11964. return v;
  11965. case_end;
  11966. case_ast_node(ac, AutoCast, expr);
  11967. return lb_build_addr(p, ac->expr);
  11968. case_end;
  11969. }
  11970. TokenPos token_pos = ast_token(expr).pos;
  11971. GB_PANIC("Unexpected address expression\n"
  11972. "\tAst: %.*s @ "
  11973. "%s\n",
  11974. LIT(ast_strings[expr->kind]),
  11975. token_pos_to_string(token_pos));
  11976. return {};
  11977. }
  11978. void lb_init_module(lbModule *m, Checker *c) {
  11979. m->info = &c->info;
  11980. gbString module_name = gb_string_make(heap_allocator(), "odin_package");
  11981. if (m->pkg) {
  11982. module_name = gb_string_appendc(module_name, "-");
  11983. module_name = gb_string_append_length(module_name, m->pkg->name.text, m->pkg->name.len);
  11984. } else if (USE_SEPARTE_MODULES) {
  11985. module_name = gb_string_appendc(module_name, "-builtin");
  11986. }
  11987. m->ctx = LLVMContextCreate();
  11988. m->mod = LLVMModuleCreateWithNameInContext(module_name ? module_name : "odin_package", m->ctx);
  11989. // m->debug_builder = nullptr;
  11990. if (build_context.ODIN_DEBUG) {
  11991. enum {DEBUG_METADATA_VERSION = 3};
  11992. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  11993. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  11994. switch (build_context.metrics.os) {
  11995. case TargetOs_windows:
  11996. LLVMAddModuleFlag(m->mod,
  11997. LLVMModuleFlagBehaviorWarning,
  11998. "CodeView", 8,
  11999. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  12000. break;
  12001. case TargetOs_darwin:
  12002. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  12003. LLVMAddModuleFlag(m->mod,
  12004. LLVMModuleFlagBehaviorWarning,
  12005. "Dwarf Version", 13,
  12006. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  12007. break;
  12008. }
  12009. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  12010. }
  12011. gbAllocator a = heap_allocator();
  12012. map_init(&m->types, a);
  12013. map_init(&m->llvm_types, a);
  12014. map_init(&m->values, a);
  12015. map_init(&m->soa_values, a);
  12016. string_map_init(&m->members, a);
  12017. map_init(&m->procedure_values, a);
  12018. string_map_init(&m->procedures, a);
  12019. string_map_init(&m->const_strings, a);
  12020. map_init(&m->anonymous_proc_lits, a);
  12021. map_init(&m->function_type_map, a);
  12022. map_init(&m->equal_procs, a);
  12023. map_init(&m->hasher_procs, a);
  12024. array_init(&m->procedures_to_generate, a, 0, 1024);
  12025. array_init(&m->foreign_library_paths, a, 0, 1024);
  12026. map_init(&m->debug_values, a);
  12027. array_init(&m->debug_incomplete_types, a, 0, 1024);
  12028. }
  12029. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  12030. if (global_error_collector.count != 0) {
  12031. return false;
  12032. }
  12033. isize tc = c->parser->total_token_count;
  12034. if (tc < 2) {
  12035. return false;
  12036. }
  12037. String init_fullpath = c->parser->init_fullpath;
  12038. if (build_context.out_filepath.len == 0) {
  12039. gen->output_name = remove_directory_from_path(init_fullpath);
  12040. gen->output_name = remove_extension_from_path(gen->output_name);
  12041. gen->output_name = string_trim_whitespace(gen->output_name);
  12042. if (gen->output_name.len == 0) {
  12043. gen->output_name = c->info.init_scope->pkg->name;
  12044. }
  12045. gen->output_base = gen->output_name;
  12046. } else {
  12047. gen->output_name = build_context.out_filepath;
  12048. gen->output_name = string_trim_whitespace(gen->output_name);
  12049. if (gen->output_name.len == 0) {
  12050. gen->output_name = c->info.init_scope->pkg->name;
  12051. }
  12052. isize pos = string_extension_position(gen->output_name);
  12053. if (pos < 0) {
  12054. gen->output_base = gen->output_name;
  12055. } else {
  12056. gen->output_base = substring(gen->output_name, 0, pos);
  12057. }
  12058. }
  12059. gbAllocator ha = heap_allocator();
  12060. array_init(&gen->output_object_paths, ha);
  12061. array_init(&gen->output_temp_paths, ha);
  12062. gen->output_base = path_to_full_path(ha, gen->output_base);
  12063. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  12064. output_file_path = gb_string_appendc(output_file_path, ".obj");
  12065. defer (gb_string_free(output_file_path));
  12066. gen->info = &c->info;
  12067. map_init(&gen->modules, permanent_allocator(), gen->info->packages.entries.count*2);
  12068. map_init(&gen->modules_through_ctx, permanent_allocator(), gen->info->packages.entries.count*2);
  12069. map_init(&gen->anonymous_proc_lits, heap_allocator(), 1024);
  12070. gb_mutex_init(&gen->mutex);
  12071. if (USE_SEPARTE_MODULES) {
  12072. for_array(i, gen->info->packages.entries) {
  12073. AstPackage *pkg = gen->info->packages.entries[i].value;
  12074. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  12075. m->pkg = pkg;
  12076. m->gen = gen;
  12077. map_set(&gen->modules, hash_pointer(pkg), m);
  12078. lb_init_module(m, c);
  12079. }
  12080. }
  12081. gen->default_module.gen = gen;
  12082. map_set(&gen->modules, hash_pointer(nullptr), &gen->default_module);
  12083. lb_init_module(&gen->default_module, c);
  12084. for_array(i, gen->modules.entries) {
  12085. lbModule *m = gen->modules.entries[i].value;
  12086. LLVMContextRef ctx = LLVMGetModuleContext(m->mod);
  12087. map_set(&gen->modules_through_ctx, hash_pointer(ctx), m);
  12088. }
  12089. return true;
  12090. }
  12091. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  12092. GB_ASSERT(type != nullptr);
  12093. type = default_type(type);
  12094. isize max_len = 7+8+1;
  12095. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  12096. u32 id = cast(u32)gb_atomic32_fetch_add(&m->gen->global_generated_index, 1);
  12097. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", id);
  12098. String name = make_string(str, len-1);
  12099. Scope *scope = nullptr;
  12100. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  12101. lbValue g = {};
  12102. g.type = alloc_type_pointer(type);
  12103. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  12104. if (value.value != nullptr) {
  12105. GB_ASSERT_MSG(LLVMIsConstant(value.value), LLVMPrintValueToString(value.value));
  12106. LLVMSetInitializer(g.value, value.value);
  12107. } else {
  12108. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  12109. }
  12110. lb_add_entity(m, e, g);
  12111. lb_add_member(m, name, g);
  12112. return lb_addr(g);
  12113. }
  12114. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  12115. AstPackage *p = m->info->runtime_package;
  12116. Entity *e = scope_lookup_current(p->scope, name);
  12117. return lb_find_value_from_entity(m, e);
  12118. }
  12119. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  12120. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  12121. lbValue *found = map_get(&m->values, hash_entity(e));
  12122. return lb_find_value_from_entity(m, e);
  12123. }
  12124. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  12125. i32 index = cast(i32)lb_type_info_index(m->info, type);
  12126. GB_ASSERT(index >= 0);
  12127. // gb_printf_err("%d %s\n", index, type_to_string(type));
  12128. LLVMValueRef indices[2] = {
  12129. LLVMConstInt(lb_type(m, t_int), 0, false),
  12130. LLVMConstInt(lb_type(m, t_int), index, false),
  12131. };
  12132. lbValue res = {};
  12133. res.type = t_type_info_ptr;
  12134. res.value = LLVMConstGEP(lb_global_type_info_data_ptr(m).value, indices, cast(unsigned)gb_count_of(indices));
  12135. return res;
  12136. }
  12137. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  12138. GB_ASSERT(p->module == &p->module->gen->default_module);
  12139. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  12140. lb_global_type_info_member_types_index += cast(i32)count;
  12141. return offset;
  12142. }
  12143. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  12144. GB_ASSERT(p->module == &p->module->gen->default_module);
  12145. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  12146. lb_global_type_info_member_names_index += cast(i32)count;
  12147. return offset;
  12148. }
  12149. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  12150. GB_ASSERT(p->module == &p->module->gen->default_module);
  12151. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  12152. lb_global_type_info_member_offsets_index += cast(i32)count;
  12153. return offset;
  12154. }
  12155. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  12156. GB_ASSERT(p->module == &p->module->gen->default_module);
  12157. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  12158. lb_global_type_info_member_usings_index += cast(i32)count;
  12159. return offset;
  12160. }
  12161. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  12162. GB_ASSERT(p->module == &p->module->gen->default_module);
  12163. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  12164. lb_global_type_info_member_tags_index += cast(i32)count;
  12165. return offset;
  12166. }
  12167. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  12168. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  12169. return lb_addr_get_ptr(p, addr);
  12170. }
  12171. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  12172. Token token = {Token_Ident};
  12173. isize name_len = prefix.len + 1 + 20;
  12174. auto suffix_id = cast(unsigned long long)id;
  12175. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  12176. gb_snprintf(text, name_len,
  12177. "%.*s-%llu", LIT(prefix), suffix_id);
  12178. text[name_len] = 0;
  12179. String s = make_string_c(text);
  12180. Type *t = alloc_type_array(elem_type, count);
  12181. lbValue g = {};
  12182. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  12183. g.type = alloc_type_pointer(t);
  12184. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  12185. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  12186. string_map_set(&m->members, s, g);
  12187. return g;
  12188. }
  12189. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  12190. lbModule *m = p->module;
  12191. LLVMContextRef ctx = m->ctx;
  12192. CheckerInfo *info = m->info;
  12193. {
  12194. // NOTE(bill): Set the type_table slice with the global backing array
  12195. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  12196. Type *type = base_type(lb_global_type_info_data_entity->type);
  12197. GB_ASSERT(is_type_array(type));
  12198. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  12199. LLVMValueRef values[2] = {
  12200. LLVMConstInBoundsGEP(lb_global_type_info_data_ptr(m).value, indices, gb_count_of(indices)),
  12201. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  12202. };
  12203. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  12204. LLVMSetInitializer(global_type_table.value, slice);
  12205. }
  12206. // Useful types
  12207. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  12208. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  12209. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  12210. Type *t_type_info_flags = type_info_flags_entity->type;
  12211. i32 type_info_member_types_index = 0;
  12212. i32 type_info_member_names_index = 0;
  12213. i32 type_info_member_offsets_index = 0;
  12214. for_array(type_info_type_index, info->type_info_types) {
  12215. Type *t = info->type_info_types[type_info_type_index];
  12216. if (t == nullptr || t == t_invalid) {
  12217. continue;
  12218. }
  12219. isize entry_index = lb_type_info_index(info, t, false);
  12220. if (entry_index <= 0) {
  12221. continue;
  12222. }
  12223. lbValue tag = {};
  12224. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data_ptr(m), cast(i32)entry_index);
  12225. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  12226. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  12227. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  12228. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  12229. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  12230. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  12231. switch (t->kind) {
  12232. case Type_Named: {
  12233. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  12234. LLVMValueRef pkg_name = nullptr;
  12235. if (t->Named.type_name->pkg) {
  12236. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  12237. } else {
  12238. pkg_name = LLVMConstNull(lb_type(m, t_string));
  12239. }
  12240. String proc_name = {};
  12241. if (t->Named.type_name->parent_proc_decl) {
  12242. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  12243. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  12244. proc_name = decl->entity->token.string;
  12245. }
  12246. }
  12247. TokenPos pos = t->Named.type_name->token.pos;
  12248. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  12249. LLVMValueRef vals[4] = {
  12250. lb_const_string(p->module, t->Named.type_name->token.string).value,
  12251. lb_get_type_info_ptr(m, t->Named.base).value,
  12252. pkg_name,
  12253. loc.value
  12254. };
  12255. lbValue res = {};
  12256. res.type = type_deref(tag.type);
  12257. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12258. lb_emit_store(p, tag, res);
  12259. break;
  12260. }
  12261. case Type_Basic:
  12262. switch (t->Basic.kind) {
  12263. case Basic_bool:
  12264. case Basic_b8:
  12265. case Basic_b16:
  12266. case Basic_b32:
  12267. case Basic_b64:
  12268. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  12269. break;
  12270. case Basic_i8:
  12271. case Basic_u8:
  12272. case Basic_i16:
  12273. case Basic_u16:
  12274. case Basic_i32:
  12275. case Basic_u32:
  12276. case Basic_i64:
  12277. case Basic_u64:
  12278. case Basic_i128:
  12279. case Basic_u128:
  12280. case Basic_i16le:
  12281. case Basic_u16le:
  12282. case Basic_i32le:
  12283. case Basic_u32le:
  12284. case Basic_i64le:
  12285. case Basic_u64le:
  12286. case Basic_i128le:
  12287. case Basic_u128le:
  12288. case Basic_i16be:
  12289. case Basic_u16be:
  12290. case Basic_i32be:
  12291. case Basic_u32be:
  12292. case Basic_i64be:
  12293. case Basic_u64be:
  12294. case Basic_i128be:
  12295. case Basic_u128be:
  12296. case Basic_int:
  12297. case Basic_uint:
  12298. case Basic_uintptr: {
  12299. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  12300. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  12301. // NOTE(bill): This is matches the runtime layout
  12302. u8 endianness_value = 0;
  12303. if (t->Basic.flags & BasicFlag_EndianLittle) {
  12304. endianness_value = 1;
  12305. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  12306. endianness_value = 2;
  12307. }
  12308. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  12309. LLVMValueRef vals[2] = {
  12310. is_signed.value,
  12311. endianness.value,
  12312. };
  12313. lbValue res = {};
  12314. res.type = type_deref(tag.type);
  12315. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12316. lb_emit_store(p, tag, res);
  12317. break;
  12318. }
  12319. case Basic_rune:
  12320. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  12321. break;
  12322. case Basic_f16:
  12323. case Basic_f32:
  12324. case Basic_f64:
  12325. case Basic_f16le:
  12326. case Basic_f32le:
  12327. case Basic_f64le:
  12328. case Basic_f16be:
  12329. case Basic_f32be:
  12330. case Basic_f64be:
  12331. {
  12332. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  12333. // NOTE(bill): This is matches the runtime layout
  12334. u8 endianness_value = 0;
  12335. if (t->Basic.flags & BasicFlag_EndianLittle) {
  12336. endianness_value = 1;
  12337. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  12338. endianness_value = 2;
  12339. }
  12340. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  12341. LLVMValueRef vals[1] = {
  12342. endianness.value,
  12343. };
  12344. lbValue res = {};
  12345. res.type = type_deref(tag.type);
  12346. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12347. lb_emit_store(p, tag, res);
  12348. }
  12349. break;
  12350. case Basic_complex32:
  12351. case Basic_complex64:
  12352. case Basic_complex128:
  12353. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  12354. break;
  12355. case Basic_quaternion64:
  12356. case Basic_quaternion128:
  12357. case Basic_quaternion256:
  12358. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  12359. break;
  12360. case Basic_rawptr:
  12361. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  12362. break;
  12363. case Basic_string:
  12364. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  12365. break;
  12366. case Basic_cstring:
  12367. {
  12368. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  12369. LLVMValueRef vals[1] = {
  12370. lb_const_bool(m, t_bool, true).value,
  12371. };
  12372. lbValue res = {};
  12373. res.type = type_deref(tag.type);
  12374. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12375. lb_emit_store(p, tag, res);
  12376. }
  12377. break;
  12378. case Basic_any:
  12379. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  12380. break;
  12381. case Basic_typeid:
  12382. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  12383. break;
  12384. }
  12385. break;
  12386. case Type_Pointer: {
  12387. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  12388. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  12389. LLVMValueRef vals[1] = {
  12390. gep.value,
  12391. };
  12392. lbValue res = {};
  12393. res.type = type_deref(tag.type);
  12394. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12395. lb_emit_store(p, tag, res);
  12396. break;
  12397. }
  12398. case Type_Array: {
  12399. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  12400. i64 ez = type_size_of(t->Array.elem);
  12401. LLVMValueRef vals[3] = {
  12402. lb_get_type_info_ptr(m, t->Array.elem).value,
  12403. lb_const_int(m, t_int, ez).value,
  12404. lb_const_int(m, t_int, t->Array.count).value,
  12405. };
  12406. lbValue res = {};
  12407. res.type = type_deref(tag.type);
  12408. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12409. lb_emit_store(p, tag, res);
  12410. break;
  12411. }
  12412. case Type_EnumeratedArray: {
  12413. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  12414. LLVMValueRef vals[6] = {
  12415. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  12416. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  12417. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  12418. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  12419. // Unions
  12420. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  12421. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  12422. };
  12423. lbValue res = {};
  12424. res.type = type_deref(tag.type);
  12425. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12426. lb_emit_store(p, tag, res);
  12427. // NOTE(bill): Union assignment
  12428. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  12429. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  12430. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  12431. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  12432. lb_emit_store(p, min_value, min_v);
  12433. lb_emit_store(p, max_value, max_v);
  12434. break;
  12435. }
  12436. case Type_DynamicArray: {
  12437. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  12438. LLVMValueRef vals[2] = {
  12439. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  12440. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  12441. };
  12442. lbValue res = {};
  12443. res.type = type_deref(tag.type);
  12444. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12445. lb_emit_store(p, tag, res);
  12446. break;
  12447. }
  12448. case Type_Slice: {
  12449. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  12450. LLVMValueRef vals[2] = {
  12451. lb_get_type_info_ptr(m, t->Slice.elem).value,
  12452. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  12453. };
  12454. lbValue res = {};
  12455. res.type = type_deref(tag.type);
  12456. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12457. lb_emit_store(p, tag, res);
  12458. break;
  12459. }
  12460. case Type_Proc: {
  12461. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  12462. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  12463. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  12464. if (t->Proc.params != nullptr) {
  12465. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  12466. }
  12467. if (t->Proc.results != nullptr) {
  12468. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  12469. }
  12470. LLVMValueRef vals[4] = {
  12471. params,
  12472. results,
  12473. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  12474. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  12475. };
  12476. lbValue res = {};
  12477. res.type = type_deref(tag.type);
  12478. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12479. lb_emit_store(p, tag, res);
  12480. break;
  12481. }
  12482. case Type_Tuple: {
  12483. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  12484. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  12485. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  12486. for_array(i, t->Tuple.variables) {
  12487. // NOTE(bill): offset is not used for tuples
  12488. Entity *f = t->Tuple.variables[i];
  12489. lbValue index = lb_const_int(m, t_int, i);
  12490. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  12491. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  12492. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  12493. if (f->token.string.len > 0) {
  12494. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  12495. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  12496. }
  12497. }
  12498. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  12499. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  12500. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  12501. LLVMValueRef vals[2] = {
  12502. types_slice,
  12503. names_slice,
  12504. };
  12505. lbValue res = {};
  12506. res.type = type_deref(tag.type);
  12507. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12508. lb_emit_store(p, tag, res);
  12509. break;
  12510. }
  12511. case Type_Enum:
  12512. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  12513. {
  12514. GB_ASSERT(t->Enum.base_type != nullptr);
  12515. // 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));
  12516. LLVMValueRef vals[3] = {};
  12517. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  12518. if (t->Enum.fields.count > 0) {
  12519. auto fields = t->Enum.fields;
  12520. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  12521. str_lit("$enum_names"), cast(i64)entry_index);
  12522. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  12523. str_lit("$enum_values"), cast(i64)entry_index);
  12524. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  12525. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  12526. GB_ASSERT(is_type_integer(t->Enum.base_type));
  12527. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  12528. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  12529. for_array(i, fields) {
  12530. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  12531. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  12532. }
  12533. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  12534. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  12535. LLVMSetInitializer(name_array.value, name_init);
  12536. LLVMSetInitializer(value_array.value, value_init);
  12537. lbValue v_count = lb_const_int(m, t_int, fields.count);
  12538. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  12539. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  12540. } else {
  12541. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  12542. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  12543. }
  12544. lbValue res = {};
  12545. res.type = type_deref(tag.type);
  12546. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12547. lb_emit_store(p, tag, res);
  12548. }
  12549. break;
  12550. case Type_Union: {
  12551. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  12552. {
  12553. LLVMValueRef vals[7] = {};
  12554. isize variant_count = gb_max(0, t->Union.variants.count);
  12555. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  12556. // NOTE(bill): Zeroth is nil so ignore it
  12557. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  12558. Type *vt = t->Union.variants[variant_index];
  12559. lbValue tip = lb_get_type_info_ptr(m, vt);
  12560. lbValue index = lb_const_int(m, t_int, variant_index);
  12561. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  12562. lb_emit_store(p, type_info, lb_type_info(m, vt));
  12563. }
  12564. lbValue count = lb_const_int(m, t_int, variant_count);
  12565. vals[0] = llvm_const_slice(m, memory_types, count);
  12566. i64 tag_size = union_tag_size(t);
  12567. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  12568. if (tag_size > 0) {
  12569. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  12570. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  12571. } else {
  12572. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  12573. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  12574. }
  12575. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  12576. vals[3] = lb_get_equal_proc_for_type(m, t).value;
  12577. }
  12578. vals[4] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  12579. vals[5] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  12580. vals[6] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  12581. for (isize i = 0; i < gb_count_of(vals); i++) {
  12582. if (vals[i] == nullptr) {
  12583. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  12584. }
  12585. }
  12586. lbValue res = {};
  12587. res.type = type_deref(tag.type);
  12588. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12589. lb_emit_store(p, tag, res);
  12590. }
  12591. break;
  12592. }
  12593. case Type_Struct: {
  12594. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  12595. LLVMValueRef vals[12] = {};
  12596. {
  12597. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  12598. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  12599. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  12600. vals[5] = is_packed.value;
  12601. vals[6] = is_raw_union.value;
  12602. vals[7] = is_custom_align.value;
  12603. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  12604. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  12605. }
  12606. if (t->Struct.soa_kind != StructSoa_None) {
  12607. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  12608. Type *kind_type = type_deref(kind.type);
  12609. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  12610. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  12611. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  12612. vals[9] = soa_kind.value;
  12613. vals[10] = soa_type.value;
  12614. vals[11] = soa_len.value;
  12615. }
  12616. }
  12617. isize count = t->Struct.fields.count;
  12618. if (count > 0) {
  12619. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  12620. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  12621. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  12622. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  12623. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  12624. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  12625. for (isize source_index = 0; source_index < count; source_index++) {
  12626. // TODO(bill): Order fields in source order not layout order
  12627. Entity *f = t->Struct.fields[source_index];
  12628. lbValue tip = lb_get_type_info_ptr(m, f->type);
  12629. i64 foffset = 0;
  12630. if (!t->Struct.is_raw_union) {
  12631. foffset = t->Struct.offsets[f->Variable.field_index];
  12632. }
  12633. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  12634. lbValue index = lb_const_int(m, t_int, source_index);
  12635. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  12636. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  12637. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  12638. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  12639. if (f->token.string.len > 0) {
  12640. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  12641. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  12642. }
  12643. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  12644. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  12645. if (t->Struct.tags.count > 0) {
  12646. String tag_string = t->Struct.tags[source_index];
  12647. if (tag_string.len > 0) {
  12648. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  12649. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  12650. }
  12651. }
  12652. }
  12653. lbValue cv = lb_const_int(m, t_int, count);
  12654. vals[0] = llvm_const_slice(m, memory_types, cv);
  12655. vals[1] = llvm_const_slice(m, memory_names, cv);
  12656. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  12657. vals[3] = llvm_const_slice(m, memory_usings, cv);
  12658. vals[4] = llvm_const_slice(m, memory_tags, cv);
  12659. }
  12660. for (isize i = 0; i < gb_count_of(vals); i++) {
  12661. if (vals[i] == nullptr) {
  12662. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  12663. }
  12664. }
  12665. lbValue res = {};
  12666. res.type = type_deref(tag.type);
  12667. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12668. lb_emit_store(p, tag, res);
  12669. break;
  12670. }
  12671. case Type_Map: {
  12672. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  12673. init_map_internal_types(t);
  12674. LLVMValueRef vals[5] = {
  12675. lb_get_type_info_ptr(m, t->Map.key).value,
  12676. lb_get_type_info_ptr(m, t->Map.value).value,
  12677. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  12678. lb_get_equal_proc_for_type(m, t->Map.key).value,
  12679. lb_get_hasher_proc_for_type(m, t->Map.key).value
  12680. };
  12681. lbValue res = {};
  12682. res.type = type_deref(tag.type);
  12683. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12684. lb_emit_store(p, tag, res);
  12685. break;
  12686. }
  12687. case Type_BitSet:
  12688. {
  12689. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  12690. GB_ASSERT(is_type_typed(t->BitSet.elem));
  12691. LLVMValueRef vals[4] = {
  12692. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  12693. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  12694. lb_const_int(m, t_i64, t->BitSet.lower).value,
  12695. lb_const_int(m, t_i64, t->BitSet.upper).value,
  12696. };
  12697. if (t->BitSet.underlying != nullptr) {
  12698. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  12699. }
  12700. lbValue res = {};
  12701. res.type = type_deref(tag.type);
  12702. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12703. lb_emit_store(p, tag, res);
  12704. }
  12705. break;
  12706. case Type_SimdVector:
  12707. {
  12708. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  12709. LLVMValueRef vals[3] = {};
  12710. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  12711. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  12712. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  12713. lbValue res = {};
  12714. res.type = type_deref(tag.type);
  12715. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12716. lb_emit_store(p, tag, res);
  12717. }
  12718. break;
  12719. case Type_RelativePointer:
  12720. {
  12721. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  12722. LLVMValueRef vals[2] = {
  12723. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  12724. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  12725. };
  12726. lbValue res = {};
  12727. res.type = type_deref(tag.type);
  12728. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12729. lb_emit_store(p, tag, res);
  12730. }
  12731. break;
  12732. case Type_RelativeSlice:
  12733. {
  12734. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  12735. LLVMValueRef vals[2] = {
  12736. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  12737. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  12738. };
  12739. lbValue res = {};
  12740. res.type = type_deref(tag.type);
  12741. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  12742. lb_emit_store(p, tag, res);
  12743. }
  12744. break;
  12745. }
  12746. if (tag.value != nullptr) {
  12747. Type *tag_type = type_deref(tag.type);
  12748. GB_ASSERT(is_type_named(tag_type));
  12749. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  12750. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  12751. } else {
  12752. if (t != t_llvm_bool) {
  12753. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  12754. }
  12755. }
  12756. }
  12757. }
  12758. struct lbGlobalVariable {
  12759. lbValue var;
  12760. lbValue init;
  12761. DeclInfo *decl;
  12762. bool is_initialized;
  12763. };
  12764. lbProcedure *lb_create_startup_type_info(lbModule *m) {
  12765. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12766. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  12767. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12768. Type *params = alloc_type_tuple();
  12769. Type *results = alloc_type_tuple();
  12770. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  12771. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  12772. p->is_startup = true;
  12773. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  12774. lb_begin_procedure_body(p);
  12775. lb_setup_type_info_data(p);
  12776. lb_end_procedure_body(p);
  12777. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12778. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12779. LLVMDumpValue(p->value);
  12780. gb_printf_err("\n\n\n\n");
  12781. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12782. }
  12783. lb_run_function_pass_manager(default_function_pass_manager, p);
  12784. return p;
  12785. }
  12786. lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *startup_type_info, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  12787. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(main_module->mod);
  12788. lb_populate_function_pass_manager(main_module, default_function_pass_manager, false, build_context.optimization_level);
  12789. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12790. Type *params = alloc_type_tuple();
  12791. Type *results = alloc_type_tuple();
  12792. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  12793. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  12794. p->is_startup = true;
  12795. lb_begin_procedure_body(p);
  12796. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(main_module, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  12797. for_array(i, global_variables) {
  12798. auto *var = &global_variables[i];
  12799. if (var->is_initialized) {
  12800. continue;
  12801. }
  12802. lbModule *entity_module = main_module;
  12803. Entity *e = var->decl->entity;
  12804. GB_ASSERT(e->kind == Entity_Variable);
  12805. e->code_gen_module = entity_module;
  12806. Ast *init_expr = var->decl->init_expr;
  12807. if (init_expr != nullptr) {
  12808. lbValue init = lb_build_expr(p, init_expr);
  12809. if (init.value == nullptr) {
  12810. LLVMTypeRef global_type = LLVMGetElementType(LLVMTypeOf(var->var.value));
  12811. if (is_type_untyped_undef(init.type)) {
  12812. LLVMSetInitializer(var->var.value, LLVMGetUndef(global_type));
  12813. var->is_initialized = true;
  12814. continue;
  12815. } else if (is_type_untyped_nil(init.type)) {
  12816. LLVMSetInitializer(var->var.value, LLVMConstNull(global_type));
  12817. var->is_initialized = true;
  12818. continue;
  12819. }
  12820. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  12821. }
  12822. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  12823. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  12824. if (is_type_any(e->type) || is_type_union(e->type)) {
  12825. var->init = init;
  12826. } else if (lb_is_const_or_global(init)) {
  12827. if (!var->is_initialized) {
  12828. LLVMSetInitializer(var->var.value, init.value);
  12829. var->is_initialized = true;
  12830. continue;
  12831. }
  12832. } else {
  12833. var->init = init;
  12834. }
  12835. }
  12836. if (var->init.value != nullptr) {
  12837. GB_ASSERT(!var->is_initialized);
  12838. Type *t = type_deref(var->var.type);
  12839. if (is_type_any(t)) {
  12840. // NOTE(bill): Edge case for 'any' type
  12841. Type *var_type = default_type(var->init.type);
  12842. lbAddr g = lb_add_global_generated(main_module, var_type, var->init);
  12843. lb_addr_store(p, g, var->init);
  12844. lbValue gp = lb_addr_get_ptr(p, g);
  12845. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  12846. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  12847. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  12848. lb_emit_store(p, ti, lb_type_info(main_module, var_type));
  12849. } else {
  12850. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  12851. LLVMTypeRef vt = LLVMGetElementType(pvt);
  12852. lbValue src0 = lb_emit_conv(p, var->init, t);
  12853. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  12854. LLVMValueRef dst = var->var.value;
  12855. LLVMBuildStore(p->builder, src, dst);
  12856. }
  12857. var->is_initialized = true;
  12858. }
  12859. }
  12860. lb_end_procedure_body(p);
  12861. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12862. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12863. LLVMDumpValue(p->value);
  12864. gb_printf_err("\n\n\n\n");
  12865. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12866. }
  12867. lb_run_function_pass_manager(default_function_pass_manager, p);
  12868. return p;
  12869. }
  12870. lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime) {
  12871. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  12872. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  12873. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  12874. Type *params = alloc_type_tuple();
  12875. Type *results = alloc_type_tuple();
  12876. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  12877. String name = str_lit("main");
  12878. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  12879. name = str_lit("mainCRTStartup");
  12880. } else {
  12881. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  12882. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  12883. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  12884. }
  12885. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  12886. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  12887. Type *proc_type = alloc_type_proc(nullptr,
  12888. params, params->Tuple.variables.count,
  12889. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  12890. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  12891. p->is_startup = true;
  12892. lb_begin_procedure_body(p);
  12893. { // initialize `runtime.args__`
  12894. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  12895. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  12896. LLVMSetValueName2(argc.value, "argc", 4);
  12897. LLVMSetValueName2(argv.value, "argv", 4);
  12898. argc = lb_emit_conv(p, argc, t_int);
  12899. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  12900. lb_fill_slice(p, args, argv, argc);
  12901. }
  12902. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  12903. if (build_context.command_kind == Command_test) {
  12904. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  12905. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  12906. Type *slice_type = alloc_type_slice(t_Internal_Test);
  12907. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  12908. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  12909. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  12910. LLVMValueRef indices[2] = {};
  12911. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  12912. for_array(i, m->info->testing_procedures) {
  12913. Entity *testing_proc = m->info->testing_procedures[i];
  12914. String name = testing_proc->token.string;
  12915. String pkg_name = {};
  12916. if (testing_proc->pkg != nullptr) {
  12917. pkg_name = testing_proc->pkg->name;
  12918. }
  12919. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  12920. lbValue v_name = lb_find_or_add_entity_string(m, name);
  12921. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  12922. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  12923. LLVMValueRef vals[3] = {};
  12924. vals[0] = v_pkg.value;
  12925. vals[1] = v_name.value;
  12926. vals[2] = v_proc.value;
  12927. GB_ASSERT(LLVMIsConstant(vals[0]));
  12928. GB_ASSERT(LLVMIsConstant(vals[1]));
  12929. GB_ASSERT(LLVMIsConstant(vals[2]));
  12930. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  12931. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  12932. LLVMBuildStore(p->builder, src, dst);
  12933. }
  12934. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  12935. lb_fill_slice(p, all_tests_slice,
  12936. lb_array_elem(p, all_tests_array),
  12937. lb_const_int(m, t_int, m->info->testing_procedures.count));
  12938. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  12939. auto args = array_make<lbValue>(heap_allocator(), 1);
  12940. args[0] = lb_addr_load(p, all_tests_slice);
  12941. lb_emit_call(p, runner, args);
  12942. } else {
  12943. if (m->info->entry_point != nullptr) {
  12944. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  12945. lb_emit_call(p, entry_point, {});
  12946. }
  12947. }
  12948. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  12949. lb_end_procedure_body(p);
  12950. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  12951. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  12952. LLVMDumpValue(p->value);
  12953. gb_printf_err("\n\n\n\n");
  12954. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  12955. }
  12956. lb_run_function_pass_manager(default_function_pass_manager, p);
  12957. return p;
  12958. }
  12959. String lb_filepath_ll_for_module(lbModule *m) {
  12960. String path = m->gen->output_base;
  12961. if (m->pkg) {
  12962. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  12963. } else if (USE_SEPARTE_MODULES) {
  12964. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  12965. }
  12966. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  12967. return path;
  12968. }
  12969. String lb_filepath_obj_for_module(lbModule *m) {
  12970. String path = m->gen->output_base;
  12971. if (m->pkg) {
  12972. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  12973. }
  12974. String ext = {};
  12975. if (build_context.build_mode == BuildMode_Assembly) {
  12976. ext = STR_LIT(".S");
  12977. } else {
  12978. if (is_arch_wasm()) {
  12979. ext = STR_LIT(".wasm.o");
  12980. } else {
  12981. switch (build_context.metrics.os) {
  12982. case TargetOs_windows:
  12983. ext = STR_LIT(".obj");
  12984. break;
  12985. default:
  12986. case TargetOs_darwin:
  12987. case TargetOs_linux:
  12988. case TargetOs_essence:
  12989. ext = STR_LIT(".o");
  12990. break;
  12991. }
  12992. }
  12993. }
  12994. return concatenate_strings(permanent_allocator(), path, ext);
  12995. }
  12996. bool lb_is_module_empty(lbModule *m) {
  12997. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  12998. LLVMGetFirstGlobal(m->mod) == nullptr) {
  12999. return true;
  13000. }
  13001. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  13002. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  13003. return false;
  13004. }
  13005. }
  13006. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  13007. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  13008. continue;
  13009. }
  13010. if (!LLVMIsExternallyInitialized(g)) {
  13011. return false;
  13012. }
  13013. }
  13014. return true;
  13015. }
  13016. struct lbLLVMEmitWorker {
  13017. LLVMTargetMachineRef target_machine;
  13018. LLVMCodeGenFileType code_gen_file_type;
  13019. String filepath_obj;
  13020. lbModule *m;
  13021. };
  13022. WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  13023. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  13024. char *llvm_error = nullptr;
  13025. auto wd = cast(lbLLVMEmitWorker *)data;
  13026. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  13027. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13028. gb_exit(1);
  13029. }
  13030. return 0;
  13031. }
  13032. WORKER_TASK_PROC(lb_llvm_function_pass_worker_proc) {
  13033. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  13034. auto m = cast(lbModule *)data;
  13035. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  13036. LLVMPassManagerRef function_pass_manager_minimal = LLVMCreateFunctionPassManagerForModule(m->mod);
  13037. LLVMPassManagerRef function_pass_manager_size = LLVMCreateFunctionPassManagerForModule(m->mod);
  13038. LLVMPassManagerRef function_pass_manager_speed = LLVMCreateFunctionPassManagerForModule(m->mod);
  13039. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  13040. LLVMInitializeFunctionPassManager(function_pass_manager_minimal);
  13041. LLVMInitializeFunctionPassManager(function_pass_manager_size);
  13042. LLVMInitializeFunctionPassManager(function_pass_manager_speed);
  13043. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  13044. lb_populate_function_pass_manager_specific(m, function_pass_manager_minimal, 0);
  13045. lb_populate_function_pass_manager_specific(m, function_pass_manager_size, 1);
  13046. lb_populate_function_pass_manager_specific(m, function_pass_manager_speed, 2);
  13047. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  13048. LLVMFinalizeFunctionPassManager(function_pass_manager_minimal);
  13049. LLVMFinalizeFunctionPassManager(function_pass_manager_size);
  13050. LLVMFinalizeFunctionPassManager(function_pass_manager_speed);
  13051. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(m->mod);
  13052. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  13053. lb_populate_function_pass_manager(m, default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  13054. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  13055. for_array(i, m->procedures_to_generate) {
  13056. lbProcedure *p = m->procedures_to_generate[i];
  13057. if (p->body != nullptr) { // Build Procedure
  13058. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  13059. lb_run_function_pass_manager(default_function_pass_manager_without_memcpy, p);
  13060. } else {
  13061. if (p->entity && p->entity->kind == Entity_Procedure) {
  13062. switch (p->entity->Procedure.optimization_mode) {
  13063. case ProcedureOptimizationMode_None:
  13064. case ProcedureOptimizationMode_Minimal:
  13065. lb_run_function_pass_manager(function_pass_manager_minimal, p);
  13066. break;
  13067. case ProcedureOptimizationMode_Size:
  13068. lb_run_function_pass_manager(function_pass_manager_size, p);
  13069. break;
  13070. case ProcedureOptimizationMode_Speed:
  13071. lb_run_function_pass_manager(function_pass_manager_speed, p);
  13072. break;
  13073. default:
  13074. lb_run_function_pass_manager(default_function_pass_manager, p);
  13075. break;
  13076. }
  13077. } else {
  13078. lb_run_function_pass_manager(default_function_pass_manager, p);
  13079. }
  13080. }
  13081. }
  13082. }
  13083. for_array(i, m->equal_procs.entries) {
  13084. lbProcedure *p = m->equal_procs.entries[i].value;
  13085. lb_run_function_pass_manager(default_function_pass_manager, p);
  13086. }
  13087. for_array(i, m->hasher_procs.entries) {
  13088. lbProcedure *p = m->hasher_procs.entries[i].value;
  13089. lb_run_function_pass_manager(default_function_pass_manager, p);
  13090. }
  13091. return 0;
  13092. }
  13093. struct lbLLVMModulePassWorkerData {
  13094. lbModule *m;
  13095. LLVMTargetMachineRef target_machine;
  13096. };
  13097. WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  13098. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  13099. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  13100. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  13101. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  13102. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  13103. return 0;
  13104. }
  13105. void lb_generate_code(lbGenerator *gen) {
  13106. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  13107. #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)
  13108. TIME_SECTION("LLVM Initializtion");
  13109. isize thread_count = gb_max(build_context.thread_count, 1);
  13110. isize worker_count = thread_count-1;
  13111. LLVMBool do_threading = (LLVMIsMultithreaded() && USE_SEPARTE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  13112. thread_pool_init(&lb_thread_pool, heap_allocator(), worker_count, "LLVMBackend");
  13113. defer (thread_pool_destroy(&lb_thread_pool));
  13114. lbModule *default_module = &gen->default_module;
  13115. CheckerInfo *info = gen->info;
  13116. auto *min_dep_set = &info->minimum_dependency_set;
  13117. LLVMInitializeAllTargetInfos();
  13118. LLVMInitializeAllTargets();
  13119. LLVMInitializeAllTargetMCs();
  13120. LLVMInitializeAllAsmPrinters();
  13121. LLVMInitializeAllAsmParsers();
  13122. LLVMInitializeAllDisassemblers();
  13123. LLVMInitializeNativeTarget();
  13124. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  13125. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  13126. for_array(i, gen->modules.entries) {
  13127. LLVMSetTarget(gen->modules.entries[i].value->mod, target_triple);
  13128. }
  13129. LLVMTargetRef target = {};
  13130. char *llvm_error = nullptr;
  13131. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  13132. GB_ASSERT(target != nullptr);
  13133. TIME_SECTION("LLVM Create Target Machine");
  13134. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  13135. if (is_arch_wasm()) {
  13136. code_mode = LLVMCodeModelJITDefault;
  13137. }
  13138. char const *host_cpu_name = LLVMGetHostCPUName();
  13139. char const *llvm_cpu = "generic";
  13140. char const *llvm_features = "";
  13141. if (build_context.microarch.len != 0) {
  13142. if (build_context.microarch == "native") {
  13143. llvm_cpu = host_cpu_name;
  13144. } else {
  13145. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  13146. }
  13147. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  13148. llvm_features = LLVMGetHostCPUFeatures();
  13149. }
  13150. }
  13151. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  13152. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  13153. switch (build_context.optimization_level) {
  13154. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  13155. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  13156. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  13157. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  13158. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  13159. }
  13160. // NOTE(bill): Target Machine Creation
  13161. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  13162. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), gen->modules.entries.count);
  13163. for_array(i, gen->modules.entries) {
  13164. target_machines[i] = LLVMCreateTargetMachine(
  13165. target, target_triple, llvm_cpu,
  13166. llvm_features,
  13167. code_gen_level,
  13168. LLVMRelocDefault,
  13169. code_mode);
  13170. LLVMSetModuleDataLayout(gen->modules.entries[i].value->mod, LLVMCreateTargetDataLayout(target_machines[i]));
  13171. }
  13172. for_array(i, gen->modules.entries) {
  13173. lbModule *m = gen->modules.entries[i].value;
  13174. if (m->debug_builder) { // Debug Info
  13175. for_array(i, info->files.entries) {
  13176. AstFile *f = info->files.entries[i].value;
  13177. String fullpath = f->fullpath;
  13178. String filename = remove_directory_from_path(fullpath);
  13179. String directory = directory_from_path(fullpath);
  13180. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  13181. cast(char const *)filename.text, filename.len,
  13182. cast(char const *)directory.text, directory.len);
  13183. lb_set_llvm_metadata(m, f, res);
  13184. }
  13185. gbString producer = gb_string_make(heap_allocator(), "odin");
  13186. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  13187. // #ifdef NIGHTLY
  13188. // producer = gb_string_appendc(producer, "-nightly");
  13189. // #endif
  13190. // #ifdef GIT_SHA
  13191. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  13192. // #endif
  13193. gbString split_name = gb_string_make(heap_allocator(), "");
  13194. LLVMBool is_optimized = build_context.optimization_level > 0;
  13195. AstFile *init_file = m->info->init_package->files[0];
  13196. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  13197. init_file = m->info->entry_point->identifier->file;
  13198. }
  13199. LLVMBool split_debug_inlining = false;
  13200. LLVMBool debug_info_for_profiling = false;
  13201. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  13202. lb_get_llvm_metadata(m, init_file),
  13203. producer, gb_string_length(producer),
  13204. is_optimized, "", 0,
  13205. 1, split_name, gb_string_length(split_name),
  13206. LLVMDWARFEmissionFull,
  13207. 0, split_debug_inlining,
  13208. debug_info_for_profiling,
  13209. "", 0, // sys_root
  13210. "", 0 // SDK
  13211. );
  13212. GB_ASSERT(m->debug_compile_unit != nullptr);
  13213. }
  13214. }
  13215. TIME_SECTION("LLVM Global Variables");
  13216. {
  13217. lbModule *m = default_module;
  13218. { // Add type info data
  13219. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  13220. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  13221. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  13222. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  13223. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13224. if (!USE_SEPARTE_MODULES) {
  13225. LLVMSetLinkage(g, LLVMInternalLinkage);
  13226. }
  13227. lbValue value = {};
  13228. value.value = g;
  13229. value.type = alloc_type_pointer(t);
  13230. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  13231. lb_add_entity(m, lb_global_type_info_data_entity, value);
  13232. }
  13233. { // Type info member buffer
  13234. // NOTE(bill): Removes need for heap allocation by making it global memory
  13235. isize count = 0;
  13236. for_array(entry_index, m->info->type_info_types) {
  13237. Type *t = m->info->type_info_types[entry_index];
  13238. isize index = lb_type_info_index(m->info, t, false);
  13239. if (index < 0) {
  13240. continue;
  13241. }
  13242. switch (t->kind) {
  13243. case Type_Union:
  13244. count += t->Union.variants.count;
  13245. break;
  13246. case Type_Struct:
  13247. count += t->Struct.fields.count;
  13248. break;
  13249. case Type_Tuple:
  13250. count += t->Tuple.variables.count;
  13251. break;
  13252. }
  13253. }
  13254. if (count > 0) {
  13255. {
  13256. char const *name = LB_TYPE_INFO_TYPES_NAME;
  13257. Type *t = alloc_type_array(t_type_info_ptr, count);
  13258. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13259. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13260. LLVMSetLinkage(g, LLVMInternalLinkage);
  13261. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  13262. }
  13263. {
  13264. char const *name = LB_TYPE_INFO_NAMES_NAME;
  13265. Type *t = alloc_type_array(t_string, count);
  13266. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13267. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13268. LLVMSetLinkage(g, LLVMInternalLinkage);
  13269. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  13270. }
  13271. {
  13272. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  13273. Type *t = alloc_type_array(t_uintptr, count);
  13274. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13275. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13276. LLVMSetLinkage(g, LLVMInternalLinkage);
  13277. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  13278. }
  13279. {
  13280. char const *name = LB_TYPE_INFO_USINGS_NAME;
  13281. Type *t = alloc_type_array(t_bool, count);
  13282. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13283. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13284. LLVMSetLinkage(g, LLVMInternalLinkage);
  13285. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  13286. }
  13287. {
  13288. char const *name = LB_TYPE_INFO_TAGS_NAME;
  13289. Type *t = alloc_type_array(t_string, count);
  13290. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  13291. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  13292. LLVMSetLinkage(g, LLVMInternalLinkage);
  13293. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  13294. }
  13295. }
  13296. }
  13297. }
  13298. isize global_variable_max_count = 0;
  13299. Entity *entry_point = info->entry_point;
  13300. bool has_dll_main = false;
  13301. bool has_win_main = false;
  13302. for_array(i, info->entities) {
  13303. Entity *e = info->entities[i];
  13304. String name = e->token.string;
  13305. bool is_global = e->pkg != nullptr;
  13306. if (e->kind == Entity_Variable) {
  13307. global_variable_max_count++;
  13308. } else if (e->kind == Entity_Procedure && !is_global) {
  13309. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  13310. GB_ASSERT(e == entry_point);
  13311. // entry_point = e;
  13312. }
  13313. if (e->Procedure.is_export ||
  13314. (e->Procedure.link_name.len > 0) ||
  13315. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  13316. if (!has_dll_main && name == "DllMain") {
  13317. has_dll_main = true;
  13318. } else if (!has_win_main && name == "WinMain") {
  13319. has_win_main = true;
  13320. }
  13321. }
  13322. }
  13323. }
  13324. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  13325. for_array(i, info->variable_init_order) {
  13326. DeclInfo *d = info->variable_init_order[i];
  13327. Entity *e = d->entity;
  13328. if ((e->scope->flags & ScopeFlag_File) == 0) {
  13329. continue;
  13330. }
  13331. if (!ptr_set_exists(min_dep_set, e)) {
  13332. continue;
  13333. }
  13334. DeclInfo *decl = decl_info_of_entity(e);
  13335. if (decl == nullptr) {
  13336. continue;
  13337. }
  13338. GB_ASSERT(e->kind == Entity_Variable);
  13339. bool is_foreign = e->Variable.is_foreign;
  13340. bool is_export = e->Variable.is_export;
  13341. lbModule *m = &gen->default_module;
  13342. String name = lb_get_entity_name(m, e);
  13343. lbValue g = {};
  13344. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  13345. g.type = alloc_type_pointer(e->type);
  13346. if (e->Variable.thread_local_model != "") {
  13347. LLVMSetThreadLocal(g.value, true);
  13348. String m = e->Variable.thread_local_model;
  13349. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  13350. if (m == "default") {
  13351. mode = LLVMGeneralDynamicTLSModel;
  13352. } else if (m == "localdynamic") {
  13353. mode = LLVMLocalDynamicTLSModel;
  13354. } else if (m == "initialexec") {
  13355. mode = LLVMInitialExecTLSModel;
  13356. } else if (m == "localexec") {
  13357. mode = LLVMLocalExecTLSModel;
  13358. } else {
  13359. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  13360. }
  13361. LLVMSetThreadLocalMode(g.value, mode);
  13362. }
  13363. if (is_foreign) {
  13364. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  13365. LLVMSetExternallyInitialized(g.value, true);
  13366. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  13367. } else {
  13368. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  13369. }
  13370. if (is_export) {
  13371. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  13372. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  13373. } else {
  13374. if (USE_SEPARTE_MODULES) {
  13375. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  13376. } else {
  13377. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  13378. }
  13379. }
  13380. if (e->Variable.link_section.len > 0) {
  13381. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  13382. }
  13383. lbGlobalVariable var = {};
  13384. var.var = g;
  13385. var.decl = decl;
  13386. if (decl->init_expr != nullptr) {
  13387. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  13388. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  13389. if (tav.mode != Addressing_Invalid) {
  13390. if (tav.value.kind != ExactValue_Invalid) {
  13391. ExactValue v = tav.value;
  13392. lbValue init = lb_const_value(m, tav.type, v);
  13393. LLVMSetInitializer(g.value, init.value);
  13394. var.is_initialized = true;
  13395. }
  13396. }
  13397. }
  13398. if (!var.is_initialized &&
  13399. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  13400. var.is_initialized = true;
  13401. }
  13402. }
  13403. array_add(&global_variables, var);
  13404. lb_add_entity(m, e, g);
  13405. lb_add_member(m, name, g);
  13406. if (m->debug_builder) {
  13407. String global_name = e->token.string;
  13408. if (global_name.len != 0 && global_name != "_") {
  13409. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  13410. LLVMMetadataRef llvm_scope = llvm_file;
  13411. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  13412. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  13413. LLVMMetadataRef llvm_decl = nullptr;
  13414. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  13415. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  13416. m->debug_builder, llvm_scope,
  13417. cast(char const *)global_name.text, global_name.len,
  13418. "", 0, // linkage
  13419. llvm_file, e->token.pos.line,
  13420. lb_debug_type(m, e->type),
  13421. local_to_unit,
  13422. llvm_expr,
  13423. llvm_decl,
  13424. align_in_bits
  13425. );
  13426. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  13427. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  13428. }
  13429. }
  13430. }
  13431. TIME_SECTION("LLVM Global Procedures and Types");
  13432. for_array(i, info->entities) {
  13433. Entity *e = info->entities[i];
  13434. String name = e->token.string;
  13435. DeclInfo *decl = e->decl_info;
  13436. Scope * scope = e->scope;
  13437. if ((scope->flags & ScopeFlag_File) == 0) {
  13438. continue;
  13439. }
  13440. Scope *package_scope = scope->parent;
  13441. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  13442. switch (e->kind) {
  13443. case Entity_Variable:
  13444. // NOTE(bill): Handled above as it requires a specific load order
  13445. continue;
  13446. case Entity_ProcGroup:
  13447. continue;
  13448. case Entity_TypeName:
  13449. case Entity_Procedure:
  13450. break;
  13451. }
  13452. bool polymorphic_struct = false;
  13453. if (e->type != nullptr && e->kind == Entity_TypeName) {
  13454. Type *bt = base_type(e->type);
  13455. if (bt->kind == Type_Struct) {
  13456. polymorphic_struct = is_type_polymorphic(bt);
  13457. }
  13458. }
  13459. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  13460. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  13461. continue;
  13462. }
  13463. lbModule *m = &gen->default_module;
  13464. if (USE_SEPARTE_MODULES) {
  13465. m = lb_pkg_module(gen, e->pkg);
  13466. }
  13467. String mangled_name = lb_get_entity_name(m, e);
  13468. switch (e->kind) {
  13469. case Entity_TypeName:
  13470. lb_type(m, e->type);
  13471. break;
  13472. case Entity_Procedure:
  13473. {
  13474. lbProcedure *p = lb_create_procedure(m, e);
  13475. array_add(&m->procedures_to_generate, p);
  13476. }
  13477. break;
  13478. }
  13479. }
  13480. TIME_SECTION("LLVM Runtime Type Information Creation");
  13481. lbProcedure *startup_type_info = lb_create_startup_type_info(default_module);
  13482. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  13483. lbProcedure *startup_runtime = lb_create_startup_runtime(default_module, startup_type_info, global_variables);
  13484. TIME_SECTION("LLVM Procedure Generation");
  13485. for_array(j, gen->modules.entries) {
  13486. lbModule *m = gen->modules.entries[j].value;
  13487. for_array(i, m->procedures_to_generate) {
  13488. lbProcedure *p = m->procedures_to_generate[i];
  13489. if (p->is_done) {
  13490. continue;
  13491. }
  13492. if (p->body != nullptr) { // Build Procedure
  13493. m->curr_procedure = p;
  13494. lb_begin_procedure_body(p);
  13495. lb_build_stmt(p, p->body);
  13496. lb_end_procedure_body(p);
  13497. p->is_done = true;
  13498. m->curr_procedure = nullptr;
  13499. }
  13500. lb_end_procedure(p);
  13501. // Add Flags
  13502. if (p->body != nullptr) {
  13503. if (p->name == "memcpy" || p->name == "memmove" ||
  13504. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  13505. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  13506. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  13507. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  13508. }
  13509. }
  13510. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  13511. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  13512. LLVMDumpValue(p->value);
  13513. gb_printf_err("\n\n\n\n");
  13514. String filepath_ll = lb_filepath_ll_for_module(m);
  13515. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  13516. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13517. }
  13518. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  13519. gb_exit(1);
  13520. }
  13521. }
  13522. }
  13523. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  13524. TIME_SECTION("LLVM main");
  13525. lb_create_main_procedure(default_module, startup_runtime);
  13526. }
  13527. if (build_context.ODIN_DEBUG) {
  13528. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  13529. for_array(j, gen->modules.entries) {
  13530. lbModule *m = gen->modules.entries[j].value;
  13531. if (m->debug_builder != nullptr) {
  13532. lb_debug_complete_types(m);
  13533. LLVMDIBuilderFinalize(m->debug_builder);
  13534. }
  13535. }
  13536. }
  13537. TIME_SECTION("LLVM Function Pass");
  13538. for_array(i, gen->modules.entries) {
  13539. lbModule *m = gen->modules.entries[i].value;
  13540. lb_llvm_function_pass_worker_proc(m);
  13541. }
  13542. TIME_SECTION("LLVM Module Pass");
  13543. for_array(i, gen->modules.entries) {
  13544. lbModule *m = gen->modules.entries[i].value;
  13545. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  13546. wd->m = m;
  13547. wd->target_machine = target_machines[i];
  13548. lb_llvm_module_pass_worker_proc(wd);
  13549. }
  13550. llvm_error = nullptr;
  13551. defer (LLVMDisposeMessage(llvm_error));
  13552. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  13553. if (build_context.build_mode == BuildMode_Assembly) {
  13554. code_gen_file_type = LLVMAssemblyFile;
  13555. }
  13556. for_array(j, gen->modules.entries) {
  13557. lbModule *m = gen->modules.entries[j].value;
  13558. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  13559. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  13560. if (build_context.keep_temp_files) {
  13561. TIME_SECTION("LLVM Print Module to File");
  13562. String filepath_ll = lb_filepath_ll_for_module(m);
  13563. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  13564. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13565. gb_exit(1);
  13566. return;
  13567. }
  13568. }
  13569. gb_exit(1);
  13570. return;
  13571. }
  13572. }
  13573. llvm_error = nullptr;
  13574. if (build_context.keep_temp_files ||
  13575. build_context.build_mode == BuildMode_LLVM_IR) {
  13576. TIME_SECTION("LLVM Print Module to File");
  13577. for_array(j, gen->modules.entries) {
  13578. lbModule *m = gen->modules.entries[j].value;
  13579. if (lb_is_module_empty(m)) {
  13580. continue;
  13581. }
  13582. String filepath_ll = lb_filepath_ll_for_module(m);
  13583. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  13584. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13585. gb_exit(1);
  13586. return;
  13587. }
  13588. array_add(&gen->output_temp_paths, filepath_ll);
  13589. }
  13590. if (build_context.build_mode == BuildMode_LLVM_IR) {
  13591. gb_exit(0);
  13592. return;
  13593. }
  13594. }
  13595. TIME_SECTION("LLVM Add Foreign Library Paths");
  13596. for_array(j, gen->modules.entries) {
  13597. lbModule *m = gen->modules.entries[j].value;
  13598. for_array(i, m->info->required_foreign_imports_through_force) {
  13599. Entity *e = m->info->required_foreign_imports_through_force[i];
  13600. lb_add_foreign_library_path(m, e);
  13601. }
  13602. if (lb_is_module_empty(m)) {
  13603. continue;
  13604. }
  13605. }
  13606. TIME_SECTION("LLVM Object Generation");
  13607. if (do_threading) {
  13608. for_array(j, gen->modules.entries) {
  13609. lbModule *m = gen->modules.entries[j].value;
  13610. if (lb_is_module_empty(m)) {
  13611. continue;
  13612. }
  13613. String filepath_ll = lb_filepath_ll_for_module(m);
  13614. String filepath_obj = lb_filepath_obj_for_module(m);
  13615. array_add(&gen->output_object_paths, filepath_obj);
  13616. array_add(&gen->output_temp_paths, filepath_ll);
  13617. auto *wd = gb_alloc_item(heap_allocator(), lbLLVMEmitWorker);
  13618. wd->target_machine = target_machines[j];
  13619. wd->code_gen_file_type = code_gen_file_type;
  13620. wd->filepath_obj = filepath_obj;
  13621. wd->m = m;
  13622. thread_pool_add_task(&lb_thread_pool, lb_llvm_emit_worker_proc, wd);
  13623. }
  13624. thread_pool_start(&lb_thread_pool);
  13625. thread_pool_wait_to_process(&lb_thread_pool);
  13626. } else {
  13627. for_array(j, gen->modules.entries) {
  13628. lbModule *m = gen->modules.entries[j].value;
  13629. if (lb_is_module_empty(m)) {
  13630. continue;
  13631. }
  13632. String filepath_obj = lb_filepath_obj_for_module(m);
  13633. array_add(&gen->output_object_paths, filepath_obj);
  13634. String short_name = remove_directory_from_path(filepath_obj);
  13635. gbString section_name = gb_string_make(heap_allocator(), "LLVM Generate Object: ");
  13636. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  13637. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  13638. if (LLVMTargetMachineEmitToFile(target_machines[j], m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  13639. gb_printf_err("LLVM Error: %s\n", llvm_error);
  13640. gb_exit(1);
  13641. return;
  13642. }
  13643. }
  13644. }
  13645. #undef TIME_SECTION
  13646. }