llvm_backend.cpp 327 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663
  1. #include "llvm_backend.hpp"
  2. gb_global lbAddr lb_global_type_info_data = {};
  3. gb_global lbAddr lb_global_type_info_member_types = {};
  4. gb_global lbAddr lb_global_type_info_member_names = {};
  5. gb_global lbAddr lb_global_type_info_member_offsets = {};
  6. gb_global lbAddr lb_global_type_info_member_usings = {};
  7. gb_global lbAddr lb_global_type_info_member_tags = {};
  8. gb_global isize lb_global_type_info_data_index = 0;
  9. gb_global isize lb_global_type_info_member_types_index = 0;
  10. gb_global isize lb_global_type_info_member_names_index = 0;
  11. gb_global isize lb_global_type_info_member_offsets_index = 0;
  12. gb_global isize lb_global_type_info_member_usings_index = 0;
  13. gb_global isize lb_global_type_info_member_tags_index = 0;
  14. struct lbLoopData {
  15. lbAddr idx_addr;
  16. lbValue idx;
  17. lbBlock *body;
  18. lbBlock *done;
  19. lbBlock *loop;
  20. };
  21. struct lbCompoundLitElemTempData {
  22. Ast * expr;
  23. lbValue value;
  24. i32 elem_index;
  25. lbValue gep;
  26. };
  27. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  28. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  29. LLVMValueRef llvm_zero32(lbModule *m) {
  30. return LLVMConstInt(lb_type(m, t_i32), 0, false);
  31. }
  32. LLVMValueRef llvm_one32(lbModule *m) {
  33. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  34. }
  35. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  36. lbValue v = lb_find_or_add_entity_string(m, str);
  37. unsigned indices[1] = {0};
  38. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  39. }
  40. lbAddr lb_addr(lbValue addr) {
  41. lbAddr v = {lbAddr_Default, addr};
  42. return v;
  43. }
  44. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  45. lbAddr v = {lbAddr_Map, addr};
  46. v.map.key = map_key;
  47. v.map.type = map_type;
  48. v.map.result = map_result;
  49. return v;
  50. }
  51. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  52. lbAddr v = {lbAddr_SoaVariable, addr};
  53. v.soa.index = index;
  54. v.soa.index_expr = index_expr;
  55. return v;
  56. }
  57. lbAddr lb_addr_bit_field(lbValue value, i32 index) {
  58. lbAddr addr = {};
  59. addr.kind = lbAddr_BitField;
  60. addr.addr = value;
  61. addr.bit_field.value_index = index;
  62. return addr;
  63. }
  64. Type *lb_addr_type(lbAddr const &addr) {
  65. if (addr.addr.value == nullptr) {
  66. return nullptr;
  67. }
  68. if (addr.kind == lbAddr_Map) {
  69. Type *t = base_type(addr.map.type);
  70. GB_ASSERT(is_type_map(t));
  71. return t->Map.value;
  72. }
  73. return type_deref(addr.addr.type);
  74. }
  75. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  76. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  77. }
  78. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  79. if (addr.addr.value == nullptr) {
  80. GB_PANIC("Illegal addr -> nullptr");
  81. return {};
  82. }
  83. switch (addr.kind) {
  84. case lbAddr_Map:
  85. case lbAddr_BitField: {
  86. lbValue v = lb_addr_load(p, addr);
  87. return lb_address_from_load_or_generate_local(p, v);
  88. }
  89. case lbAddr_Context:
  90. GB_PANIC("lbAddr_Context should be handled elsewhere");
  91. }
  92. return addr.addr;
  93. }
  94. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  95. lbAddr addr = lb_build_addr(p, expr);
  96. return lb_addr_get_ptr(p, addr);
  97. }
  98. void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) {
  99. if (addr.addr.value == nullptr) {
  100. return;
  101. }
  102. GB_ASSERT(value.type != nullptr);
  103. if (is_type_untyped_undef(value.type)) {
  104. Type *t = lb_addr_type(addr);
  105. value.type = t;
  106. value.value = LLVMGetUndef(lb_type(p->module, t));
  107. } else if (is_type_untyped_nil(value.type)) {
  108. Type *t = lb_addr_type(addr);
  109. value.type = t;
  110. value.value = LLVMConstNull(lb_type(p->module, t));
  111. }
  112. if (addr.kind == lbAddr_Map) {
  113. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value);
  114. return;
  115. } else if (addr.kind == lbAddr_BitField) {
  116. Type *bft = base_type(type_deref(addr.addr.type));
  117. GB_ASSERT(is_type_bit_field(bft));
  118. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  119. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  120. if (size_in_bits == 0) {
  121. return;
  122. }
  123. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  124. LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits);
  125. LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, "");
  126. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  127. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  128. LLVMBuildStore(p->builder, src, field_ptr);
  129. return;
  130. } else if (addr.kind == lbAddr_Context) {
  131. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  132. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  133. lb_addr_store(p, next_addr, old);
  134. lb_push_context_onto_stack(p, next_addr);
  135. lbValue next = lb_addr_get_ptr(p, next_addr);
  136. if (addr.ctx.sel.index.count > 0) {
  137. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  138. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  139. lb_emit_store(p, lhs, rhs);
  140. } else {
  141. lbValue lhs = next;
  142. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  143. lb_emit_store(p, lhs, rhs);
  144. }
  145. return;
  146. } else if (addr.kind == lbAddr_SoaVariable) {
  147. Type *t = type_deref(addr.addr.type);
  148. t = base_type(t);
  149. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  150. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  151. lbValue index = addr.soa.index;
  152. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  153. Type *t = base_type(type_deref(addr.addr.type));
  154. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  155. i64 count = t->Struct.soa_count;
  156. lbValue len = lb_const_int(p->module, t_int, count);
  157. // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  158. }
  159. for_array(i, t->Struct.fields) {
  160. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  161. dst = lb_emit_array_ep(p, dst, index);
  162. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  163. lb_emit_store(p, dst, src);
  164. }
  165. return;
  166. }
  167. GB_ASSERT(value.value != nullptr);
  168. value = lb_emit_conv(p, value, lb_addr_type(addr));
  169. LLVMBuildStore(p->builder, value.value, addr.addr.value);
  170. }
  171. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  172. GB_ASSERT(value.value != nullptr);
  173. Type *a = type_deref(ptr.type);
  174. if (is_type_boolean(a)) {
  175. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  176. value = lb_emit_conv(p, value, a);
  177. }
  178. Type *ca = core_type(a);
  179. if (ca->kind == Type_Basic) {
  180. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  181. } else {
  182. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  183. }
  184. LLVMValueRef v = LLVMBuildStore(p->builder, value.value, ptr.value);
  185. }
  186. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  187. lbModule *m = p->module;
  188. GB_ASSERT(value.value != nullptr);
  189. Type *t = type_deref(value.type);
  190. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  191. return lbValue{v, t};
  192. }
  193. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  194. GB_ASSERT(addr.addr.value != nullptr);
  195. if (addr.kind == lbAddr_Map) {
  196. Type *map_type = base_type(addr.map.type);
  197. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  198. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  199. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  200. auto args = array_make<lbValue>(heap_allocator(), 2);
  201. args[0] = h;
  202. args[1] = key;
  203. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  204. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  205. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  206. lbBlock *then = lb_create_block(p, "map.get.then");
  207. lbBlock *done = lb_create_block(p, "map.get.done");
  208. lb_emit_if(p, ok, then, done);
  209. lb_start_block(p, then);
  210. {
  211. // TODO(bill): mem copy it instead?
  212. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  213. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  214. lb_emit_store(p, gep0, lb_emit_load(p, value));
  215. }
  216. lb_emit_jump(p, done);
  217. lb_start_block(p, done);
  218. if (is_type_tuple(addr.map.result)) {
  219. return lb_addr_load(p, v);
  220. } else {
  221. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  222. return lb_emit_load(p, single);
  223. }
  224. } else if (addr.kind == lbAddr_BitField) {
  225. Type *bft = base_type(type_deref(addr.addr.type));
  226. GB_ASSERT(is_type_bit_field(bft));
  227. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  228. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  229. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  230. if (size_in_bytes == 0) {
  231. GB_ASSERT(size_in_bits == 0);
  232. lbValue res = {};
  233. res.type = t_i32;
  234. res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false);
  235. return res;
  236. }
  237. Type *int_type = nullptr;
  238. switch (size_in_bytes) {
  239. case 1: int_type = t_u8; break;
  240. case 2: int_type = t_u16; break;
  241. case 4: int_type = t_u32; break;
  242. case 8: int_type = t_u64; break;
  243. case 16: int_type = t_u128; break;
  244. }
  245. GB_ASSERT(int_type != nullptr);
  246. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  247. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  248. LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, "");
  249. lbValue res = {};
  250. res.type = int_type;
  251. res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), "");
  252. return res;
  253. } else if (addr.kind == lbAddr_Context) {
  254. if (addr.ctx.sel.index.count > 0) {
  255. lbValue a = addr.addr;
  256. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  257. return lb_emit_load(p, b);
  258. } else {
  259. return lb_emit_load(p, addr.addr);
  260. }
  261. } else if (addr.kind == lbAddr_SoaVariable) {
  262. Type *t = type_deref(addr.addr.type);
  263. t = base_type(t);
  264. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  265. Type *elem = t->Struct.soa_elem;
  266. lbValue len = {};
  267. if (t->Struct.soa_kind == StructSoa_Fixed) {
  268. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  269. } else {
  270. lbValue v = lb_emit_load(p, addr.addr);
  271. len = lb_soa_struct_len(p, v);
  272. }
  273. lbAddr res = lb_add_local_generated(p, elem, true);
  274. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  275. // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  276. }
  277. if (t->Struct.soa_kind == StructSoa_Fixed) {
  278. for_array(i, t->Struct.fields) {
  279. Entity *field = t->Struct.fields[i];
  280. Type *base_type = field->type;
  281. GB_ASSERT(base_type->kind == Type_Array);
  282. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  283. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  284. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  285. lbValue src = lb_emit_load(p, src_ptr);
  286. lb_emit_store(p, dst, src);
  287. }
  288. } else {
  289. isize field_count = t->Struct.fields.count;
  290. if (t->Struct.soa_kind == StructSoa_Slice) {
  291. field_count -= 1;
  292. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  293. field_count -= 3;
  294. }
  295. for (isize i = 0; i < field_count; i++) {
  296. Entity *field = t->Struct.fields[i];
  297. Type *base_type = field->type;
  298. GB_ASSERT(base_type->kind == Type_Pointer);
  299. Type *elem = base_type->Pointer.elem;
  300. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  301. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  302. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  303. lbValue src = lb_emit_load(p, src_ptr);
  304. src = lb_emit_load(p, src);
  305. lb_emit_store(p, dst, src);
  306. }
  307. }
  308. return lb_addr_load(p, res);
  309. }
  310. if (is_type_proc(addr.addr.type)) {
  311. return addr.addr;
  312. }
  313. return lb_emit_load(p, addr.addr);
  314. }
  315. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  316. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  317. }
  318. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  319. Type *t = u.type;
  320. GB_ASSERT_MSG(is_type_pointer(t) &&
  321. is_type_union(type_deref(t)), "%s", type_to_string(t));
  322. Type *ut = type_deref(t);
  323. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  324. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  325. GB_ASSERT(type_size_of(ut) > 0);
  326. Type *tag_type = union_tag_type(ut);
  327. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  328. unsigned element_count = LLVMCountStructElementTypes(uvt);
  329. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  330. lbValue tag_ptr = {};
  331. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  332. tag_ptr.type = alloc_type_pointer(tag_type);
  333. return tag_ptr;
  334. }
  335. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  336. gbAllocator a = heap_allocator();
  337. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  338. lb_emit_store(p, underlying, variant);
  339. Type *t = type_deref(parent.type);
  340. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  341. // No tag needed!
  342. } else {
  343. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  344. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  345. }
  346. }
  347. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  348. unsigned field_count = LLVMCountStructElementTypes(src);
  349. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  350. LLVMGetStructElementTypes(src, fields);
  351. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  352. gb_free(heap_allocator(), fields);
  353. }
  354. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  355. switch (alignment) {
  356. case 1:
  357. return LLVMArrayType(lb_type(m, t_u8), 0);
  358. case 2:
  359. return LLVMArrayType(lb_type(m, t_u16), 0);
  360. case 4:
  361. return LLVMArrayType(lb_type(m, t_u32), 0);
  362. case 8:
  363. return LLVMArrayType(lb_type(m, t_u64), 0);
  364. case 16:
  365. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  366. default:
  367. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  368. break;
  369. }
  370. return nullptr;
  371. }
  372. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  373. if (!elem_type_can_be_constant(elem_type)) {
  374. return false;
  375. }
  376. if (elem->kind == Ast_FieldValue) {
  377. elem = elem->FieldValue.value;
  378. }
  379. TypeAndValue tav = type_and_value_of_expr(elem);
  380. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  381. return tav.value.kind != ExactValue_Invalid;
  382. }
  383. String lb_mangle_name(lbModule *m, Entity *e) {
  384. gbAllocator a = heap_allocator();
  385. String name = e->token.string;
  386. AstPackage *pkg = e->pkg;
  387. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  388. String pkgn = pkg->name;
  389. GB_ASSERT(!rune_is_digit(pkgn[0]));
  390. isize max_len = pkgn.len + 1 + name.len + 1;
  391. bool require_suffix_id = is_type_polymorphic(e->type, true);
  392. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  393. require_suffix_id = true;
  394. } else {
  395. require_suffix_id = true;
  396. }
  397. if (require_suffix_id) {
  398. max_len += 21;
  399. }
  400. char *new_name = gb_alloc_array(a, char, max_len);
  401. isize new_name_len = gb_snprintf(
  402. new_name, max_len,
  403. "%.*s.%.*s", LIT(pkgn), LIT(name)
  404. );
  405. if (require_suffix_id) {
  406. char *str = new_name + new_name_len-1;
  407. isize len = max_len-new_name_len;
  408. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  409. new_name_len += extra-1;
  410. }
  411. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  412. return mangled_name;
  413. }
  414. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  415. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  416. // and as a result, the declaration does not have time to determine what it should be
  417. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  418. if (e->TypeName.ir_mangled_name.len != 0) {
  419. return e->TypeName.ir_mangled_name;
  420. }
  421. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  422. if (p == nullptr) {
  423. Entity *proc = nullptr;
  424. if (e->parent_proc_decl != nullptr) {
  425. proc = e->parent_proc_decl->entity;
  426. } else {
  427. Scope *scope = e->scope;
  428. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  429. scope = scope->parent;
  430. }
  431. GB_ASSERT(scope != nullptr);
  432. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  433. proc = scope->procedure_entity;
  434. }
  435. GB_ASSERT(proc->kind == Entity_Procedure);
  436. GB_ASSERT(proc->code_gen_procedure != nullptr);
  437. p = proc->code_gen_procedure;
  438. }
  439. // NOTE(bill): Generate a new name
  440. // parent_proc.name-guid
  441. String ts_name = e->token.string;
  442. lbModule *m = p->module;
  443. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  444. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  445. u32 guid = ++p->module->nested_type_name_guid;
  446. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  447. String name = make_string(cast(u8 *)name_text, name_len-1);
  448. e->TypeName.ir_mangled_name = name;
  449. return name;
  450. }
  451. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  452. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  453. return e->TypeName.ir_mangled_name;
  454. }
  455. GB_ASSERT(e != nullptr);
  456. if (e->pkg == nullptr) {
  457. return e->token.string;
  458. }
  459. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  460. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  461. }
  462. String name = {};
  463. bool no_name_mangle = false;
  464. if (e->kind == Entity_Variable) {
  465. bool is_foreign = e->Variable.is_foreign;
  466. bool is_export = e->Variable.is_export;
  467. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  468. if (e->Variable.link_name.len > 0) {
  469. return e->Variable.link_name;
  470. }
  471. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  472. return e->Procedure.link_name;
  473. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  474. no_name_mangle = true;
  475. }
  476. if (!no_name_mangle) {
  477. name = lb_mangle_name(m, e);
  478. }
  479. if (name.len == 0) {
  480. name = e->token.string;
  481. }
  482. if (e->kind == Entity_TypeName) {
  483. if ((e->scope->flags & ScopeFlag_File) == 0) {
  484. gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e);
  485. }
  486. e->TypeName.ir_mangled_name = name;
  487. } else if (e->kind == Entity_Procedure) {
  488. e->Procedure.link_name = name;
  489. }
  490. return name;
  491. }
  492. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  493. Type *original_type = type;
  494. LLVMContextRef ctx = m->ctx;
  495. i64 size = type_size_of(type); // Check size
  496. GB_ASSERT(type != t_invalid);
  497. switch (type->kind) {
  498. case Type_Basic:
  499. switch (type->Basic.kind) {
  500. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  501. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  502. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  503. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  504. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  505. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  506. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  507. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  508. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  509. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  510. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  511. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  512. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  513. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  514. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  515. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  516. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  517. // Basic_f16,
  518. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  519. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  520. // Basic_complex32,
  521. case Basic_complex64:
  522. {
  523. char const *name = "..complex64";
  524. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  525. if (type != nullptr) {
  526. return type;
  527. }
  528. type = LLVMStructCreateNamed(ctx, name);
  529. LLVMTypeRef fields[2] = {
  530. lb_type(m, t_f32),
  531. lb_type(m, t_f32),
  532. };
  533. LLVMStructSetBody(type, fields, 2, false);
  534. return type;
  535. }
  536. case Basic_complex128:
  537. {
  538. char const *name = "..complex128";
  539. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  540. if (type != nullptr) {
  541. return type;
  542. }
  543. type = LLVMStructCreateNamed(ctx, name);
  544. LLVMTypeRef fields[2] = {
  545. lb_type(m, t_f64),
  546. lb_type(m, t_f64),
  547. };
  548. LLVMStructSetBody(type, fields, 2, false);
  549. return type;
  550. }
  551. case Basic_quaternion128:
  552. {
  553. char const *name = "..quaternion128";
  554. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  555. if (type != nullptr) {
  556. return type;
  557. }
  558. type = LLVMStructCreateNamed(ctx, name);
  559. LLVMTypeRef fields[4] = {
  560. lb_type(m, t_f32),
  561. lb_type(m, t_f32),
  562. lb_type(m, t_f32),
  563. lb_type(m, t_f32),
  564. };
  565. LLVMStructSetBody(type, fields, 4, false);
  566. return type;
  567. }
  568. case Basic_quaternion256:
  569. {
  570. char const *name = "..quaternion256";
  571. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  572. if (type != nullptr) {
  573. return type;
  574. }
  575. type = LLVMStructCreateNamed(ctx, name);
  576. LLVMTypeRef fields[4] = {
  577. lb_type(m, t_f64),
  578. lb_type(m, t_f64),
  579. lb_type(m, t_f64),
  580. lb_type(m, t_f64),
  581. };
  582. LLVMStructSetBody(type, fields, 4, false);
  583. return type;
  584. }
  585. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  586. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  587. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  588. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  589. case Basic_string:
  590. {
  591. char const *name = "..string";
  592. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  593. if (type != nullptr) {
  594. return type;
  595. }
  596. type = LLVMStructCreateNamed(ctx, name);
  597. LLVMTypeRef fields[2] = {
  598. LLVMPointerType(lb_type(m, t_u8), 0),
  599. lb_type(m, t_int),
  600. };
  601. LLVMStructSetBody(type, fields, 2, false);
  602. return type;
  603. }
  604. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  605. case Basic_any:
  606. {
  607. char const *name = "..any";
  608. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  609. if (type != nullptr) {
  610. return type;
  611. }
  612. type = LLVMStructCreateNamed(ctx, name);
  613. LLVMTypeRef fields[2] = {
  614. lb_type(m, t_rawptr),
  615. lb_type(m, t_typeid),
  616. };
  617. LLVMStructSetBody(type, fields, 2, false);
  618. return type;
  619. }
  620. case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size);
  621. // Endian Specific Types
  622. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  623. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  624. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  625. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  626. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  627. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  628. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  629. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  630. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  631. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  632. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  633. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  634. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  635. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  636. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  637. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  638. // Untyped types
  639. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  640. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  641. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  642. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  643. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  644. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  645. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  646. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  647. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  648. }
  649. break;
  650. case Type_Named:
  651. {
  652. Type *base = base_type(type->Named.base);
  653. switch (base->kind) {
  654. case Type_Basic:
  655. return lb_type(m, base);
  656. case Type_Named:
  657. case Type_Generic:
  658. case Type_BitFieldValue:
  659. GB_PANIC("INVALID TYPE");
  660. break;
  661. case Type_Pointer:
  662. case Type_Opaque:
  663. case Type_Array:
  664. case Type_EnumeratedArray:
  665. case Type_Slice:
  666. case Type_DynamicArray:
  667. case Type_Map:
  668. case Type_Enum:
  669. case Type_BitSet:
  670. case Type_SimdVector:
  671. return lb_type(m, base);
  672. // TODO(bill): Deal with this correctly. Can this be named?
  673. case Type_Proc:
  674. return lb_type(m, base);
  675. case Type_Tuple:
  676. return lb_type(m, base);
  677. }
  678. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  679. if (found) {
  680. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  681. if (kind == LLVMStructTypeKind) {
  682. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  683. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  684. if (llvm_type != nullptr) {
  685. return llvm_type;
  686. }
  687. llvm_type = LLVMStructCreateNamed(ctx, name);
  688. map_set(&m->types, hash_type(type), llvm_type);
  689. lb_clone_struct_type(llvm_type, *found);
  690. return llvm_type;
  691. }
  692. }
  693. switch (base->kind) {
  694. case Type_Struct:
  695. case Type_Union:
  696. case Type_BitField:
  697. {
  698. char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  699. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  700. if (llvm_type != nullptr) {
  701. return llvm_type;
  702. }
  703. llvm_type = LLVMStructCreateNamed(ctx, name);
  704. map_set(&m->types, hash_type(type), llvm_type);
  705. lb_clone_struct_type(llvm_type, lb_type(m, base));
  706. return llvm_type;
  707. }
  708. }
  709. return lb_type(m, base);
  710. }
  711. case Type_Pointer:
  712. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  713. case Type_Opaque:
  714. return lb_type(m, base_type(type));
  715. case Type_Array:
  716. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  717. case Type_EnumeratedArray:
  718. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  719. case Type_Slice:
  720. {
  721. LLVMTypeRef fields[2] = {
  722. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  723. lb_type(m, t_int), // len
  724. };
  725. return LLVMStructTypeInContext(ctx, fields, 2, false);
  726. }
  727. break;
  728. case Type_DynamicArray:
  729. {
  730. LLVMTypeRef fields[4] = {
  731. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  732. lb_type(m, t_int), // len
  733. lb_type(m, t_int), // cap
  734. lb_type(m, t_allocator), // allocator
  735. };
  736. return LLVMStructTypeInContext(ctx, fields, 4, false);
  737. }
  738. break;
  739. case Type_Map:
  740. return lb_type(m, type->Map.internal_type);
  741. case Type_Struct:
  742. {
  743. if (type->Struct.is_raw_union) {
  744. unsigned field_count = 2;
  745. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  746. i64 alignment = type_align_of(type);
  747. unsigned size_of_union = cast(unsigned)type_size_of(type);
  748. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  749. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  750. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  751. }
  752. isize offset = 0;
  753. if (type->Struct.custom_align > 0) {
  754. offset = 1;
  755. }
  756. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  757. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  758. GB_ASSERT(fields != nullptr);
  759. defer (gb_free(heap_allocator(), fields));
  760. for_array(i, type->Struct.fields) {
  761. Entity *field = type->Struct.fields[i];
  762. fields[i+offset] = lb_type(m, field->type);
  763. }
  764. if (type->Struct.custom_align > 0) {
  765. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  766. }
  767. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  768. }
  769. break;
  770. case Type_Union:
  771. if (type->Union.variants.count == 0) {
  772. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  773. } else {
  774. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  775. // LLVM takes the first element's alignment as the entire alignment (like C)
  776. i64 align = type_align_of(type);
  777. i64 size = type_size_of(type);
  778. if (is_type_union_maybe_pointer_original_alignment(type)) {
  779. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  780. return LLVMStructTypeInContext(ctx, fields, 1, false);
  781. }
  782. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  783. LLVMTypeRef fields[3] = {};
  784. unsigned field_count = 1;
  785. fields[0] = lb_alignment_prefix_type_hack(m, align);
  786. if (is_type_union_maybe_pointer(type)) {
  787. field_count += 1;
  788. fields[1] = lb_type(m, type->Union.variants[0]);
  789. } else {
  790. field_count += 2;
  791. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  792. fields[2] = lb_type(m, union_tag_type(type));
  793. }
  794. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  795. }
  796. break;
  797. case Type_Enum:
  798. return lb_type(m, base_enum_type(type));
  799. case Type_Tuple:
  800. if (type->Tuple.variables.count == 1) {
  801. return lb_type(m, type->Tuple.variables[0]->type);
  802. } else {
  803. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  804. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  805. defer (gb_free(heap_allocator(), fields));
  806. for_array(i, type->Tuple.variables) {
  807. Entity *field = type->Tuple.variables[i];
  808. fields[i] = lb_type(m, field->type);
  809. }
  810. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  811. }
  812. case Type_Proc:
  813. {
  814. set_procedure_abi_types(heap_allocator(), type);
  815. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  816. isize offset = 0;
  817. if (type->Proc.return_by_pointer) {
  818. offset = 1;
  819. } else if (type->Proc.abi_compat_result_type != nullptr) {
  820. return_type = lb_type(m, type->Proc.abi_compat_result_type);
  821. }
  822. isize extra_param_count = offset;
  823. if (type->Proc.calling_convention == ProcCC_Odin) {
  824. extra_param_count += 1;
  825. }
  826. isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  827. LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  828. defer (gb_free(heap_allocator(), param_types));
  829. isize param_index = offset;
  830. for_array(i, type->Proc.abi_compat_params) {
  831. Type *param = type->Proc.abi_compat_params[i];
  832. if (param == nullptr) {
  833. continue;
  834. }
  835. param_types[param_index++] = lb_type(m, param);
  836. }
  837. if (type->Proc.return_by_pointer) {
  838. param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  839. }
  840. if (type->Proc.calling_convention == ProcCC_Odin) {
  841. param_types[param_index++] = lb_type(m, t_context_ptr);
  842. }
  843. LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  844. return LLVMPointerType(t, 0);
  845. }
  846. break;
  847. case Type_BitFieldValue:
  848. return LLVMIntType(type->BitFieldValue.bits);
  849. case Type_BitField:
  850. {
  851. LLVMTypeRef internal_type = nullptr;
  852. {
  853. GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  854. unsigned field_count = cast(unsigned)type->BitField.fields.count;
  855. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  856. defer (gb_free(heap_allocator(), fields));
  857. for_array(i, type->BitField.sizes) {
  858. u32 size = type->BitField.sizes[i];
  859. fields[i] = LLVMIntType(size);
  860. }
  861. internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  862. }
  863. unsigned field_count = 2;
  864. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  865. i64 alignment = 1;
  866. if (type->BitField.custom_align > 0) {
  867. alignment = type->BitField.custom_align;
  868. }
  869. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  870. fields[1] = internal_type;
  871. return LLVMStructTypeInContext(ctx, fields, field_count, true);
  872. }
  873. break;
  874. case Type_BitSet:
  875. return LLVMIntType(8*cast(unsigned)type_size_of(type));
  876. case Type_SimdVector:
  877. if (type->SimdVector.is_x86_mmx) {
  878. return LLVMX86MMXTypeInContext(ctx);
  879. }
  880. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  881. }
  882. GB_PANIC("Invalid type %s", type_to_string(type));
  883. return LLVMInt32TypeInContext(ctx);
  884. }
  885. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  886. type = default_type(type);
  887. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  888. if (found) {
  889. return *found;
  890. }
  891. LLVMTypeRef llvm_type = lb_type_internal(m, type);
  892. map_set(&m->types, hash_type(type), llvm_type);
  893. return llvm_type;
  894. }
  895. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  896. if (e != nullptr) {
  897. map_set(&m->values, hash_entity(e), val);
  898. }
  899. }
  900. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  901. if (name.len > 0) {
  902. map_set(&m->members, hash_string(name), val);
  903. }
  904. }
  905. void lb_add_member(lbModule *m, HashKey const &key, lbValue val) {
  906. map_set(&m->members, key, val);
  907. }
  908. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  909. if (p->entity != nullptr) {
  910. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  911. }
  912. map_set(&m->procedures, hash_string(p->name), p);
  913. }
  914. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  915. lbAddr res = lb_add_local_generated(p, t_string, false);
  916. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  917. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  918. return lb_addr_load(p, res);
  919. }
  920. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  921. unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name));
  922. return LLVMCreateEnumAttribute(ctx, kind, value);
  923. }
  924. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  925. LLVMContextRef ctx = LLVMGetModuleContext(p->module->mod);
  926. // LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, lb_create_enum_attribute(ctx, name, value));
  927. }
  928. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  929. lb_add_proc_attribute_at_index(p, index, name, true);
  930. }
  931. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  932. GB_ASSERT(entity != nullptr);
  933. String link_name = lb_get_entity_name(m, entity);
  934. {
  935. HashKey key = hash_string(link_name);
  936. lbValue *found = map_get(&m->members, key);
  937. if (found) {
  938. lb_add_entity(m, entity, *found);
  939. lbProcedure **p_found = map_get(&m->procedures, key);
  940. GB_ASSERT(p_found != nullptr);
  941. return *p_found;
  942. }
  943. }
  944. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  945. p->module = m;
  946. entity->code_gen_module = m;
  947. entity->code_gen_procedure = p;
  948. p->entity = entity;
  949. p->name = link_name;
  950. DeclInfo *decl = entity->decl_info;
  951. ast_node(pl, ProcLit, decl->proc_lit);
  952. Type *pt = base_type(entity->type);
  953. GB_ASSERT(pt->kind == Type_Proc);
  954. set_procedure_abi_types(heap_allocator(), entity->type);
  955. p->type = entity->type;
  956. p->type_expr = decl->type_expr;
  957. p->body = pl->body;
  958. p->tags = pt->Proc.tags;
  959. p->inlining = ProcInlining_none;
  960. p->is_foreign = entity->Procedure.is_foreign;
  961. p->is_export = entity->Procedure.is_export;
  962. p->is_entry_point = false;
  963. gbAllocator a = heap_allocator();
  964. p->children.allocator = a;
  965. p->params.allocator = a;
  966. p->defer_stmts.allocator = a;
  967. p->blocks.allocator = a;
  968. p->branch_blocks.allocator = a;
  969. p->context_stack.allocator = a;
  970. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  971. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  972. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  973. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  974. LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]);
  975. lbValue proc_value = {p->value, p->type};
  976. lb_add_entity(m, entity, proc_value);
  977. lb_add_member(m, p->name, proc_value);
  978. lb_add_procedure_value(m, p);
  979. // NOTE(bill): offset==0 is the return value
  980. isize offset = 1;
  981. if (pt->Proc.return_by_pointer) {
  982. lb_add_proc_attribute_at_index(p, 1, "sret");
  983. lb_add_proc_attribute_at_index(p, 1, "noalias");
  984. offset = 2;
  985. }
  986. isize parameter_index = 0;
  987. if (pt->Proc.param_count) {
  988. TypeTuple *params = &pt->Proc.params->Tuple;
  989. for (isize i = 0; i < pt->Proc.param_count; i++) {
  990. Entity *e = params->variables[i];
  991. Type *original_type = e->type;
  992. Type *abi_type = pt->Proc.abi_compat_params[i];
  993. if (e->kind != Entity_Variable) continue;
  994. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  995. continue;
  996. }
  997. if (is_type_tuple(abi_type)) {
  998. for_array(j, abi_type->Tuple.variables) {
  999. Type *tft = abi_type->Tuple.variables[j]->type;
  1000. if (e->flags&EntityFlag_NoAlias) {
  1001. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1002. }
  1003. }
  1004. parameter_index += abi_type->Tuple.variables.count;
  1005. } else {
  1006. if (e->flags&EntityFlag_NoAlias) {
  1007. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1008. }
  1009. parameter_index += 1;
  1010. }
  1011. }
  1012. }
  1013. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1014. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1015. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1016. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1017. }
  1018. if (entity->Procedure.is_foreign) {
  1019. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1020. }
  1021. { // Debug Information
  1022. unsigned line = cast(unsigned)entity->token.pos.line;
  1023. LLVMMetadataRef file = nullptr;
  1024. if (entity->file != nullptr) {
  1025. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1026. }
  1027. LLVMMetadataRef scope = nullptr;
  1028. LLVMMetadataRef type = nullptr;
  1029. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1030. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1031. cast(char const *)entity->token.string.text, entity->token.string.len,
  1032. cast(char const *)p->name.text, p->name.len,
  1033. file, line, type,
  1034. true, p->body == nullptr,
  1035. line, LLVMDIFlagZero, false
  1036. );
  1037. GB_ASSERT(res != nullptr);
  1038. map_set(&m->debug_values, hash_pointer(p), res);
  1039. }
  1040. return p;
  1041. }
  1042. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1043. {
  1044. HashKey key = hash_string(link_name);
  1045. lbValue *found = map_get(&m->members, key);
  1046. GB_ASSERT(found == nullptr);
  1047. }
  1048. lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure);
  1049. p->module = m;
  1050. p->name = link_name;
  1051. p->type = type;
  1052. p->type_expr = nullptr;
  1053. p->body = nullptr;
  1054. p->tags = 0;
  1055. p->inlining = ProcInlining_none;
  1056. p->is_foreign = false;
  1057. p->is_export = false;
  1058. p->is_entry_point = false;
  1059. gbAllocator a = heap_allocator();
  1060. p->children.allocator = a;
  1061. p->params.allocator = a;
  1062. p->defer_stmts.allocator = a;
  1063. p->blocks.allocator = a;
  1064. p->branch_blocks.allocator = a;
  1065. p->context_stack.allocator = a;
  1066. char *c_link_name = alloc_cstring(heap_allocator(), p->name);
  1067. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1068. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1069. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1070. Type *pt = p->type;
  1071. LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]);
  1072. lbValue proc_value = {p->value, p->type};
  1073. lb_add_member(m, p->name, proc_value);
  1074. lb_add_procedure_value(m, p);
  1075. // NOTE(bill): offset==0 is the return value
  1076. isize offset = 1;
  1077. if (pt->Proc.return_by_pointer) {
  1078. lb_add_proc_attribute_at_index(p, 1, "sret");
  1079. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1080. offset = 2;
  1081. }
  1082. isize parameter_index = 0;
  1083. if (pt->Proc.param_count) {
  1084. TypeTuple *params = &pt->Proc.params->Tuple;
  1085. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1086. Entity *e = params->variables[i];
  1087. Type *original_type = e->type;
  1088. Type *abi_type = pt->Proc.abi_compat_params[i];
  1089. if (e->kind != Entity_Variable) continue;
  1090. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1091. continue;
  1092. }
  1093. if (is_type_tuple(abi_type)) {
  1094. for_array(j, abi_type->Tuple.variables) {
  1095. Type *tft = abi_type->Tuple.variables[j]->type;
  1096. if (e->flags&EntityFlag_NoAlias) {
  1097. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1098. }
  1099. }
  1100. parameter_index += abi_type->Tuple.variables.count;
  1101. } else {
  1102. if (e->flags&EntityFlag_NoAlias) {
  1103. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1104. }
  1105. parameter_index += 1;
  1106. }
  1107. }
  1108. }
  1109. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1110. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1111. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1112. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1113. }
  1114. return p;
  1115. }
  1116. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  1117. lbParamPasskind kind = lbParamPass_Value;
  1118. if (e != nullptr && abi_type != e->type) {
  1119. if (is_type_pointer(abi_type)) {
  1120. GB_ASSERT(e->kind == Entity_Variable);
  1121. kind = lbParamPass_Pointer;
  1122. if (e->flags&EntityFlag_Value) {
  1123. kind = lbParamPass_ConstRef;
  1124. }
  1125. } else if (is_type_integer(abi_type)) {
  1126. kind = lbParamPass_Integer;
  1127. } else if (abi_type == t_llvm_bool) {
  1128. kind = lbParamPass_Value;
  1129. } else if (is_type_simd_vector(abi_type)) {
  1130. kind = lbParamPass_BitCast;
  1131. } else if (is_type_float(abi_type)) {
  1132. kind = lbParamPass_BitCast;
  1133. } else if (is_type_tuple(abi_type)) {
  1134. kind = lbParamPass_Tuple;
  1135. } else {
  1136. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  1137. }
  1138. }
  1139. if (kind_) *kind_ = kind;
  1140. lbValue res = {};
  1141. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  1142. res.type = abi_type;
  1143. return res;
  1144. }
  1145. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1146. lbParamPasskind kind = lbParamPass_Value;
  1147. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  1148. array_add(&p->params, v);
  1149. lbValue res = {};
  1150. switch (kind) {
  1151. case lbParamPass_Value: {
  1152. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1153. lbValue x = v;
  1154. if (abi_type == t_llvm_bool) {
  1155. x = lb_emit_conv(p, x, t_bool);
  1156. }
  1157. lb_addr_store(p, l, x);
  1158. return x;
  1159. }
  1160. case lbParamPass_Pointer:
  1161. lb_add_entity(p->module, e, v);
  1162. return lb_emit_load(p, v);
  1163. case lbParamPass_Integer: {
  1164. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1165. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  1166. lb_emit_store(p, iptr, v);
  1167. return lb_addr_load(p, l);
  1168. }
  1169. case lbParamPass_ConstRef:
  1170. lb_add_entity(p->module, e, v);
  1171. return lb_emit_load(p, v);
  1172. case lbParamPass_BitCast: {
  1173. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1174. lbValue x = lb_emit_transmute(p, v, e->type);
  1175. lb_addr_store(p, l, x);
  1176. return x;
  1177. }
  1178. case lbParamPass_Tuple: {
  1179. lbAddr l = lb_add_local(p, e->type, e, true, index);
  1180. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1181. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  1182. if (abi_type->Tuple.variables.count > 0) {
  1183. array_pop(&p->params);
  1184. }
  1185. for_array(i, abi_type->Tuple.variables) {
  1186. Type *t = abi_type->Tuple.variables[i]->type;
  1187. lbParamPasskind elem_kind = lbParamPass_Value;
  1188. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  1189. array_add(&p->params, elem);
  1190. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  1191. lb_emit_store(p, dst, elem);
  1192. }
  1193. return lb_addr_load(p, l);
  1194. }
  1195. }
  1196. GB_PANIC("Unreachable");
  1197. return {};
  1198. }
  1199. void lb_start_block(lbProcedure *p, lbBlock *b) {
  1200. GB_ASSERT(b != nullptr);
  1201. if (!b->appended) {
  1202. b->appended = true;
  1203. LLVMAppendExistingBasicBlock(p->value, b->block);
  1204. }
  1205. LLVMPositionBuilderAtEnd(p->builder, b->block);
  1206. p->curr_block = b;
  1207. }
  1208. void lb_begin_procedure_body(lbProcedure *p) {
  1209. DeclInfo *decl = decl_info_of_entity(p->entity);
  1210. if (decl != nullptr) {
  1211. for_array(i, decl->labels) {
  1212. BlockLabel bl = decl->labels[i];
  1213. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  1214. array_add(&p->branch_blocks, bb);
  1215. }
  1216. }
  1217. p->builder = LLVMCreateBuilder();
  1218. p->decl_block = lb_create_block(p, "decls", true);
  1219. p->entry_block = lb_create_block(p, "entry", true);
  1220. lb_start_block(p, p->entry_block);
  1221. GB_ASSERT(p->type != nullptr);
  1222. i32 parameter_index = 0;
  1223. if (p->type->Proc.return_by_pointer) {
  1224. // NOTE(bill): this must be parameter 0
  1225. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  1226. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  1227. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  1228. lbValue return_ptr_value = {};
  1229. return_ptr_value.value = LLVMGetParam(p->value, 0);
  1230. return_ptr_value.type = alloc_type_pointer(p->type->Proc.abi_compat_result_type);
  1231. p->return_ptr = lb_addr(return_ptr_value);
  1232. lb_add_entity(p->module, e, return_ptr_value);
  1233. parameter_index += 1;
  1234. }
  1235. if (p->type->Proc.params != nullptr) {
  1236. TypeTuple *params = &p->type->Proc.params->Tuple;
  1237. if (p->type_expr != nullptr) {
  1238. ast_node(pt, ProcType, p->type_expr);
  1239. isize param_index = 0;
  1240. isize q_index = 0;
  1241. for_array(i, params->variables) {
  1242. ast_node(fl, FieldList, pt->params);
  1243. GB_ASSERT(fl->list.count > 0);
  1244. GB_ASSERT(fl->list[0]->kind == Ast_Field);
  1245. if (q_index == fl->list[param_index]->Field.names.count) {
  1246. q_index = 0;
  1247. param_index++;
  1248. }
  1249. ast_node(field, Field, fl->list[param_index]);
  1250. Ast *name = field->names[q_index++];
  1251. Entity *e = params->variables[i];
  1252. if (e->kind != Entity_Variable) {
  1253. continue;
  1254. }
  1255. Type *abi_type = p->type->Proc.abi_compat_params[i];
  1256. if (e->token.string != "") {
  1257. lb_add_param(p, e, name, abi_type, parameter_index);
  1258. }
  1259. if (is_type_tuple(abi_type)) {
  1260. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  1261. } else {
  1262. parameter_index += 1;
  1263. }
  1264. }
  1265. } else {
  1266. auto abi_types = p->type->Proc.abi_compat_params;
  1267. for_array(i, params->variables) {
  1268. Entity *e = params->variables[i];
  1269. if (e->kind != Entity_Variable) {
  1270. continue;
  1271. }
  1272. Type *abi_type = e->type;
  1273. if (abi_types.count > 0) {
  1274. abi_type = abi_types[i];
  1275. }
  1276. if (e->token.string != "") {
  1277. lb_add_param(p, e, nullptr, abi_type, parameter_index);
  1278. }
  1279. if (is_type_tuple(abi_type)) {
  1280. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  1281. } else {
  1282. parameter_index += 1;
  1283. }
  1284. }
  1285. }
  1286. }
  1287. if (p->type->Proc.has_named_results) {
  1288. GB_ASSERT(p->type->Proc.result_count > 0);
  1289. TypeTuple *results = &p->type->Proc.results->Tuple;
  1290. LLVMValueRef return_ptr = LLVMGetParam(p->value, 0);
  1291. isize result_index = 0;
  1292. for_array(i, results->variables) {
  1293. Entity *e = results->variables[i];
  1294. if (e->kind != Entity_Variable) {
  1295. continue;
  1296. }
  1297. if (e->token.string != "") {
  1298. GB_ASSERT(!is_blank_ident(e->token));
  1299. lbAddr res = lb_add_local(p, e->type, e);
  1300. lbValue c = {};
  1301. switch (e->Variable.param_value.kind) {
  1302. case ParameterValue_Constant:
  1303. c = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  1304. break;
  1305. case ParameterValue_Nil:
  1306. c = lb_const_nil(p->module, e->type);
  1307. break;
  1308. case ParameterValue_Location:
  1309. GB_PANIC("ParameterValue_Location");
  1310. break;
  1311. }
  1312. if (c.value != nullptr) {
  1313. lb_addr_store(p, res, c);
  1314. }
  1315. }
  1316. result_index += 1;
  1317. }
  1318. }
  1319. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  1320. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  1321. e->flags |= EntityFlag_NoAlias;
  1322. lbValue param = {};
  1323. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  1324. param.type = e->type;
  1325. lb_add_entity(p->module, e, param);
  1326. lbAddr ctx_addr = {};
  1327. ctx_addr.kind = lbAddr_Context;
  1328. ctx_addr.addr = param;
  1329. lbContextData ctx = {ctx_addr, p->scope_index};
  1330. array_add(&p->context_stack, ctx);
  1331. }
  1332. lb_start_block(p, p->entry_block);
  1333. }
  1334. void lb_end_procedure_body(lbProcedure *p) {
  1335. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  1336. LLVMBuildBr(p->builder, p->entry_block->block);
  1337. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  1338. if (p->type->Proc.result_count == 0) {
  1339. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  1340. if (!LLVMIsAReturnInst(instr)) {
  1341. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1342. LLVMBuildRetVoid(p->builder);
  1343. }
  1344. } else {
  1345. if (p->curr_block->preds.count == 0) {
  1346. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  1347. if (instr == nullptr) {
  1348. // NOTE(bill): Remove dead trailing block
  1349. LLVMDeleteBasicBlock(p->curr_block->block);
  1350. }
  1351. }
  1352. }
  1353. p->curr_block = nullptr;
  1354. }
  1355. void lb_end_procedure(lbProcedure *p) {
  1356. LLVMDisposeBuilder(p->builder);
  1357. }
  1358. void lb_add_edge(lbBlock *from, lbBlock *to) {
  1359. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  1360. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  1361. array_add(&from->succs, to);
  1362. array_add(&to->preds, from);
  1363. }
  1364. }
  1365. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  1366. lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock);
  1367. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  1368. b->appended = false;
  1369. if (append) {
  1370. b->appended = true;
  1371. LLVMAppendExistingBasicBlock(p->value, b->block);
  1372. }
  1373. b->scope = p->curr_scope;
  1374. b->scope_index = p->scope_index;
  1375. b->preds.allocator = heap_allocator();
  1376. b->succs.allocator = heap_allocator();
  1377. array_add(&p->blocks, b);
  1378. return b;
  1379. }
  1380. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  1381. if (p->curr_block == nullptr) {
  1382. return;
  1383. }
  1384. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1385. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1386. return;
  1387. }
  1388. lb_add_edge(p->curr_block, target_block);
  1389. LLVMBuildBr(p->builder, target_block->block);
  1390. p->curr_block = nullptr;
  1391. }
  1392. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  1393. lbBlock *b = p->curr_block;
  1394. if (b == nullptr) {
  1395. return;
  1396. }
  1397. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1398. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1399. return;
  1400. }
  1401. lb_add_edge(b, true_block);
  1402. lb_add_edge(b, false_block);
  1403. LLVMValueRef cv = cond.value;
  1404. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  1405. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  1406. }
  1407. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  1408. switch (cond->kind) {
  1409. case_ast_node(pe, ParenExpr, cond);
  1410. return lb_build_cond(p, pe->expr, true_block, false_block);
  1411. case_end;
  1412. case_ast_node(ue, UnaryExpr, cond);
  1413. if (ue->op.kind == Token_Not) {
  1414. return lb_build_cond(p, ue->expr, false_block, true_block);
  1415. }
  1416. case_end;
  1417. case_ast_node(be, BinaryExpr, cond);
  1418. if (be->op.kind == Token_CmpAnd) {
  1419. lbBlock *block = lb_create_block(p, "cmp.and");
  1420. lb_build_cond(p, be->left, block, false_block);
  1421. lb_start_block(p, block);
  1422. return lb_build_cond(p, be->right, true_block, false_block);
  1423. } else if (be->op.kind == Token_CmpOr) {
  1424. lbBlock *block = lb_create_block(p, "cmp.or");
  1425. lb_build_cond(p, be->left, true_block, block);
  1426. lb_start_block(p, block);
  1427. return lb_build_cond(p, be->right, true_block, false_block);
  1428. }
  1429. case_end;
  1430. }
  1431. lbValue v = lb_build_expr(p, cond);
  1432. // v = lb_emit_conv(p, v, t_bool);
  1433. v = lb_emit_conv(p, v, t_llvm_bool);
  1434. lb_emit_if(p, v, true_block, false_block);
  1435. return v;
  1436. }
  1437. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  1438. GB_ASSERT(p->decl_block != p->curr_block);
  1439. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  1440. char const *name = "";
  1441. if (e != nullptr) {
  1442. // name = alloc_cstring(heap_allocator(), e->token.string);
  1443. }
  1444. LLVMTypeRef llvm_type = lb_type(p->module, type);
  1445. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  1446. LLVMSetAlignment(ptr, 16); // TODO(bill): Make this configurable
  1447. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  1448. if (zero_init) {
  1449. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  1450. }
  1451. lbValue val = {};
  1452. val.value = ptr;
  1453. val.type = alloc_type_pointer(type);
  1454. if (e != nullptr) {
  1455. lb_add_entity(p->module, e, val);
  1456. }
  1457. return lb_addr(val);
  1458. }
  1459. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  1460. return lb_add_local(p, type, nullptr, zero_init);
  1461. }
  1462. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  1463. GB_ASSERT(pd->body != nullptr);
  1464. lbModule *m = p->module;
  1465. auto *min_dep_set = &m->info->minimum_dependency_set;
  1466. if (ptr_set_exists(min_dep_set, e) == false) {
  1467. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1468. return;
  1469. }
  1470. // NOTE(bill): Generate a new name
  1471. // parent.name-guid
  1472. String original_name = e->token.string;
  1473. String pd_name = original_name;
  1474. if (e->Procedure.link_name.len > 0) {
  1475. pd_name = e->Procedure.link_name;
  1476. }
  1477. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  1478. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  1479. i32 guid = cast(i32)p->children.count;
  1480. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  1481. String name = make_string(cast(u8 *)name_text, name_len-1);
  1482. set_procedure_abi_types(heap_allocator(), e->type);
  1483. e->Procedure.link_name = name;
  1484. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  1485. lbValue value = {};
  1486. value.value = nested_proc->value;
  1487. value.type = nested_proc->type;
  1488. lb_add_entity(m, e, value);
  1489. array_add(&p->children, nested_proc);
  1490. array_add(&m->procedures_to_generate, nested_proc);
  1491. }
  1492. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  1493. if (e == nullptr) {
  1494. return;
  1495. }
  1496. GB_ASSERT(e->kind == Entity_LibraryName);
  1497. GB_ASSERT(e->flags & EntityFlag_Used);
  1498. for_array(i, e->LibraryName.paths) {
  1499. String library_path = e->LibraryName.paths[i];
  1500. if (library_path.len == 0) {
  1501. continue;
  1502. }
  1503. bool ok = true;
  1504. for_array(path_index, m->foreign_library_paths) {
  1505. String path = m->foreign_library_paths[path_index];
  1506. #if defined(GB_SYSTEM_WINDOWS)
  1507. if (str_eq_ignore_case(path, library_path)) {
  1508. #else
  1509. if (str_eq(path, library_path)) {
  1510. #endif
  1511. ok = false;
  1512. break;
  1513. }
  1514. }
  1515. if (ok) {
  1516. array_add(&m->foreign_library_paths, library_path);
  1517. }
  1518. }
  1519. }
  1520. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  1521. if (vd == nullptr || vd->is_mutable) {
  1522. return;
  1523. }
  1524. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  1525. static i32 global_guid = 0;
  1526. for_array(i, vd->names) {
  1527. Ast *ident = vd->names[i];
  1528. GB_ASSERT(ident->kind == Ast_Ident);
  1529. Entity *e = entity_of_ident(ident);
  1530. GB_ASSERT(e != nullptr);
  1531. if (e->kind != Entity_TypeName) {
  1532. continue;
  1533. }
  1534. bool polymorphic_struct = false;
  1535. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1536. Type *bt = base_type(e->type);
  1537. if (bt->kind == Type_Struct) {
  1538. polymorphic_struct = bt->Struct.is_polymorphic;
  1539. }
  1540. }
  1541. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1542. continue;
  1543. }
  1544. if (e->TypeName.ir_mangled_name.len != 0) {
  1545. // NOTE(bill): Already set
  1546. continue;
  1547. }
  1548. lb_set_nested_type_name_ir_mangled_name(e, p);
  1549. }
  1550. for_array(i, vd->names) {
  1551. Ast *ident = vd->names[i];
  1552. GB_ASSERT(ident->kind == Ast_Ident);
  1553. Entity *e = entity_of_ident(ident);
  1554. GB_ASSERT(e != nullptr);
  1555. if (e->kind != Entity_Procedure) {
  1556. continue;
  1557. }
  1558. CheckerInfo *info = p->module->info;
  1559. DeclInfo *decl = decl_info_of_entity(e);
  1560. ast_node(pl, ProcLit, decl->proc_lit);
  1561. if (pl->body != nullptr) {
  1562. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  1563. if (found) {
  1564. auto procs = *found;
  1565. for_array(i, procs) {
  1566. Entity *e = procs[i];
  1567. if (!ptr_set_exists(min_dep_set, e)) {
  1568. continue;
  1569. }
  1570. DeclInfo *d = decl_info_of_entity(e);
  1571. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  1572. }
  1573. } else {
  1574. lb_build_nested_proc(p, pl, e);
  1575. }
  1576. } else {
  1577. // FFI - Foreign function interace
  1578. String original_name = e->token.string;
  1579. String name = original_name;
  1580. if (e->Procedure.is_foreign) {
  1581. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  1582. }
  1583. if (e->Procedure.link_name.len > 0) {
  1584. name = e->Procedure.link_name;
  1585. }
  1586. HashKey key = hash_string(name);
  1587. lbValue *prev_value = map_get(&p->module->members, key);
  1588. if (prev_value != nullptr) {
  1589. // NOTE(bill): Don't do mutliple declarations in the IR
  1590. return;
  1591. }
  1592. set_procedure_abi_types(heap_allocator(), e->type);
  1593. e->Procedure.link_name = name;
  1594. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  1595. lbValue value = {};
  1596. value.value = nested_proc->value;
  1597. value.type = nested_proc->type;
  1598. array_add(&p->module->procedures_to_generate, nested_proc);
  1599. if (p != nullptr) {
  1600. array_add(&p->children, nested_proc);
  1601. } else {
  1602. map_set(&p->module->members, hash_string(name), value);
  1603. }
  1604. }
  1605. }
  1606. }
  1607. void lb_build_stmt_list(lbProcedure *p, Array<Ast *> const &stmts) {
  1608. for_array(i, stmts) {
  1609. Ast *stmt = stmts[i];
  1610. switch (stmt->kind) {
  1611. case_ast_node(vd, ValueDecl, stmt);
  1612. lb_build_constant_value_decl(p, vd);
  1613. case_end;
  1614. case_ast_node(fb, ForeignBlockDecl, stmt);
  1615. ast_node(block, BlockStmt, fb->body);
  1616. lb_build_stmt_list(p, block->stmts);
  1617. case_end;
  1618. }
  1619. }
  1620. for_array(i, stmts) {
  1621. lb_build_stmt(p, stmts[i]);
  1622. }
  1623. }
  1624. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  1625. GB_ASSERT(ident->kind == Ast_Ident);
  1626. Entity *e = entity_of_ident(ident);
  1627. GB_ASSERT(e->kind == Entity_Label);
  1628. for_array(i, p->branch_blocks) {
  1629. lbBranchBlocks *b = &p->branch_blocks[i];
  1630. if (b->label == e->Label.node) {
  1631. return *b;
  1632. }
  1633. }
  1634. GB_PANIC("Unreachable");
  1635. lbBranchBlocks empty = {};
  1636. return empty;
  1637. }
  1638. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  1639. lbTargetList *tl = gb_alloc_item(heap_allocator(), lbTargetList);
  1640. tl->prev = p->target_list;
  1641. tl->break_ = break_;
  1642. tl->continue_ = continue_;
  1643. tl->fallthrough_ = fallthrough_;
  1644. p->target_list = tl;
  1645. if (label != nullptr) { // Set label blocks
  1646. GB_ASSERT(label->kind == Ast_Label);
  1647. for_array(i, p->branch_blocks) {
  1648. lbBranchBlocks *b = &p->branch_blocks[i];
  1649. GB_ASSERT(b->label != nullptr && label != nullptr);
  1650. GB_ASSERT(b->label->kind == Ast_Label);
  1651. if (b->label == label) {
  1652. b->break_ = break_;
  1653. b->continue_ = continue_;
  1654. return tl;
  1655. }
  1656. }
  1657. GB_PANIC("Unreachable");
  1658. }
  1659. return tl;
  1660. }
  1661. void lb_pop_target_list(lbProcedure *p) {
  1662. p->target_list = p->target_list->prev;
  1663. }
  1664. void lb_open_scope(lbProcedure *p) {
  1665. p->scope_index += 1;
  1666. }
  1667. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  1668. lb_emit_defer_stmts(p, kind, block);
  1669. GB_ASSERT(p->scope_index > 0);
  1670. // NOTE(bill): Remove `context`s made in that scope
  1671. while (p->context_stack.count > 0) {
  1672. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  1673. if (ctx->scope_index >= p->scope_index) {
  1674. array_pop(&p->context_stack);
  1675. } else {
  1676. break;
  1677. }
  1678. }
  1679. p->scope_index -= 1;
  1680. }
  1681. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  1682. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  1683. GB_ASSERT(is_type_boolean(tv.type));
  1684. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  1685. if (tv.value.value_bool) {
  1686. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  1687. } else if (ws->else_stmt) {
  1688. switch (ws->else_stmt->kind) {
  1689. case Ast_BlockStmt:
  1690. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  1691. break;
  1692. case Ast_WhenStmt:
  1693. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  1694. break;
  1695. default:
  1696. GB_PANIC("Invalid 'else' statement in 'when' statement");
  1697. break;
  1698. }
  1699. }
  1700. }
  1701. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  1702. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1703. lbModule *m = p->module;
  1704. lbValue count = {};
  1705. Type *expr_type = base_type(type_deref(expr.type));
  1706. switch (expr_type->kind) {
  1707. case Type_Array:
  1708. count = lb_const_int(m, t_int, expr_type->Array.count);
  1709. break;
  1710. }
  1711. lbValue val = {};
  1712. lbValue idx = {};
  1713. lbBlock *loop = nullptr;
  1714. lbBlock *done = nullptr;
  1715. lbBlock *body = nullptr;
  1716. lbAddr index = lb_add_local_generated(p, t_int, false);
  1717. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  1718. loop = lb_create_block(p, "for.index.loop");
  1719. lb_emit_jump(p, loop);
  1720. lb_start_block(p, loop);
  1721. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  1722. lb_addr_store(p, index, incr);
  1723. body = lb_create_block(p, "for.index.body");
  1724. done = lb_create_block(p, "for.index.done");
  1725. if (count.value == nullptr) {
  1726. GB_ASSERT(count_ptr.value != nullptr);
  1727. count = lb_emit_load(p, count_ptr);
  1728. }
  1729. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  1730. lb_emit_if(p, cond, body, done);
  1731. lb_start_block(p, body);
  1732. idx = lb_addr_load(p, index);
  1733. switch (expr_type->kind) {
  1734. case Type_Array: {
  1735. if (val_type != nullptr) {
  1736. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  1737. }
  1738. break;
  1739. }
  1740. case Type_EnumeratedArray: {
  1741. if (val_type != nullptr) {
  1742. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  1743. // NOTE(bill): Override the idx value for the enumeration
  1744. Type *index_type = expr_type->EnumeratedArray.index;
  1745. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  1746. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  1747. }
  1748. }
  1749. break;
  1750. }
  1751. case Type_Slice: {
  1752. if (val_type != nullptr) {
  1753. lbValue elem = lb_slice_elem(p, expr);
  1754. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  1755. }
  1756. break;
  1757. }
  1758. case Type_DynamicArray: {
  1759. if (val_type != nullptr) {
  1760. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  1761. elem = lb_emit_load(p, elem);
  1762. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  1763. }
  1764. break;
  1765. }
  1766. case Type_Map: {
  1767. lbAddr key = lb_add_local_generated(p, expr_type->Map.key, true);
  1768. lbValue entries = lb_map_entries_ptr(p, expr);
  1769. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  1770. elem = lb_emit_load(p, elem);
  1771. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  1772. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  1773. lbValue hash = lb_emit_struct_ep(p, entry, 0);
  1774. if (is_type_string(expr_type->Map.key)) {
  1775. lbValue str = lb_emit_struct_ep(p, hash, 1);
  1776. lb_addr_store(p, key, lb_emit_load(p, str));
  1777. } else {
  1778. lbValue hash_ptr = lb_emit_struct_ep(p, hash, 0);
  1779. hash_ptr = lb_emit_conv(p, hash_ptr, key.addr.type);
  1780. lb_addr_store(p, key, lb_emit_load(p, hash_ptr));
  1781. }
  1782. idx = lb_addr_load(p, key);
  1783. break;
  1784. }
  1785. default:
  1786. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  1787. break;
  1788. }
  1789. if (val_) *val_ = val;
  1790. if (idx_) *idx_ = idx;
  1791. if (loop_) *loop_ = loop;
  1792. if (done_) *done_ = done;
  1793. }
  1794. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  1795. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1796. lbModule *m = p->module;
  1797. lbValue count = lb_const_int(m, t_int, 0);
  1798. Type *expr_type = base_type(expr.type);
  1799. switch (expr_type->kind) {
  1800. case Type_Basic:
  1801. count = lb_string_len(p, expr);
  1802. break;
  1803. default:
  1804. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  1805. break;
  1806. }
  1807. lbValue val = {};
  1808. lbValue idx = {};
  1809. lbBlock *loop = nullptr;
  1810. lbBlock *done = nullptr;
  1811. lbBlock *body = nullptr;
  1812. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  1813. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  1814. loop = lb_create_block(p, "for.string.loop");
  1815. lb_emit_jump(p, loop);
  1816. lb_start_block(p, loop);
  1817. body = lb_create_block(p, "for.string.body");
  1818. done = lb_create_block(p, "for.string.done");
  1819. lbValue offset = lb_addr_load(p, offset_);
  1820. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  1821. lb_emit_if(p, cond, body, done);
  1822. lb_start_block(p, body);
  1823. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  1824. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  1825. auto args = array_make<lbValue>(heap_allocator(), 1);
  1826. args[0] = lb_emit_string(p, str_elem, str_len);
  1827. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  1828. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  1829. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  1830. idx = offset;
  1831. if (val_type != nullptr) {
  1832. val = lb_emit_struct_ev(p, rune_and_len, 0);
  1833. }
  1834. if (val_) *val_ = val;
  1835. if (idx_) *idx_ = idx;
  1836. if (loop_) *loop_ = loop;
  1837. if (done_) *done_ = done;
  1838. }
  1839. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  1840. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1841. lbModule *m = p->module;
  1842. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  1843. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  1844. lbValue lower = lb_build_expr(p, node->left);
  1845. lbValue upper = {};
  1846. lbValue val = {};
  1847. lbValue idx = {};
  1848. lbBlock *loop = nullptr;
  1849. lbBlock *done = nullptr;
  1850. lbBlock *body = nullptr;
  1851. if (val_type == nullptr) {
  1852. val_type = lower.type;
  1853. }
  1854. lbAddr value = lb_add_local_generated(p, val_type, false);
  1855. lb_addr_store(p, value, lower);
  1856. lbAddr index = lb_add_local_generated(p, t_int, false);
  1857. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  1858. loop = lb_create_block(p, "for.interval.loop");
  1859. lb_emit_jump(p, loop);
  1860. lb_start_block(p, loop);
  1861. body = lb_create_block(p, "for.interval.body");
  1862. done = lb_create_block(p, "for.interval.done");
  1863. TokenKind op = Token_Lt;
  1864. switch (node->op.kind) {
  1865. case Token_Ellipsis: op = Token_LtEq; break;
  1866. case Token_RangeHalf: op = Token_Lt; break;
  1867. default: GB_PANIC("Invalid interval operator"); break;
  1868. }
  1869. upper = lb_build_expr(p, node->right);
  1870. lbValue curr_value = lb_addr_load(p, value);
  1871. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  1872. lb_emit_if(p, cond, body, done);
  1873. lb_start_block(p, body);
  1874. val = lb_addr_load(p, value);
  1875. idx = lb_addr_load(p, index);
  1876. lb_emit_increment(p, value.addr);
  1877. lb_emit_increment(p, index.addr);
  1878. if (val_) *val_ = val;
  1879. if (idx_) *idx_ = idx;
  1880. if (loop_) *loop_ = loop;
  1881. if (done_) *done_ = done;
  1882. }
  1883. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  1884. lbModule *m = p->module;
  1885. Type *t = enum_type;
  1886. GB_ASSERT(is_type_enum(t));
  1887. Type *enum_ptr = alloc_type_pointer(t);
  1888. t = base_type(t);
  1889. Type *core_elem = core_type(t);
  1890. GB_ASSERT(t->kind == Type_Enum);
  1891. i64 enum_count = t->Enum.fields.count;
  1892. lbValue max_count = lb_const_int(m, t_int, enum_count);
  1893. lbValue ti = lb_type_info(m, t);
  1894. lbValue variant = lb_emit_struct_ep(p, ti, 3);
  1895. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  1896. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  1897. lbValue values_data = lb_slice_elem(p, values);
  1898. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  1899. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  1900. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  1901. lb_emit_jump(p, loop);
  1902. lb_start_block(p, loop);
  1903. lbBlock *body = lb_create_block(p, "for.enum.body");
  1904. lbBlock *done = lb_create_block(p, "for.enum.done");
  1905. lbValue offset = lb_addr_load(p, offset_);
  1906. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  1907. lb_emit_if(p, cond, body, done);
  1908. lb_start_block(p, body);
  1909. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  1910. lb_emit_increment(p, offset_.addr);
  1911. lbValue val = {};
  1912. if (val_type != nullptr) {
  1913. GB_ASSERT(are_types_identical(enum_type, val_type));
  1914. if (is_type_integer(core_elem)) {
  1915. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  1916. val = lb_emit_conv(p, i, t);
  1917. } else {
  1918. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  1919. }
  1920. }
  1921. if (val_) *val_ = val;
  1922. if (idx_) *idx_ = offset;
  1923. if (loop_) *loop_ = loop;
  1924. if (done_) *done_ = done;
  1925. }
  1926. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  1927. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  1928. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  1929. lb_emit_jump(p, loop);
  1930. lb_start_block(p, loop);
  1931. lbBlock *body = lb_create_block(p, "for.tuple.body");
  1932. lbBlock *done = lb_create_block(p, "for.tuple.done");
  1933. lbValue tuple_value = lb_build_expr(p, expr);
  1934. Type *tuple = tuple_value.type;
  1935. GB_ASSERT(tuple->kind == Type_Tuple);
  1936. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  1937. i32 cond_index = tuple_count-1;
  1938. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  1939. lb_emit_if(p, cond, body, done);
  1940. lb_start_block(p, body);
  1941. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  1942. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  1943. if (loop_) *loop_ = loop;
  1944. if (done_) *done_ = done;
  1945. }
  1946. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  1947. lb_open_scope(p);
  1948. Type *val0_type = nullptr;
  1949. Type *val1_type = nullptr;
  1950. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  1951. val0_type = type_of_expr(rs->val0);
  1952. }
  1953. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  1954. val1_type = type_of_expr(rs->val1);
  1955. }
  1956. if (val0_type != nullptr) {
  1957. Entity *e = entity_of_ident(rs->val0);
  1958. lb_add_local(p, e->type, e, true);
  1959. }
  1960. if (val1_type != nullptr) {
  1961. Entity *e = entity_of_ident(rs->val1);
  1962. lb_add_local(p, e->type, e, true);
  1963. }
  1964. lbValue val = {};
  1965. lbValue key = {};
  1966. lbBlock *loop = nullptr;
  1967. lbBlock *done = nullptr;
  1968. Ast *expr = unparen_expr(rs->expr);
  1969. bool is_map = false;
  1970. TypeAndValue tav = type_and_value_of_expr(expr);
  1971. if (is_ast_range(expr)) {
  1972. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  1973. } else if (tav.mode == Addressing_Type) {
  1974. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  1975. } else {
  1976. Type *expr_type = type_of_expr(expr);
  1977. Type *et = base_type(type_deref(expr_type));
  1978. switch (et->kind) {
  1979. case Type_Map: {
  1980. is_map = true;
  1981. gbAllocator a = heap_allocator();
  1982. lbAddr addr = lb_build_addr(p, expr);
  1983. lbValue map = lb_addr_get_ptr(p, addr);
  1984. if (is_type_pointer(type_deref(lb_addr_type(addr)))) {
  1985. map = lb_addr_load(p, addr);
  1986. }
  1987. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  1988. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  1989. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  1990. break;
  1991. }
  1992. case Type_Array: {
  1993. lbValue array = lb_build_addr_ptr(p, expr);
  1994. if (is_type_pointer(type_deref(array.type))) {
  1995. array = lb_emit_load(p, array);
  1996. }
  1997. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  1998. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  1999. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2000. break;
  2001. }
  2002. case Type_EnumeratedArray: {
  2003. lbValue array = lb_build_addr_ptr(p, expr);
  2004. if (is_type_pointer(type_deref(array.type))) {
  2005. array = lb_emit_load(p, array);
  2006. }
  2007. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2008. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  2009. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2010. break;
  2011. }
  2012. case Type_DynamicArray: {
  2013. lbValue count_ptr = {};
  2014. lbValue array = lb_build_addr_ptr(p, expr);
  2015. if (is_type_pointer(type_deref(array.type))) {
  2016. array = lb_emit_load(p, array);
  2017. }
  2018. count_ptr = lb_emit_struct_ep(p, array, 1);
  2019. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  2020. break;
  2021. }
  2022. case Type_Slice: {
  2023. lbValue count_ptr = {};
  2024. lbValue slice = lb_build_expr(p, expr);
  2025. if (is_type_pointer(slice.type)) {
  2026. count_ptr = lb_emit_struct_ep(p, slice, 1);
  2027. slice = lb_emit_load(p, slice);
  2028. } else {
  2029. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  2030. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  2031. }
  2032. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  2033. break;
  2034. }
  2035. case Type_Basic: {
  2036. lbValue string = lb_build_expr(p, expr);
  2037. if (is_type_pointer(string.type)) {
  2038. string = lb_emit_load(p, string);
  2039. }
  2040. if (is_type_untyped(expr_type)) {
  2041. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  2042. lb_addr_store(p, s, string);
  2043. string = lb_addr_load(p, s);
  2044. }
  2045. Type *t = base_type(string.type);
  2046. GB_ASSERT(!is_type_cstring(t));
  2047. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  2048. break;
  2049. }
  2050. case Type_Tuple:
  2051. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  2052. break;
  2053. default:
  2054. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  2055. break;
  2056. }
  2057. }
  2058. lbAddr val0_addr = {};
  2059. lbAddr val1_addr = {};
  2060. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2061. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2062. if (is_map) {
  2063. if (val0_type) lb_addr_store(p, val0_addr, key);
  2064. if (val1_type) lb_addr_store(p, val1_addr, val);
  2065. } else {
  2066. if (val0_type) lb_addr_store(p, val0_addr, val);
  2067. if (val1_type) lb_addr_store(p, val1_addr, key);
  2068. }
  2069. lb_push_target_list(p, rs->label, done, loop, nullptr);
  2070. lb_build_stmt(p, rs->body);
  2071. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2072. lb_pop_target_list(p);
  2073. lb_emit_jump(p, loop);
  2074. lb_start_block(p, done);
  2075. }
  2076. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  2077. lbModule *m = p->module;
  2078. lb_open_scope(p); // Open scope here
  2079. Type *val0_type = nullptr;
  2080. Type *val1_type = nullptr;
  2081. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2082. val0_type = type_of_expr(rs->val0);
  2083. }
  2084. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2085. val1_type = type_of_expr(rs->val1);
  2086. }
  2087. if (val0_type != nullptr) {
  2088. Entity *e = entity_of_ident(rs->val0);
  2089. lb_add_local(p, e->type, e, true);
  2090. }
  2091. if (val1_type != nullptr) {
  2092. Entity *e = entity_of_ident(rs->val1);
  2093. lb_add_local(p, e->type, e, true);
  2094. }
  2095. lbValue val = {};
  2096. lbValue key = {};
  2097. lbBlock *loop = nullptr;
  2098. lbBlock *done = nullptr;
  2099. Ast *expr = unparen_expr(rs->expr);
  2100. TypeAndValue tav = type_and_value_of_expr(expr);
  2101. if (is_ast_range(expr)) {
  2102. lbAddr val0_addr = {};
  2103. lbAddr val1_addr = {};
  2104. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2105. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2106. TokenKind op = expr->BinaryExpr.op.kind;
  2107. Ast *start_expr = expr->BinaryExpr.left;
  2108. Ast *end_expr = expr->BinaryExpr.right;
  2109. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  2110. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  2111. ExactValue start = start_expr->tav.value;
  2112. ExactValue end = end_expr->tav.value;
  2113. if (op == Token_Ellipsis) { // .. [start, end]
  2114. ExactValue index = exact_value_i64(0);
  2115. for (ExactValue val = start;
  2116. compare_exact_values(Token_LtEq, val, end);
  2117. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2118. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2119. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2120. lb_build_stmt(p, rs->body);
  2121. }
  2122. } else if (op == Token_RangeHalf) { // ..< [start, end)
  2123. ExactValue index = exact_value_i64(0);
  2124. for (ExactValue val = start;
  2125. compare_exact_values(Token_Lt, val, end);
  2126. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2127. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2128. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2129. lb_build_stmt(p, rs->body);
  2130. }
  2131. }
  2132. } else if (tav.mode == Addressing_Type) {
  2133. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  2134. Type *et = type_deref(tav.type);
  2135. Type *bet = base_type(et);
  2136. lbAddr val0_addr = {};
  2137. lbAddr val1_addr = {};
  2138. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2139. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2140. for_array(i, bet->Enum.fields) {
  2141. Entity *field = bet->Enum.fields[i];
  2142. GB_ASSERT(field->kind == Entity_Constant);
  2143. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  2144. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2145. lb_build_stmt(p, rs->body);
  2146. }
  2147. } else {
  2148. lbAddr val0_addr = {};
  2149. lbAddr val1_addr = {};
  2150. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2151. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2152. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  2153. Type *t = base_type(expr->tav.type);
  2154. switch (t->kind) {
  2155. case Type_Basic:
  2156. GB_ASSERT(is_type_string(t));
  2157. {
  2158. ExactValue value = expr->tav.value;
  2159. GB_ASSERT(value.kind == ExactValue_String);
  2160. String str = value.value_string;
  2161. Rune codepoint = 0;
  2162. isize offset = 0;
  2163. do {
  2164. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  2165. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  2166. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  2167. lb_build_stmt(p, rs->body);
  2168. offset += width;
  2169. } while (offset < str.len);
  2170. }
  2171. break;
  2172. case Type_Array:
  2173. if (t->Array.count > 0) {
  2174. lbValue val = lb_build_expr(p, expr);
  2175. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2176. for (i64 i = 0; i < t->Array.count; i++) {
  2177. if (val0_type) {
  2178. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2179. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2180. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2181. }
  2182. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2183. lb_build_stmt(p, rs->body);
  2184. }
  2185. }
  2186. break;
  2187. case Type_EnumeratedArray:
  2188. if (t->EnumeratedArray.count > 0) {
  2189. lbValue val = lb_build_expr(p, expr);
  2190. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2191. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  2192. if (val0_type) {
  2193. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2194. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2195. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2196. }
  2197. if (val1_type) {
  2198. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  2199. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  2200. }
  2201. lb_build_stmt(p, rs->body);
  2202. }
  2203. }
  2204. break;
  2205. default:
  2206. GB_PANIC("Invalid inline for type");
  2207. break;
  2208. }
  2209. }
  2210. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2211. }
  2212. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  2213. if (ss->init != nullptr) {
  2214. lb_build_stmt(p, ss->init);
  2215. }
  2216. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  2217. if (ss->tag != nullptr) {
  2218. tag = lb_build_expr(p, ss->tag);
  2219. }
  2220. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  2221. ast_node(body, BlockStmt, ss->body);
  2222. Array<Ast *> default_stmts = {};
  2223. lbBlock *default_fall = nullptr;
  2224. lbBlock *default_block = nullptr;
  2225. lbBlock *fall = nullptr;
  2226. bool append_fall = false;
  2227. isize case_count = body->stmts.count;
  2228. for_array(i, body->stmts) {
  2229. Ast *clause = body->stmts[i];
  2230. lbBlock *body = fall;
  2231. ast_node(cc, CaseClause, clause);
  2232. if (body == nullptr) {
  2233. if (cc->list.count == 0) {
  2234. body = lb_create_block(p, "switch.dflt.body");
  2235. } else {
  2236. body = lb_create_block(p, "switch.case.body");
  2237. }
  2238. }
  2239. if (append_fall && body == fall) {
  2240. append_fall = false;
  2241. }
  2242. fall = done;
  2243. if (i+1 < case_count) {
  2244. append_fall = true;
  2245. fall = lb_create_block(p, "switch.fall.body");
  2246. }
  2247. if (cc->list.count == 0) {
  2248. // default case
  2249. default_stmts = cc->stmts;
  2250. default_fall = fall;
  2251. default_block = body;
  2252. continue;
  2253. }
  2254. lbBlock *next_cond = nullptr;
  2255. for_array(j, cc->list) {
  2256. Ast *expr = unparen_expr(cc->list[j]);
  2257. next_cond = lb_create_block(p, "switch.case.next");
  2258. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  2259. if (is_ast_range(expr)) {
  2260. ast_node(ie, BinaryExpr, expr);
  2261. TokenKind op = Token_Invalid;
  2262. switch (ie->op.kind) {
  2263. case Token_Ellipsis: op = Token_LtEq; break;
  2264. case Token_RangeHalf: op = Token_Lt; break;
  2265. default: GB_PANIC("Invalid interval operator"); break;
  2266. }
  2267. lbValue lhs = lb_build_expr(p, ie->left);
  2268. lbValue rhs = lb_build_expr(p, ie->right);
  2269. // TODO(bill): do short circuit here
  2270. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  2271. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  2272. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  2273. } else {
  2274. if (expr->tav.mode == Addressing_Type) {
  2275. GB_ASSERT(is_type_typeid(tag.type));
  2276. lbValue e = lb_typeid(p->module, expr->tav.type);
  2277. e = lb_emit_conv(p, e, tag.type);
  2278. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  2279. } else {
  2280. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  2281. }
  2282. }
  2283. lb_emit_if(p, cond, body, next_cond);
  2284. lb_start_block(p, next_cond);
  2285. }
  2286. lb_start_block(p, body);
  2287. lb_push_target_list(p, ss->label, done, nullptr, fall);
  2288. lb_open_scope(p);
  2289. lb_build_stmt_list(p, cc->stmts);
  2290. lb_close_scope(p, lbDeferExit_Default, body);
  2291. lb_pop_target_list(p);
  2292. lb_emit_jump(p, done);
  2293. lb_start_block(p, next_cond);
  2294. }
  2295. if (default_block != nullptr) {
  2296. lb_emit_jump(p, default_block);
  2297. lb_start_block(p, default_block);
  2298. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  2299. lb_open_scope(p);
  2300. lb_build_stmt_list(p, default_stmts);
  2301. lb_close_scope(p, lbDeferExit_Default, default_block);
  2302. lb_pop_target_list(p);
  2303. }
  2304. lb_emit_jump(p, done);
  2305. lb_start_block(p, done);
  2306. }
  2307. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  2308. Entity *e = implicit_entity_of_node(clause);
  2309. GB_ASSERT(e != nullptr);
  2310. lbAddr x = lb_add_local(p, e->type, e, false);
  2311. lb_addr_store(p, x, value);
  2312. }
  2313. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  2314. ast_node(cc, CaseClause, clause);
  2315. lb_push_target_list(p, label, done, nullptr, nullptr);
  2316. lb_open_scope(p);
  2317. lb_build_stmt_list(p, cc->stmts);
  2318. lb_close_scope(p, lbDeferExit_Default, body);
  2319. lb_pop_target_list(p);
  2320. lb_emit_jump(p, done);
  2321. }
  2322. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  2323. lbModule *m = p->module;
  2324. ast_node(as, AssignStmt, ss->tag);
  2325. GB_ASSERT(as->lhs.count == 1);
  2326. GB_ASSERT(as->rhs.count == 1);
  2327. lbValue parent = lb_build_expr(p, as->rhs[0]);
  2328. bool is_parent_ptr = is_type_pointer(parent.type);
  2329. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  2330. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  2331. lbValue parent_value = parent;
  2332. lbValue parent_ptr = parent;
  2333. if (!is_parent_ptr) {
  2334. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  2335. }
  2336. lbValue tag_index = {};
  2337. lbValue union_data = {};
  2338. if (switch_kind == TypeSwitch_Union) {
  2339. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  2340. tag_index = lb_emit_load(p, tag_ptr);
  2341. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  2342. }
  2343. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  2344. lb_emit_jump(p, start_block);
  2345. lb_start_block(p, start_block);
  2346. // NOTE(bill): Append this later
  2347. lbBlock *done = lb_create_block(p, "typeswitch.done");
  2348. Ast *default_ = nullptr;
  2349. ast_node(body, BlockStmt, ss->body);
  2350. gb_local_persist i32 weird_count = 0;
  2351. for_array(i, body->stmts) {
  2352. Ast *clause = body->stmts[i];
  2353. ast_node(cc, CaseClause, clause);
  2354. if (cc->list.count == 0) {
  2355. default_ = clause;
  2356. continue;
  2357. }
  2358. lbBlock *body = lb_create_block(p, "typeswitch.body");
  2359. lbBlock *next = nullptr;
  2360. Type *case_type = nullptr;
  2361. for_array(type_index, cc->list) {
  2362. next = lb_create_block(p, "typeswitch.next");
  2363. case_type = type_of_expr(cc->list[type_index]);
  2364. lbValue cond = {};
  2365. if (switch_kind == TypeSwitch_Union) {
  2366. Type *ut = base_type(type_deref(parent.type));
  2367. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  2368. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  2369. } else if (switch_kind == TypeSwitch_Any) {
  2370. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  2371. lbValue case_typeid = lb_typeid(m, case_type);
  2372. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  2373. }
  2374. GB_ASSERT(cond.value != nullptr);
  2375. lb_emit_if(p, cond, body, next);
  2376. lb_start_block(p, next);
  2377. }
  2378. Entity *case_entity = implicit_entity_of_node(clause);
  2379. lbValue value = parent_value;
  2380. lb_start_block(p, body);
  2381. // bool any_or_not_ptr = is_type_any(type_deref(parent.type)) || !is_parent_ptr;
  2382. bool any_or_not_ptr = !is_parent_ptr;
  2383. if (cc->list.count == 1) {
  2384. Type *ct = case_entity->type;
  2385. if (any_or_not_ptr) {
  2386. ct = alloc_type_pointer(ct);
  2387. }
  2388. GB_ASSERT_MSG(is_type_pointer(ct), "%s", type_to_string(ct));
  2389. lbValue data = {};
  2390. if (switch_kind == TypeSwitch_Union) {
  2391. data = union_data;
  2392. } else if (switch_kind == TypeSwitch_Any) {
  2393. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  2394. data = any_data;
  2395. }
  2396. value = lb_emit_conv(p, data, ct);
  2397. if (any_or_not_ptr) {
  2398. value = lb_emit_load(p, value);
  2399. }
  2400. }
  2401. lb_store_type_case_implicit(p, clause, value);
  2402. lb_type_case_body(p, ss->label, clause, body, done);
  2403. lb_start_block(p, next);
  2404. }
  2405. if (default_ != nullptr) {
  2406. lb_store_type_case_implicit(p, default_, parent_value);
  2407. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  2408. } else {
  2409. lb_emit_jump(p, done);
  2410. }
  2411. lb_start_block(p, done);
  2412. }
  2413. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  2414. lbModule *m = p->module;
  2415. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  2416. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  2417. type = default_type(type);
  2418. lbValue short_circuit = {};
  2419. if (op == Token_CmpAnd) {
  2420. lb_build_cond(p, left, rhs, done);
  2421. short_circuit = lb_const_bool(m, type, false);
  2422. } else if (op == Token_CmpOr) {
  2423. lb_build_cond(p, left, done, rhs);
  2424. short_circuit = lb_const_bool(m, type, true);
  2425. }
  2426. if (rhs->preds.count == 0) {
  2427. lb_start_block(p, done);
  2428. return short_circuit;
  2429. }
  2430. if (done->preds.count == 0) {
  2431. lb_start_block(p, rhs);
  2432. return lb_build_expr(p, right);
  2433. }
  2434. Array<LLVMValueRef> incoming_values = {};
  2435. Array<LLVMBasicBlockRef> incoming_blocks = {};
  2436. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  2437. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  2438. for_array(i, done->preds) {
  2439. incoming_values[i] = short_circuit.value;
  2440. incoming_blocks[i] = done->preds[i]->block;
  2441. }
  2442. lb_start_block(p, rhs);
  2443. lbValue edge = lb_build_expr(p, right);
  2444. incoming_values[done->preds.count] = edge.value;
  2445. incoming_blocks[done->preds.count] = p->curr_block->block;
  2446. lb_emit_jump(p, done);
  2447. lb_start_block(p, done);
  2448. lbValue res = {};
  2449. res.type = type;
  2450. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  2451. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  2452. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  2453. return res;
  2454. }
  2455. void lb_build_stmt(lbProcedure *p, Ast *node) {
  2456. switch (node->kind) {
  2457. case_ast_node(bs, EmptyStmt, node);
  2458. case_end;
  2459. case_ast_node(us, UsingStmt, node);
  2460. case_end;
  2461. case_ast_node(ws, WhenStmt, node);
  2462. lb_build_when_stmt(p, ws);
  2463. case_end;
  2464. case_ast_node(bs, BlockStmt, node);
  2465. if (bs->label != nullptr) {
  2466. lbBlock *done = lb_create_block(p, "block.done");
  2467. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  2468. tl->is_block = true;
  2469. lb_open_scope(p);
  2470. lb_build_stmt_list(p, bs->stmts);
  2471. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2472. lb_emit_jump(p, done);
  2473. lb_start_block(p, done);
  2474. } else {
  2475. lb_open_scope(p);
  2476. lb_build_stmt_list(p, bs->stmts);
  2477. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2478. }
  2479. case_end;
  2480. case_ast_node(vd, ValueDecl, node);
  2481. if (!vd->is_mutable) {
  2482. return;
  2483. }
  2484. bool is_static = false;
  2485. if (vd->names.count > 0) {
  2486. Entity *e = entity_of_ident(vd->names[0]);
  2487. if (e->flags & EntityFlag_Static) {
  2488. // NOTE(bill): If one of the entities is static, they all are
  2489. is_static = true;
  2490. }
  2491. }
  2492. if (is_static) {
  2493. for_array(i, vd->names) {
  2494. lbValue value = {};
  2495. if (vd->values.count > 0) {
  2496. GB_ASSERT(vd->names.count == vd->values.count);
  2497. Ast *ast_value = vd->values[i];
  2498. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  2499. ast_value->tav.mode == Addressing_Invalid);
  2500. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value);
  2501. }
  2502. Ast *ident = vd->names[i];
  2503. GB_ASSERT(!is_blank_ident(ident));
  2504. Entity *e = entity_of_ident(ident);
  2505. GB_ASSERT(e->flags & EntityFlag_Static);
  2506. String name = e->token.string;
  2507. String mangled_name = {};
  2508. {
  2509. gbString str = gb_string_make_length(heap_allocator(), p->name.text, p->name.len);
  2510. str = gb_string_appendc(str, "-");
  2511. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  2512. mangled_name.text = cast(u8 *)str;
  2513. mangled_name.len = gb_string_length(str);
  2514. }
  2515. char *c_name = alloc_cstring(heap_allocator(), mangled_name);
  2516. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  2517. if (value.value != nullptr) {
  2518. LLVMSetInitializer(global, value.value);
  2519. } else {
  2520. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  2521. }
  2522. if (e->Variable.thread_local_model != "") {
  2523. LLVMSetThreadLocal(global, true);
  2524. String m = e->Variable.thread_local_model;
  2525. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  2526. if (m == "default") {
  2527. mode = LLVMGeneralDynamicTLSModel;
  2528. } else if (m == "localdynamic") {
  2529. mode = LLVMLocalDynamicTLSModel;
  2530. } else if (m == "initialexec") {
  2531. mode = LLVMInitialExecTLSModel;
  2532. } else if (m == "localexec") {
  2533. mode = LLVMLocalExecTLSModel;
  2534. } else {
  2535. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  2536. }
  2537. LLVMSetThreadLocalMode(global, mode);
  2538. } else {
  2539. LLVMSetLinkage(global, LLVMInternalLinkage);
  2540. }
  2541. lbValue global_val = {global, alloc_type_pointer(e->type)};
  2542. lb_add_entity(p->module, e, global_val);
  2543. lb_add_member(p->module, mangled_name, global_val);
  2544. }
  2545. return;
  2546. }
  2547. if (vd->values.count == 0) { // declared and zero-initialized
  2548. for_array(i, vd->names) {
  2549. Ast *name = vd->names[i];
  2550. if (!is_blank_ident(name)) {
  2551. Entity *e = entity_of_ident(name);
  2552. lb_add_local(p, e->type, e, true);
  2553. }
  2554. }
  2555. } else { // Tuple(s)
  2556. auto lvals = array_make<lbAddr>(heap_allocator(), 0, vd->names.count);
  2557. auto inits = array_make<lbValue>(heap_allocator(), 0, vd->names.count);
  2558. for_array(i, vd->names) {
  2559. Ast *name = vd->names[i];
  2560. lbAddr lval = {};
  2561. if (!is_blank_ident(name)) {
  2562. Entity *e = entity_of_ident(name);
  2563. lval = lb_add_local(p, e->type, e, false);
  2564. }
  2565. array_add(&lvals, lval);
  2566. }
  2567. for_array(i, vd->values) {
  2568. lbValue init = lb_build_expr(p, vd->values[i]);
  2569. Type *t = init.type;
  2570. if (t->kind == Type_Tuple) {
  2571. for_array(i, t->Tuple.variables) {
  2572. Entity *e = t->Tuple.variables[i];
  2573. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  2574. array_add(&inits, v);
  2575. }
  2576. } else {
  2577. array_add(&inits, init);
  2578. }
  2579. }
  2580. for_array(i, inits) {
  2581. lbAddr lval = lvals[i];
  2582. lbValue init = inits[i];
  2583. lb_addr_store(p, lval, init);
  2584. }
  2585. }
  2586. case_end;
  2587. case_ast_node(as, AssignStmt, node);
  2588. if (as->op.kind == Token_Eq) {
  2589. auto lvals = array_make<lbAddr>(heap_allocator(), 0, as->lhs.count);
  2590. for_array(i, as->lhs) {
  2591. Ast *lhs = as->lhs[i];
  2592. lbAddr lval = {};
  2593. if (!is_blank_ident(lhs)) {
  2594. lval = lb_build_addr(p, lhs);
  2595. }
  2596. array_add(&lvals, lval);
  2597. }
  2598. if (as->lhs.count == as->rhs.count) {
  2599. if (as->lhs.count == 1) {
  2600. lbAddr lval = lvals[0];
  2601. Ast *rhs = as->rhs[0];
  2602. lbValue init = lb_build_expr(p, rhs);
  2603. lb_addr_store(p, lvals[0], init);
  2604. } else {
  2605. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  2606. for_array(i, as->rhs) {
  2607. lbValue init = lb_build_expr(p, as->rhs[i]);
  2608. array_add(&inits, init);
  2609. }
  2610. for_array(i, inits) {
  2611. lbAddr lval = lvals[i];
  2612. lbValue init = inits[i];
  2613. lb_addr_store(p, lval, init);
  2614. }
  2615. }
  2616. } else {
  2617. auto inits = array_make<lbValue>(heap_allocator(), 0, lvals.count);
  2618. for_array(i, as->rhs) {
  2619. lbValue init = lb_build_expr(p, as->rhs[i]);
  2620. Type *t = init.type;
  2621. // TODO(bill): refactor for code reuse as this is repeated a bit
  2622. if (t->kind == Type_Tuple) {
  2623. for_array(i, t->Tuple.variables) {
  2624. Entity *e = t->Tuple.variables[i];
  2625. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  2626. array_add(&inits, v);
  2627. }
  2628. } else {
  2629. array_add(&inits, init);
  2630. }
  2631. }
  2632. for_array(i, inits) {
  2633. lbAddr lval = lvals[i];
  2634. lbValue init = inits[i];
  2635. lb_addr_store(p, lval, init);
  2636. }
  2637. }
  2638. } else {
  2639. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  2640. // +=, -=, etc
  2641. i32 op = cast(i32)as->op.kind;
  2642. op += Token_Add - Token_AddEq; // Convert += to +
  2643. if (op == Token_CmpAnd || op == Token_CmpOr) {
  2644. Type *type = as->lhs[0]->tav.type;
  2645. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  2646. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  2647. lb_addr_store(p, lhs, new_value);
  2648. } else {
  2649. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  2650. lbValue value = lb_build_expr(p, as->rhs[0]);
  2651. lbValue old_value = lb_addr_load(p, lhs);
  2652. Type *type = old_value.type;
  2653. lbValue change = lb_emit_conv(p, value, type);
  2654. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  2655. lb_addr_store(p, lhs, new_value);
  2656. }
  2657. return;
  2658. }
  2659. case_end;
  2660. case_ast_node(es, ExprStmt, node);
  2661. lb_build_expr(p, es->expr);
  2662. case_end;
  2663. case_ast_node(ds, DeferStmt, node);
  2664. isize scope_index = p->scope_index;
  2665. lb_add_defer_node(p, scope_index, ds->stmt);
  2666. case_end;
  2667. case_ast_node(rs, ReturnStmt, node);
  2668. lbValue res = {};
  2669. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  2670. isize return_count = p->type->Proc.result_count;
  2671. isize res_count = rs->results.count;
  2672. if (return_count == 0) {
  2673. // No return values
  2674. LLVMBuildRetVoid(p->builder);
  2675. return;
  2676. } else if (return_count == 1) {
  2677. Entity *e = tuple->variables[0];
  2678. if (res_count == 0) {
  2679. lbValue *found = map_get(&p->module->values, hash_entity(e));
  2680. GB_ASSERT(found);
  2681. res = lb_emit_load(p, *found);
  2682. } else {
  2683. res = lb_build_expr(p, rs->results[0]);
  2684. res = lb_emit_conv(p, res, e->type);
  2685. }
  2686. } else {
  2687. auto results = array_make<lbValue>(heap_allocator(), 0, return_count);
  2688. if (res_count != 0) {
  2689. for (isize res_index = 0; res_index < res_count; res_index++) {
  2690. lbValue res = lb_build_expr(p, rs->results[res_index]);
  2691. Type *t = res.type;
  2692. if (t->kind == Type_Tuple) {
  2693. for_array(i, t->Tuple.variables) {
  2694. Entity *e = t->Tuple.variables[i];
  2695. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  2696. array_add(&results, v);
  2697. }
  2698. } else {
  2699. array_add(&results, res);
  2700. }
  2701. }
  2702. } else {
  2703. for (isize res_index = 0; res_index < return_count; res_index++) {
  2704. Entity *e = tuple->variables[res_index];
  2705. lbValue *found = map_get(&p->module->values, hash_entity(e));
  2706. GB_ASSERT(found);
  2707. lbValue res = lb_emit_load(p, *found);
  2708. array_add(&results, res);
  2709. }
  2710. }
  2711. GB_ASSERT(results.count == return_count);
  2712. Type *ret_type = p->type->Proc.results;
  2713. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  2714. res = lb_add_local_generated(p, ret_type, false).addr;
  2715. for_array(i, results) {
  2716. Entity *e = tuple->variables[i];
  2717. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  2718. lbValue val = lb_emit_conv(p, results[i], e->type);
  2719. lb_emit_store(p, field, val);
  2720. }
  2721. res = lb_emit_load(p, res);
  2722. }
  2723. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2724. if (p->type->Proc.return_by_pointer) {
  2725. if (res.value != nullptr) {
  2726. lb_addr_store(p, p->return_ptr, res);
  2727. } else {
  2728. lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type));
  2729. }
  2730. LLVMBuildRetVoid(p->builder);
  2731. } else {
  2732. GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name));
  2733. Type *abi_rt = p->type->Proc.abi_compat_result_type;
  2734. if (!are_types_identical(res.type, abi_rt)) {
  2735. res = lb_emit_transmute(p, res, abi_rt);
  2736. }
  2737. LLVMBuildRet(p->builder, res.value);
  2738. }
  2739. case_end;
  2740. case_ast_node(is, IfStmt, node);
  2741. lb_open_scope(p); // Scope #1
  2742. if (is->init != nullptr) {
  2743. // TODO(bill): Should this have a separate block to begin with?
  2744. #if 1
  2745. lbBlock *init = lb_create_block(p, "if.init");
  2746. lb_emit_jump(p, init);
  2747. lb_start_block(p, init);
  2748. #endif
  2749. lb_build_stmt(p, is->init);
  2750. }
  2751. lbBlock *then = lb_create_block(p, "if.then");
  2752. lbBlock *done = lb_create_block(p, "if.done");
  2753. lbBlock *else_ = done;
  2754. if (is->else_stmt != nullptr) {
  2755. else_ = lb_create_block(p, "if.else");
  2756. }
  2757. lb_build_cond(p, is->cond, then, else_);
  2758. lb_start_block(p, then);
  2759. if (is->label != nullptr) {
  2760. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  2761. tl->is_block = true;
  2762. }
  2763. lb_build_stmt(p, is->body);
  2764. lb_emit_jump(p, done);
  2765. if (is->else_stmt != nullptr) {
  2766. lb_start_block(p, else_);
  2767. lb_open_scope(p);
  2768. lb_build_stmt(p, is->else_stmt);
  2769. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2770. lb_emit_jump(p, done);
  2771. }
  2772. lb_start_block(p, done);
  2773. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2774. case_end;
  2775. case_ast_node(fs, ForStmt, node);
  2776. lb_open_scope(p); // Open Scope here
  2777. if (fs->init != nullptr) {
  2778. #if 1
  2779. lbBlock *init = lb_create_block(p, "for.init");
  2780. lb_emit_jump(p, init);
  2781. lb_start_block(p, init);
  2782. #endif
  2783. lb_build_stmt(p, fs->init);
  2784. }
  2785. lbBlock *body = lb_create_block(p, "for.body");
  2786. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  2787. lbBlock *loop = body;
  2788. if (fs->cond != nullptr) {
  2789. loop = lb_create_block(p, "for.loop");
  2790. }
  2791. lbBlock *post = loop;
  2792. if (fs->post != nullptr) {
  2793. post = lb_create_block(p, "for.post");
  2794. }
  2795. lb_emit_jump(p, loop);
  2796. lb_start_block(p, loop);
  2797. if (loop != body) {
  2798. lb_build_cond(p, fs->cond, body, done);
  2799. lb_start_block(p, body);
  2800. }
  2801. lb_push_target_list(p, fs->label, done, post, nullptr);
  2802. lb_build_stmt(p, fs->body);
  2803. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2804. lb_pop_target_list(p);
  2805. lb_emit_jump(p, post);
  2806. if (fs->post != nullptr) {
  2807. lb_start_block(p, post);
  2808. lb_build_stmt(p, fs->post);
  2809. lb_emit_jump(p, loop);
  2810. }
  2811. lb_start_block(p, done);
  2812. case_end;
  2813. case_ast_node(rs, RangeStmt, node);
  2814. lb_build_range_stmt(p, rs);
  2815. case_end;
  2816. case_ast_node(rs, InlineRangeStmt, node);
  2817. lb_build_inline_range_stmt(p, rs);
  2818. case_end;
  2819. case_ast_node(ss, SwitchStmt, node);
  2820. lb_build_switch_stmt(p, ss);
  2821. case_end;
  2822. case_ast_node(ss, TypeSwitchStmt, node);
  2823. lb_build_type_switch_stmt(p, ss);
  2824. case_end;
  2825. case_ast_node(bs, BranchStmt, node);
  2826. lbBlock *block = nullptr;
  2827. if (bs->label != nullptr) {
  2828. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  2829. switch (bs->token.kind) {
  2830. case Token_break: block = bb.break_; break;
  2831. case Token_continue: block = bb.continue_; break;
  2832. case Token_fallthrough:
  2833. GB_PANIC("fallthrough cannot have a label");
  2834. break;
  2835. }
  2836. } else {
  2837. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  2838. if (t->is_block) {
  2839. continue;
  2840. }
  2841. switch (bs->token.kind) {
  2842. case Token_break: block = t->break_; break;
  2843. case Token_continue: block = t->continue_; break;
  2844. case Token_fallthrough: block = t->fallthrough_; break;
  2845. }
  2846. }
  2847. }
  2848. if (block != nullptr) {
  2849. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  2850. }
  2851. lb_emit_jump(p, block);
  2852. case_end;
  2853. }
  2854. }
  2855. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  2856. cond = lb_emit_conv(p, cond, t_llvm_bool);
  2857. lbValue res = {};
  2858. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  2859. res.type = x.type;
  2860. return res;
  2861. }
  2862. lbValue lb_const_nil(lbModule *m, Type *type) {
  2863. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  2864. return lbValue{v, type};
  2865. }
  2866. lbValue lb_const_undef(lbModule *m, Type *type) {
  2867. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  2868. return lbValue{v, type};
  2869. }
  2870. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  2871. lbValue res = {};
  2872. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  2873. res.type = type;
  2874. return res;
  2875. }
  2876. lbValue lb_const_string(lbModule *m, String const &value) {
  2877. return lb_const_value(m, t_string, exact_value_string(value));
  2878. }
  2879. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  2880. lbValue res = {};
  2881. res.value = LLVMConstInt(lb_type(m, type), value, false);
  2882. res.type = type;
  2883. return res;
  2884. }
  2885. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  2886. u32 u = bit_cast<u32>(f);
  2887. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  2888. return LLVMConstBitCast(i, lb_type(m, type));
  2889. }
  2890. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  2891. x = lb_emit_conv(p, x, t);
  2892. y = lb_emit_conv(p, y, t);
  2893. if (is_type_float(t)) {
  2894. gbAllocator a = heap_allocator();
  2895. i64 sz = 8*type_size_of(t);
  2896. auto args = array_make<lbValue>(heap_allocator(), 2);
  2897. args[0] = x;
  2898. args[1] = y;
  2899. switch (sz) {
  2900. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  2901. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  2902. }
  2903. GB_PANIC("Unknown float type");
  2904. }
  2905. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  2906. }
  2907. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  2908. x = lb_emit_conv(p, x, t);
  2909. y = lb_emit_conv(p, y, t);
  2910. if (is_type_float(t)) {
  2911. gbAllocator a = heap_allocator();
  2912. i64 sz = 8*type_size_of(t);
  2913. auto args = array_make<lbValue>(heap_allocator(), 2);
  2914. args[0] = x;
  2915. args[1] = y;
  2916. switch (sz) {
  2917. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  2918. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  2919. }
  2920. GB_PANIC("Unknown float type");
  2921. }
  2922. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  2923. }
  2924. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  2925. lbValue z = {};
  2926. z = lb_emit_max(p, t, x, min);
  2927. z = lb_emit_min(p, t, z, max);
  2928. return z;
  2929. }
  2930. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  2931. HashKey key = hash_string(str);
  2932. LLVMValueRef *found = map_get(&m->const_strings, key);
  2933. if (found != nullptr) {
  2934. LLVMValueRef ptr = *found;
  2935. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  2936. LLVMValueRef values[2] = {ptr, str_len};
  2937. lbValue res = {};
  2938. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  2939. res.type = t_string;
  2940. return res;
  2941. } else {
  2942. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  2943. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  2944. cast(char const *)str.text,
  2945. cast(unsigned)str.len,
  2946. false);
  2947. isize max_len = 7+8+1;
  2948. char *name = gb_alloc_array(heap_allocator(), char, max_len);
  2949. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  2950. len -= 1;
  2951. m->global_array_index++;
  2952. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  2953. LLVMSetInitializer(global_data, data);
  2954. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  2955. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  2956. LLVMValueRef values[2] = {ptr, str_len};
  2957. lbValue res = {};
  2958. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  2959. res.type = t_string;
  2960. map_set(&m->const_strings, key, ptr);
  2961. return res;
  2962. }
  2963. }
  2964. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  2965. HashKey key = hash_string(str);
  2966. LLVMValueRef *found = map_get(&m->const_strings, key);
  2967. if (found != nullptr) {
  2968. LLVMValueRef ptr = *found;
  2969. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  2970. LLVMValueRef values[2] = {ptr, len};
  2971. lbValue res = {};
  2972. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  2973. res.type = t_u8_slice;
  2974. return res;
  2975. } else {
  2976. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  2977. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  2978. cast(char const *)str.text,
  2979. cast(unsigned)str.len,
  2980. false);
  2981. isize max_len = 7+8+1;
  2982. char *name = gb_alloc_array(heap_allocator(), char, max_len);
  2983. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  2984. len -= 1;
  2985. m->global_array_index++;
  2986. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  2987. LLVMSetInitializer(global_data, data);
  2988. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  2989. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  2990. LLVMValueRef values[2] = {ptr, str_len};
  2991. lbValue res = {};
  2992. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  2993. res.type = t_u8_slice;
  2994. map_set(&m->const_strings, key, ptr);
  2995. return res;
  2996. }
  2997. }
  2998. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  2999. isize index = type_info_index(info, type, false);
  3000. if (index >= 0) {
  3001. auto *set = &info->minimum_dependency_type_info_set;
  3002. for_array(i, set->entries) {
  3003. if (set->entries[i].ptr == index) {
  3004. return i+1;
  3005. }
  3006. }
  3007. }
  3008. if (err_on_not_found) {
  3009. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  3010. }
  3011. return -1;
  3012. }
  3013. lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type) {
  3014. type = default_type(type);
  3015. u64 id = cast(u64)lb_type_info_index(m->info, type);
  3016. GB_ASSERT(id >= 0);
  3017. u64 kind = Typeid_Invalid;
  3018. u64 named = is_type_named(type) && type->kind != Type_Basic;
  3019. u64 special = 0;
  3020. u64 reserved = 0;
  3021. Type *bt = base_type(type);
  3022. TypeKind tk = bt->kind;
  3023. switch (tk) {
  3024. case Type_Basic: {
  3025. u32 flags = bt->Basic.flags;
  3026. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  3027. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  3028. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  3029. if (flags & BasicFlag_Float) kind = Typeid_Float;
  3030. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  3031. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  3032. if (flags & BasicFlag_String) kind = Typeid_String;
  3033. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  3034. } break;
  3035. case Type_Pointer: kind = Typeid_Pointer; break;
  3036. case Type_Array: kind = Typeid_Array; break;
  3037. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  3038. case Type_Slice: kind = Typeid_Slice; break;
  3039. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  3040. case Type_Map: kind = Typeid_Map; break;
  3041. case Type_Struct: kind = Typeid_Struct; break;
  3042. case Type_Enum: kind = Typeid_Enum; break;
  3043. case Type_Union: kind = Typeid_Union; break;
  3044. case Type_Tuple: kind = Typeid_Tuple; break;
  3045. case Type_Proc: kind = Typeid_Procedure; break;
  3046. case Type_BitField: kind = Typeid_Bit_Field; break;
  3047. case Type_BitSet: kind = Typeid_Bit_Set; break;
  3048. }
  3049. if (is_type_cstring(type)) {
  3050. special = 1;
  3051. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  3052. special = 1;
  3053. }
  3054. u64 data = 0;
  3055. if (build_context.word_size == 4) {
  3056. data |= (id &~ (1u<<24)) << 0u; // index
  3057. data |= (kind &~ (1u<<5)) << 24u; // kind
  3058. data |= (named &~ (1u<<1)) << 29u; // kind
  3059. data |= (special &~ (1u<<1)) << 30u; // kind
  3060. data |= (reserved &~ (1u<<1)) << 31u; // kind
  3061. } else {
  3062. GB_ASSERT(build_context.word_size == 8);
  3063. data |= (id &~ (1ull<<56)) << 0ul; // index
  3064. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  3065. data |= (named &~ (1ull<<1)) << 61ull; // kind
  3066. data |= (special &~ (1ull<<1)) << 62ull; // kind
  3067. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  3068. }
  3069. lbValue res = {};
  3070. res.value = LLVMConstInt(lb_type(m, typeid_type), data, false);
  3071. res.type = typeid_type;
  3072. return res;
  3073. }
  3074. lbValue lb_type_info(lbModule *m, Type *type) {
  3075. type = default_type(type);
  3076. isize index = lb_type_info_index(m->info, type);
  3077. GB_ASSERT(index >= 0);
  3078. LLVMTypeRef it = lb_type(m, t_int);
  3079. LLVMValueRef indices[2] = {
  3080. LLVMConstInt(it, 0, false),
  3081. LLVMConstInt(it, index, true),
  3082. };
  3083. lbValue value = {};
  3084. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  3085. value.type = t_type_info_ptr;
  3086. return value;
  3087. }
  3088. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) {
  3089. LLVMContextRef ctx = m->ctx;
  3090. type = default_type(type);
  3091. Type *original_type = type;
  3092. lbValue res = {};
  3093. res.type = original_type;
  3094. type = core_type(type);
  3095. value = convert_exact_value_for_type(value, type);
  3096. if (value.kind == ExactValue_Typeid) {
  3097. return lb_typeid(m, value.value_typeid, original_type);
  3098. }
  3099. if (value.kind == ExactValue_Invalid) {
  3100. return lb_const_nil(m, type);
  3101. }
  3102. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  3103. if (is_type_slice(type)) {
  3104. if (value.kind == ExactValue_String) {
  3105. GB_ASSERT(is_type_u8_slice(type));
  3106. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  3107. return res;
  3108. } else {
  3109. ast_node(cl, CompoundLit, value.value_compound);
  3110. isize count = cl->elems.count;
  3111. if (count == 0) {
  3112. return lb_const_nil(m, type);
  3113. }
  3114. count = gb_max(cl->max_count, count);
  3115. Type *elem = base_type(type)->Slice.elem;
  3116. Type *t = alloc_type_array(elem, count);
  3117. lbValue backing_array = lb_const_value(m, t, value);
  3118. isize max_len = 7+8+1;
  3119. char *str = gb_alloc_array(heap_allocator(), char, max_len);
  3120. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  3121. m->global_array_index++;
  3122. String name = make_string(cast(u8 *)str, len-1);
  3123. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  3124. LLVMValueRef global_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  3125. LLVMSetInitializer(global_data, backing_array.value);
  3126. lbValue g = {};
  3127. g.value = global_data;
  3128. g.type = t;
  3129. lb_add_entity(m, e, g);
  3130. lb_add_member(m, name, g);
  3131. {
  3132. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  3133. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3134. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  3135. LLVMValueRef values[2] = {ptr, len};
  3136. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3137. return res;
  3138. }
  3139. }
  3140. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  3141. LLVMValueRef data = LLVMConstStringInContext(ctx,
  3142. cast(char const *)value.value_string.text,
  3143. cast(unsigned)value.value_string.len,
  3144. false);
  3145. res.value = data;
  3146. return res;
  3147. } else if (is_type_array(type) &&
  3148. value.kind != ExactValue_Invalid &&
  3149. value.kind != ExactValue_String &&
  3150. value.kind != ExactValue_Compound) {
  3151. i64 count = type->Array.count;
  3152. Type *elem = type->Array.elem;
  3153. lbValue single_elem = lb_const_value(m, elem, value);
  3154. LLVMValueRef *elems = gb_alloc_array(heap_allocator(), LLVMValueRef, count);
  3155. for (i64 i = 0; i < count; i++) {
  3156. elems[i] = single_elem.value;
  3157. }
  3158. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  3159. return res;
  3160. }
  3161. switch (value.kind) {
  3162. case ExactValue_Invalid:
  3163. res.value = LLVMConstNull(lb_type(m, original_type));
  3164. return res;
  3165. case ExactValue_Bool:
  3166. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  3167. return res;
  3168. case ExactValue_String:
  3169. {
  3170. HashKey key = hash_string(value.value_string);
  3171. LLVMValueRef *found = map_get(&m->const_strings, key);
  3172. if (found != nullptr) {
  3173. LLVMValueRef ptr = *found;
  3174. lbValue res = {};
  3175. res.type = default_type(original_type);
  3176. if (is_type_cstring(res.type)) {
  3177. res.value = ptr;
  3178. } else {
  3179. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  3180. LLVMValueRef values[2] = {ptr, str_len};
  3181. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3182. }
  3183. return res;
  3184. }
  3185. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  3186. LLVMValueRef data = LLVMConstStringInContext(ctx,
  3187. cast(char const *)value.value_string.text,
  3188. cast(unsigned)value.value_string.len,
  3189. false);
  3190. isize max_len = 7+8+1;
  3191. char *str = gb_alloc_array(heap_allocator(), char, max_len);
  3192. isize len = gb_snprintf(str, max_len, "csbs$%x", m->global_array_index);
  3193. len -= 1;
  3194. m->global_array_index++;
  3195. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), str);
  3196. LLVMSetInitializer(global_data, data);
  3197. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3198. if (is_type_cstring(type)) {
  3199. res.value = ptr;
  3200. return res;
  3201. }
  3202. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  3203. LLVMValueRef values[2] = {ptr, str_len};
  3204. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3205. res.type = default_type(original_type);
  3206. map_set(&m->const_strings, key, ptr);
  3207. return res;
  3208. }
  3209. case ExactValue_Integer:
  3210. if (is_type_pointer(type)) {
  3211. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  3212. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  3213. } else {
  3214. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  3215. if (value.value_integer.neg) {
  3216. res.value = LLVMConstNeg(res.value);
  3217. }
  3218. }
  3219. return res;
  3220. case ExactValue_Float:
  3221. if (type_size_of(type) == 4) {
  3222. f32 f = cast(f32)value.value_float;
  3223. res.value = lb_const_f32(m, f, type);
  3224. return res;
  3225. }
  3226. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  3227. return res;
  3228. case ExactValue_Complex:
  3229. {
  3230. LLVMValueRef values[2] = {};
  3231. switch (8*type_size_of(type)) {
  3232. case 64:
  3233. values[0] = lb_const_f32(m, cast(f32)value.value_complex.real);
  3234. values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag);
  3235. break;
  3236. case 128:
  3237. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real);
  3238. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag);
  3239. break;
  3240. }
  3241. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  3242. return res;
  3243. }
  3244. break;
  3245. case ExactValue_Quaternion:
  3246. {
  3247. LLVMValueRef values[4] = {};
  3248. switch (8*type_size_of(type)) {
  3249. case 128:
  3250. // @QuaternionLayout
  3251. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real);
  3252. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag);
  3253. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag);
  3254. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag);
  3255. break;
  3256. case 256:
  3257. // @QuaternionLayout
  3258. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real);
  3259. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag);
  3260. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag);
  3261. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag);
  3262. break;
  3263. }
  3264. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  3265. return res;
  3266. }
  3267. break;
  3268. case ExactValue_Pointer:
  3269. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  3270. return res;
  3271. case ExactValue_Compound:
  3272. if (is_type_slice(type)) {
  3273. return lb_const_value(m, type, value);
  3274. } else if (is_type_array(type)) {
  3275. ast_node(cl, CompoundLit, value.value_compound);
  3276. Type *elem_type = type->Array.elem;
  3277. isize elem_count = cl->elems.count;
  3278. if (elem_count == 0) {
  3279. return lb_const_nil(m, original_type);
  3280. }
  3281. if (cl->elems[0]->kind == Ast_FieldValue) {
  3282. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  3283. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  3284. defer (gb_free(heap_allocator(), values));
  3285. isize value_index = 0;
  3286. for (i64 i = 0; i < type->Array.count; i++) {
  3287. bool found = false;
  3288. for (isize j = 0; j < elem_count; j++) {
  3289. Ast *elem = cl->elems[j];
  3290. ast_node(fv, FieldValue, elem);
  3291. if (is_ast_range(fv->field)) {
  3292. ast_node(ie, BinaryExpr, fv->field);
  3293. TypeAndValue lo_tav = ie->left->tav;
  3294. TypeAndValue hi_tav = ie->right->tav;
  3295. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3296. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3297. TokenKind op = ie->op.kind;
  3298. i64 lo = exact_value_to_i64(lo_tav.value);
  3299. i64 hi = exact_value_to_i64(hi_tav.value);
  3300. if (op == Token_Ellipsis) {
  3301. hi += 1;
  3302. }
  3303. if (lo == i) {
  3304. TypeAndValue tav = fv->value->tav;
  3305. if (tav.mode != Addressing_Constant) {
  3306. break;
  3307. }
  3308. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3309. for (i64 k = lo; k < hi; k++) {
  3310. values[value_index++] = val;
  3311. }
  3312. found = true;
  3313. i += (hi-lo-1);
  3314. break;
  3315. }
  3316. } else {
  3317. TypeAndValue index_tav = fv->field->tav;
  3318. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3319. i64 index = exact_value_to_i64(index_tav.value);
  3320. if (index == i) {
  3321. TypeAndValue tav = fv->value->tav;
  3322. if (tav.mode != Addressing_Constant) {
  3323. break;
  3324. }
  3325. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3326. values[value_index++] = val;
  3327. found = true;
  3328. break;
  3329. }
  3330. }
  3331. }
  3332. if (!found) {
  3333. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  3334. }
  3335. }
  3336. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  3337. return res;
  3338. } else {
  3339. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  3340. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count);
  3341. defer (gb_free(heap_allocator(), values));
  3342. for (isize i = 0; i < elem_count; i++) {
  3343. TypeAndValue tav = cl->elems[i]->tav;
  3344. GB_ASSERT(tav.mode != Addressing_Invalid);
  3345. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3346. }
  3347. for (isize i = elem_count; i < type->Array.count; i++) {
  3348. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3349. }
  3350. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  3351. return res;
  3352. }
  3353. } else if (is_type_enumerated_array(type)) {
  3354. ast_node(cl, CompoundLit, value.value_compound);
  3355. Type *elem_type = type->EnumeratedArray.elem;
  3356. isize elem_count = cl->elems.count;
  3357. if (elem_count == 0) {
  3358. return lb_const_nil(m, original_type);
  3359. }
  3360. if (cl->elems[0]->kind == Ast_FieldValue) {
  3361. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  3362. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  3363. defer (gb_free(heap_allocator(), values));
  3364. isize value_index = 0;
  3365. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  3366. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  3367. for (i64 i = total_lo; i <= total_hi; i++) {
  3368. bool found = false;
  3369. for (isize j = 0; j < elem_count; j++) {
  3370. Ast *elem = cl->elems[j];
  3371. ast_node(fv, FieldValue, elem);
  3372. if (is_ast_range(fv->field)) {
  3373. ast_node(ie, BinaryExpr, fv->field);
  3374. TypeAndValue lo_tav = ie->left->tav;
  3375. TypeAndValue hi_tav = ie->right->tav;
  3376. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3377. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3378. TokenKind op = ie->op.kind;
  3379. i64 lo = exact_value_to_i64(lo_tav.value);
  3380. i64 hi = exact_value_to_i64(hi_tav.value);
  3381. if (op == Token_Ellipsis) {
  3382. hi += 1;
  3383. }
  3384. if (lo == i) {
  3385. TypeAndValue tav = fv->value->tav;
  3386. if (tav.mode != Addressing_Constant) {
  3387. break;
  3388. }
  3389. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3390. for (i64 k = lo; k < hi; k++) {
  3391. values[value_index++] = val;
  3392. }
  3393. found = true;
  3394. i += (hi-lo-1);
  3395. break;
  3396. }
  3397. } else {
  3398. TypeAndValue index_tav = fv->field->tav;
  3399. GB_ASSERT(index_tav.mode == Addressing_Constant);
  3400. i64 index = exact_value_to_i64(index_tav.value);
  3401. if (index == i) {
  3402. TypeAndValue tav = fv->value->tav;
  3403. if (tav.mode != Addressing_Constant) {
  3404. break;
  3405. }
  3406. LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value;
  3407. values[value_index++] = val;
  3408. found = true;
  3409. break;
  3410. }
  3411. }
  3412. }
  3413. if (!found) {
  3414. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  3415. }
  3416. }
  3417. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  3418. return res;
  3419. } else {
  3420. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  3421. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  3422. defer (gb_free(heap_allocator(), values));
  3423. for (isize i = 0; i < elem_count; i++) {
  3424. TypeAndValue tav = cl->elems[i]->tav;
  3425. GB_ASSERT(tav.mode != Addressing_Invalid);
  3426. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3427. }
  3428. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  3429. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3430. }
  3431. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  3432. return res;
  3433. }
  3434. } else if (is_type_simd_vector(type)) {
  3435. ast_node(cl, CompoundLit, value.value_compound);
  3436. Type *elem_type = type->SimdVector.elem;
  3437. isize elem_count = cl->elems.count;
  3438. if (elem_count == 0) {
  3439. return lb_const_nil(m, original_type);
  3440. }
  3441. isize total_elem_count = type->SimdVector.count;
  3442. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, total_elem_count);
  3443. defer (gb_free(heap_allocator(), values));
  3444. for (isize i = 0; i < elem_count; i++) {
  3445. TypeAndValue tav = cl->elems[i]->tav;
  3446. GB_ASSERT(tav.mode != Addressing_Invalid);
  3447. values[i] = lb_const_value(m, elem_type, tav.value).value;
  3448. }
  3449. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  3450. values[i] = LLVMConstNull(lb_type(m, elem_type));
  3451. }
  3452. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  3453. return res;
  3454. } else if (is_type_struct(type)) {
  3455. ast_node(cl, CompoundLit, value.value_compound);
  3456. if (cl->elems.count == 0) {
  3457. return lb_const_nil(m, original_type);
  3458. }
  3459. isize offset = 0;
  3460. if (type->Struct.custom_align > 0) {
  3461. offset = 1;
  3462. }
  3463. isize value_count = type->Struct.fields.count + offset;
  3464. LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, value_count);
  3465. bool *visited = gb_alloc_array(heap_allocator(), bool, value_count);
  3466. defer (gb_free(heap_allocator(), values));
  3467. defer (gb_free(heap_allocator(), visited));
  3468. if (cl->elems.count > 0) {
  3469. if (cl->elems[0]->kind == Ast_FieldValue) {
  3470. isize elem_count = cl->elems.count;
  3471. for (isize i = 0; i < elem_count; i++) {
  3472. ast_node(fv, FieldValue, cl->elems[i]);
  3473. String name = fv->field->Ident.token.string;
  3474. TypeAndValue tav = fv->value->tav;
  3475. GB_ASSERT(tav.mode != Addressing_Invalid);
  3476. Selection sel = lookup_field(type, name, false);
  3477. Entity *f = type->Struct.fields[sel.index[0]];
  3478. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value).value;
  3479. visited[offset+f->Variable.field_index] = true;
  3480. }
  3481. } else {
  3482. for_array(i, cl->elems) {
  3483. Entity *f = type->Struct.fields[i];
  3484. TypeAndValue tav = cl->elems[i]->tav;
  3485. ExactValue val = {};
  3486. if (tav.mode != Addressing_Invalid) {
  3487. val = tav.value;
  3488. }
  3489. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val).value;
  3490. visited[offset+f->Variable.field_index] = true;
  3491. }
  3492. }
  3493. }
  3494. for (isize i = 0; i < type->Struct.fields.count; i++) {
  3495. if (!visited[offset+i]) {
  3496. GB_ASSERT(values[offset+i] == nullptr);
  3497. values[offset+i] = lb_const_nil(m, type->Struct.fields[i]->type).value;
  3498. }
  3499. }
  3500. if (type->Struct.custom_align > 0) {
  3501. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  3502. }
  3503. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  3504. return res;
  3505. } else if (is_type_bit_set(type)) {
  3506. ast_node(cl, CompoundLit, value.value_compound);
  3507. if (cl->elems.count == 0) {
  3508. return lb_const_nil(m, original_type);
  3509. }
  3510. i64 sz = type_size_of(type);
  3511. if (sz == 0) {
  3512. return lb_const_nil(m, original_type);
  3513. }
  3514. u64 bits = 0;
  3515. for_array(i, cl->elems) {
  3516. Ast *e = cl->elems[i];
  3517. GB_ASSERT(e->kind != Ast_FieldValue);
  3518. TypeAndValue tav = e->tav;
  3519. if (tav.mode != Addressing_Constant) {
  3520. continue;
  3521. }
  3522. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  3523. i64 v = big_int_to_i64(&tav.value.value_integer);
  3524. i64 lower = type->BitSet.lower;
  3525. bits |= 1ull<<cast(u64)(v-lower);
  3526. }
  3527. if (is_type_different_to_arch_endianness(type)) {
  3528. i64 size = type_size_of(type);
  3529. switch (size) {
  3530. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  3531. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  3532. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  3533. }
  3534. }
  3535. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  3536. return res;
  3537. } else {
  3538. return lb_const_nil(m, original_type);
  3539. }
  3540. break;
  3541. case ExactValue_Procedure:
  3542. {
  3543. Ast *expr = value.value_procedure;
  3544. GB_ASSERT(expr != nullptr);
  3545. if (expr->kind == Ast_ProcLit) {
  3546. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  3547. }
  3548. }
  3549. break;
  3550. case ExactValue_Typeid:
  3551. return lb_typeid(m, value.value_typeid, original_type);
  3552. }
  3553. return lb_const_nil(m, original_type);
  3554. }
  3555. u64 lb_generate_source_code_location_hash(TokenPos const &pos) {
  3556. u64 h = 0xcbf29ce484222325;
  3557. for (isize i = 0; i < pos.file.len; i++) {
  3558. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  3559. }
  3560. h = h ^ (u64(pos.line) * 0x100000001b3);
  3561. h = h ^ (u64(pos.column) * 0x100000001b3);
  3562. return h;
  3563. }
  3564. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  3565. lbModule *m = p->module;
  3566. LLVMValueRef fields[5] = {};
  3567. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  3568. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  3569. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  3570. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  3571. fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value;
  3572. lbValue res = {};
  3573. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5);
  3574. res.type = t_source_code_location;
  3575. return res;
  3576. }
  3577. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  3578. String proc_name = {};
  3579. if (p->entity) {
  3580. proc_name = p->entity->token.string;
  3581. }
  3582. TokenPos pos = {};
  3583. if (node) {
  3584. pos = ast_token(node).pos;
  3585. }
  3586. return lb_emit_source_code_location(p, proc_name, pos);
  3587. }
  3588. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  3589. switch (op) {
  3590. case Token_Add:
  3591. return x;
  3592. case Token_Not: // Boolean not
  3593. case Token_Xor: // Bitwise not
  3594. case Token_Sub: // Number negation
  3595. break;
  3596. case Token_Pointer:
  3597. GB_PANIC("This should be handled elsewhere");
  3598. break;
  3599. }
  3600. if (is_type_array(x.type)) {
  3601. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  3602. Type *tl = base_type(x.type);
  3603. lbValue val = lb_address_from_load_or_generate_local(p, x);
  3604. GB_ASSERT(is_type_array(type));
  3605. Type *elem_type = base_array_type(type);
  3606. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3607. lbAddr res_addr = lb_add_local_generated(p, type, false);
  3608. lbValue res = lb_addr_get_ptr(p, res_addr);
  3609. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3610. i32 count = cast(i32)tl->Array.count;
  3611. if (inline_array_arith) {
  3612. // inline
  3613. for (i32 i = 0; i < count; i++) {
  3614. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  3615. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  3616. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  3617. }
  3618. } else {
  3619. auto loop_data = lb_loop_start(p, count, t_i32);
  3620. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  3621. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  3622. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  3623. lb_loop_end(p, loop_data);
  3624. }
  3625. return lb_emit_load(p, res);
  3626. }
  3627. if (op == Token_Not) {
  3628. lbValue cmp = {};
  3629. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  3630. cmp.type = x.type;
  3631. return lb_emit_conv(p, cmp, type);
  3632. }
  3633. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3634. Type *platform_type = integer_endian_type_to_platform_type(type);
  3635. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  3636. lbValue res = {};
  3637. res.value = LLVMBuildNeg(p->builder, v.value, "");
  3638. res.type = platform_type;
  3639. return lb_emit_byte_swap(p, res, type);
  3640. }
  3641. lbValue res = {};
  3642. switch (op) {
  3643. case Token_Not: // Boolean not
  3644. case Token_Xor: // Bitwise not
  3645. res.value = LLVMBuildNot(p->builder, x.value, "");
  3646. res.type = x.type;
  3647. return res;
  3648. case Token_Sub: // Number negation
  3649. if (is_type_integer(x.type)) {
  3650. res.value = LLVMBuildNeg(p->builder, x.value, "");
  3651. } else if (is_type_float(x.type)) {
  3652. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  3653. } else {
  3654. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  3655. }
  3656. res.type = x.type;
  3657. return res;
  3658. }
  3659. return res;
  3660. }
  3661. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  3662. lbModule *m = p->module;
  3663. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  3664. lhs = lb_emit_conv(p, lhs, type);
  3665. rhs = lb_emit_conv(p, rhs, type);
  3666. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  3667. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  3668. GB_ASSERT(is_type_array(type));
  3669. Type *elem_type = base_array_type(type);
  3670. lbAddr res = lb_add_local_generated(p, type, false);
  3671. i64 count = base_type(type)->Array.count;
  3672. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  3673. if (inline_array_arith) {
  3674. for (i64 i = 0; i < count; i++) {
  3675. lbValue a = lb_emit_load(p, lb_emit_array_epi(p, x, i));
  3676. lbValue b = lb_emit_load(p, lb_emit_array_epi(p, y, i));
  3677. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  3678. lb_emit_store(p, lb_emit_array_epi(p, res.addr, i), c);
  3679. }
  3680. } else {
  3681. auto loop_data = lb_loop_start(p, count);
  3682. lbValue a = lb_emit_load(p, lb_emit_array_ep(p, x, loop_data.idx));
  3683. lbValue b = lb_emit_load(p, lb_emit_array_ep(p, y, loop_data.idx));
  3684. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  3685. lb_emit_store(p, lb_emit_array_ep(p, res.addr, loop_data.idx), c);
  3686. lb_loop_end(p, loop_data);
  3687. }
  3688. return lb_addr_load(p, res);
  3689. } else if (is_type_complex(type)) {
  3690. lhs = lb_emit_conv(p, lhs, type);
  3691. rhs = lb_emit_conv(p, rhs, type);
  3692. Type *ft = base_complex_elem_type(type);
  3693. if (op == Token_Quo) {
  3694. auto args = array_make<lbValue>(heap_allocator(), 2);
  3695. args[0] = lhs;
  3696. args[1] = rhs;
  3697. switch (type_size_of(ft)) {
  3698. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  3699. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  3700. default: GB_PANIC("Unknown float type"); break;
  3701. }
  3702. }
  3703. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  3704. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  3705. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  3706. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  3707. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  3708. lbValue real = {};
  3709. lbValue imag = {};
  3710. switch (op) {
  3711. case Token_Add:
  3712. real = lb_emit_arith(p, Token_Add, a, c, ft);
  3713. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  3714. break;
  3715. case Token_Sub:
  3716. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  3717. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  3718. break;
  3719. case Token_Mul: {
  3720. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  3721. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  3722. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  3723. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  3724. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  3725. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  3726. break;
  3727. }
  3728. }
  3729. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  3730. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  3731. return lb_addr_load(p, res);
  3732. } else if (is_type_quaternion(type)) {
  3733. lhs = lb_emit_conv(p, lhs, type);
  3734. rhs = lb_emit_conv(p, rhs, type);
  3735. Type *ft = base_complex_elem_type(type);
  3736. if (op == Token_Add || op == Token_Sub) {
  3737. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  3738. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  3739. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  3740. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  3741. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  3742. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  3743. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  3744. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  3745. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  3746. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  3747. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  3748. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  3749. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  3750. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  3751. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  3752. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  3753. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  3754. return lb_addr_load(p, res);
  3755. } else if (op == Token_Mul) {
  3756. auto args = array_make<lbValue>(heap_allocator(), 2);
  3757. args[0] = lhs;
  3758. args[1] = rhs;
  3759. switch (8*type_size_of(ft)) {
  3760. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  3761. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  3762. default: GB_PANIC("Unknown float type"); break;
  3763. }
  3764. } else if (op == Token_Quo) {
  3765. auto args = array_make<lbValue>(heap_allocator(), 2);
  3766. args[0] = lhs;
  3767. args[1] = rhs;
  3768. switch (8*type_size_of(ft)) {
  3769. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  3770. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  3771. default: GB_PANIC("Unknown float type"); break;
  3772. }
  3773. }
  3774. }
  3775. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  3776. switch (op) {
  3777. case Token_AndNot:
  3778. case Token_And:
  3779. case Token_Or:
  3780. case Token_Xor:
  3781. goto handle_op;
  3782. }
  3783. Type *platform_type = integer_endian_type_to_platform_type(type);
  3784. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  3785. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  3786. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  3787. return lb_emit_byte_swap(p, res, type);
  3788. }
  3789. handle_op:
  3790. lhs = lb_emit_conv(p, lhs, type);
  3791. rhs = lb_emit_conv(p, rhs, type);
  3792. lbValue res = {};
  3793. res.type = type;
  3794. switch (op) {
  3795. case Token_Add:
  3796. if (is_type_float(type)) {
  3797. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  3798. return res;
  3799. }
  3800. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  3801. return res;
  3802. case Token_Sub:
  3803. if (is_type_float(type)) {
  3804. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  3805. return res;
  3806. }
  3807. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  3808. return res;
  3809. case Token_Mul:
  3810. if (is_type_float(type)) {
  3811. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  3812. return res;
  3813. }
  3814. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  3815. return res;
  3816. case Token_Quo:
  3817. if (is_type_float(type)) {
  3818. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  3819. return res;
  3820. } else if (is_type_unsigned(type)) {
  3821. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  3822. return res;
  3823. }
  3824. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  3825. return res;
  3826. case Token_Mod:
  3827. if (is_type_float(type)) {
  3828. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  3829. return res;
  3830. } else if (is_type_unsigned(type)) {
  3831. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  3832. return res;
  3833. }
  3834. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  3835. return res;
  3836. case Token_ModMod:
  3837. if (is_type_unsigned(type)) {
  3838. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  3839. return res;
  3840. } else {
  3841. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  3842. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  3843. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  3844. res.value = c;
  3845. return res;
  3846. }
  3847. case Token_And:
  3848. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  3849. return res;
  3850. case Token_Or:
  3851. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  3852. return res;
  3853. case Token_Xor:
  3854. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  3855. return res;
  3856. case Token_Shl:
  3857. rhs = lb_emit_conv(p, rhs, lhs.type);
  3858. res.value = LLVMBuildShl(p->builder, lhs.value, rhs.value, "");
  3859. return res;
  3860. case Token_Shr:
  3861. if (is_type_unsigned(type)) {
  3862. res.value = LLVMBuildLShr(p->builder, lhs.value, rhs.value, "");
  3863. return res;
  3864. }
  3865. rhs = lb_emit_conv(p, rhs, lhs.type);
  3866. res.value = LLVMBuildAShr(p->builder, lhs.value, rhs.value, "");
  3867. return res;
  3868. case Token_AndNot:
  3869. {
  3870. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  3871. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  3872. return res;
  3873. }
  3874. break;
  3875. }
  3876. GB_PANIC("unhandled operator of lb_emit_arith");
  3877. return {};
  3878. }
  3879. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  3880. ast_node(be, BinaryExpr, expr);
  3881. TypeAndValue tv = type_and_value_of_expr(expr);
  3882. switch (be->op.kind) {
  3883. case Token_Add:
  3884. case Token_Sub:
  3885. case Token_Mul:
  3886. case Token_Quo:
  3887. case Token_Mod:
  3888. case Token_ModMod:
  3889. case Token_And:
  3890. case Token_Or:
  3891. case Token_Xor:
  3892. case Token_AndNot:
  3893. case Token_Shl:
  3894. case Token_Shr: {
  3895. Type *type = default_type(tv.type);
  3896. lbValue left = lb_build_expr(p, be->left);
  3897. lbValue right = lb_build_expr(p, be->right);
  3898. return lb_emit_arith(p, be->op.kind, left, right, type);
  3899. }
  3900. case Token_CmpEq:
  3901. case Token_NotEq:
  3902. case Token_Lt:
  3903. case Token_LtEq:
  3904. case Token_Gt:
  3905. case Token_GtEq:
  3906. {
  3907. lbValue left = lb_build_expr(p, be->left);
  3908. Type *type = default_type(tv.type);
  3909. lbValue right = lb_build_expr(p, be->right);
  3910. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  3911. return lb_emit_conv(p, cmp, type);
  3912. }
  3913. case Token_CmpAnd:
  3914. case Token_CmpOr:
  3915. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  3916. case Token_in:
  3917. case Token_not_in:
  3918. {
  3919. lbValue left = lb_build_expr(p, be->left);
  3920. Type *type = default_type(tv.type);
  3921. lbValue right = lb_build_expr(p, be->right);
  3922. Type *rt = base_type(right.type);
  3923. switch (rt->kind) {
  3924. case Type_Map:
  3925. {
  3926. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  3927. lbValue h = lb_gen_map_header(p, addr, rt);
  3928. lbValue key = lb_gen_map_key(p, left, rt->Map.key);
  3929. auto args = array_make<lbValue>(heap_allocator(), 2);
  3930. args[0] = h;
  3931. args[1] = key;
  3932. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  3933. if (be->op.kind == Token_in) {
  3934. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  3935. } else {
  3936. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  3937. }
  3938. }
  3939. break;
  3940. case Type_BitSet:
  3941. {
  3942. Type *key_type = rt->BitSet.elem;
  3943. GB_ASSERT(are_types_identical(left.type, key_type));
  3944. Type *it = bit_set_to_int(rt);
  3945. left = lb_emit_conv(p, left, it);
  3946. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  3947. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  3948. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  3949. bit = lb_emit_conv(p, bit, it);
  3950. lbValue old_value = lb_emit_transmute(p, right, it);
  3951. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  3952. if (be->op.kind == Token_in) {
  3953. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  3954. } else {
  3955. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  3956. }
  3957. }
  3958. break;
  3959. default:
  3960. GB_PANIC("Invalid 'in' type");
  3961. }
  3962. break;
  3963. }
  3964. break;
  3965. default:
  3966. GB_PANIC("Invalid binary expression");
  3967. break;
  3968. }
  3969. return {};
  3970. }
  3971. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  3972. Type *prev_src = src;
  3973. // Type *prev_dst = dst;
  3974. src = base_type(type_deref(src));
  3975. // dst = base_type(type_deref(dst));
  3976. bool src_is_ptr = src != prev_src;
  3977. // bool dst_is_ptr = dst != prev_dst;
  3978. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  3979. for_array(i, src->Struct.fields) {
  3980. Entity *f = src->Struct.fields[i];
  3981. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  3982. if (are_types_identical(dst, f->type)) {
  3983. return f->token.string;
  3984. }
  3985. if (src_is_ptr && is_type_pointer(dst)) {
  3986. if (are_types_identical(type_deref(dst), f->type)) {
  3987. return f->token.string;
  3988. }
  3989. }
  3990. if (is_type_struct(f->type)) {
  3991. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  3992. if (name.len > 0) {
  3993. return name;
  3994. }
  3995. }
  3996. }
  3997. }
  3998. return str_lit("");
  3999. }
  4000. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  4001. lbModule *m = p->module;
  4002. t = reduce_tuple_to_single_type(t);
  4003. Type *src_type = value.type;
  4004. if (are_types_identical(t, src_type)) {
  4005. return value;
  4006. }
  4007. Type *src = core_type(src_type);
  4008. Type *dst = core_type(t);
  4009. if (is_type_untyped_nil(src)) {
  4010. return lb_const_nil(m, t);
  4011. }
  4012. if (is_type_untyped_undef(src)) {
  4013. return lb_const_undef(m, t);
  4014. }
  4015. if (LLVMIsConstant(value.value)) {
  4016. if (is_type_any(dst)) {
  4017. Type *st = default_type(src_type);
  4018. lbAddr default_value = lb_add_local_generated(p, st, false);
  4019. lb_addr_store(p, default_value, value);
  4020. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  4021. lbValue id = lb_typeid(m, st);
  4022. lbAddr res = lb_add_local_generated(p, t, false);
  4023. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  4024. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  4025. lb_emit_store(p, a0, data);
  4026. lb_emit_store(p, a1, id);
  4027. return lb_addr_load(p, res);
  4028. } else if (dst->kind == Type_Basic) {
  4029. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  4030. String str = lb_get_const_string(m, value);
  4031. lbValue res = {};
  4032. res.type = t;
  4033. res.value = llvm_cstring(m, str);
  4034. return res;
  4035. }
  4036. // if (is_type_float(dst)) {
  4037. // return value;
  4038. // } else if (is_type_integer(dst)) {
  4039. // return value;
  4040. // }
  4041. // ExactValue ev = value->Constant.value;
  4042. // if (is_type_float(dst)) {
  4043. // ev = exact_value_to_float(ev);
  4044. // } else if (is_type_complex(dst)) {
  4045. // ev = exact_value_to_complex(ev);
  4046. // } else if (is_type_quaternion(dst)) {
  4047. // ev = exact_value_to_quaternion(ev);
  4048. // } else if (is_type_string(dst)) {
  4049. // // Handled elsewhere
  4050. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  4051. // } else if (is_type_integer(dst)) {
  4052. // ev = exact_value_to_integer(ev);
  4053. // } else if (is_type_pointer(dst)) {
  4054. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  4055. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  4056. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  4057. // }
  4058. // return lb_const_value(p->module, t, ev);
  4059. }
  4060. }
  4061. if (are_types_identical(src, dst)) {
  4062. if (!are_types_identical(src_type, t)) {
  4063. return lb_emit_transmute(p, value, t);
  4064. }
  4065. return value;
  4066. }
  4067. // bool <-> llvm bool
  4068. if (is_type_boolean(src) && dst == t_llvm_bool) {
  4069. lbValue res = {};
  4070. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  4071. res.type = dst;
  4072. return res;
  4073. }
  4074. if (src == t_llvm_bool && is_type_boolean(dst)) {
  4075. lbValue res = {};
  4076. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  4077. res.type = dst;
  4078. return res;
  4079. }
  4080. // integer -> integer
  4081. if (is_type_integer(src) && is_type_integer(dst)) {
  4082. GB_ASSERT(src->kind == Type_Basic &&
  4083. dst->kind == Type_Basic);
  4084. i64 sz = type_size_of(default_type(src));
  4085. i64 dz = type_size_of(default_type(dst));
  4086. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  4087. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  4088. value = lb_emit_byte_swap(p, value, platform_src_type);
  4089. }
  4090. LLVMOpcode op = LLVMTrunc;
  4091. if (dz < sz) {
  4092. op = LLVMTrunc;
  4093. } else if (dz == sz) {
  4094. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  4095. // NOTE(bill): Copy the value just for type correctness
  4096. op = LLVMBitCast;
  4097. } else if (dz > sz) {
  4098. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  4099. }
  4100. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  4101. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  4102. lbValue res = {};
  4103. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  4104. res.type = t;
  4105. return lb_emit_byte_swap(p, res, t);
  4106. } else {
  4107. lbValue res = {};
  4108. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  4109. res.type = t;
  4110. return res;
  4111. }
  4112. }
  4113. // boolean -> boolean/integer
  4114. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  4115. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  4116. lbValue res = {};
  4117. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  4118. res.type = t;
  4119. return res;
  4120. }
  4121. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  4122. return lb_emit_transmute(p, value, dst);
  4123. }
  4124. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  4125. return lb_emit_transmute(p, value, dst);
  4126. }
  4127. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  4128. return lb_emit_transmute(p, value, dst);
  4129. }
  4130. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  4131. return lb_emit_transmute(p, value, dst);
  4132. }
  4133. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  4134. lbValue c = lb_emit_conv(p, value, t_cstring);
  4135. auto args = array_make<lbValue>(heap_allocator(), 1);
  4136. args[0] = c;
  4137. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  4138. return lb_emit_conv(p, s, dst);
  4139. }
  4140. // integer -> boolean
  4141. if (is_type_integer(src) && is_type_boolean(dst)) {
  4142. lbValue res = {};
  4143. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  4144. res.type = t_llvm_bool;
  4145. return lb_emit_conv(p, res, t);
  4146. }
  4147. // float -> float
  4148. if (is_type_float(src) && is_type_float(dst)) {
  4149. gbAllocator a = heap_allocator();
  4150. i64 sz = type_size_of(src);
  4151. i64 dz = type_size_of(dst);
  4152. lbValue res = {};
  4153. res.type = t;
  4154. if (dz >= sz) {
  4155. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  4156. } else {
  4157. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  4158. }
  4159. return res;
  4160. }
  4161. if (is_type_complex(src) && is_type_complex(dst)) {
  4162. Type *ft = base_complex_elem_type(dst);
  4163. lbAddr gen = lb_add_local_generated(p, dst, false);
  4164. lbValue gp = lb_addr_get_ptr(p, gen);
  4165. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4166. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4167. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  4168. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  4169. return lb_addr_load(p, gen);
  4170. }
  4171. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  4172. // @QuaternionLayout
  4173. Type *ft = base_complex_elem_type(dst);
  4174. lbAddr gen = lb_add_local_generated(p, dst, false);
  4175. lbValue gp = lb_addr_get_ptr(p, gen);
  4176. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4177. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4178. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  4179. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  4180. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  4181. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  4182. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  4183. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  4184. return lb_addr_load(p, gen);
  4185. }
  4186. if (is_type_float(src) && is_type_complex(dst)) {
  4187. Type *ft = base_complex_elem_type(dst);
  4188. lbAddr gen = lb_add_local_generated(p, dst, true);
  4189. lbValue gp = lb_addr_get_ptr(p, gen);
  4190. lbValue real = lb_emit_conv(p, value, ft);
  4191. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  4192. return lb_addr_load(p, gen);
  4193. }
  4194. if (is_type_float(src) && is_type_quaternion(dst)) {
  4195. Type *ft = base_complex_elem_type(dst);
  4196. lbAddr gen = lb_add_local_generated(p, dst, true);
  4197. lbValue gp = lb_addr_get_ptr(p, gen);
  4198. lbValue real = lb_emit_conv(p, value, ft);
  4199. // @QuaternionLayout
  4200. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  4201. return lb_addr_load(p, gen);
  4202. }
  4203. if (is_type_complex(src) && is_type_quaternion(dst)) {
  4204. Type *ft = base_complex_elem_type(dst);
  4205. lbAddr gen = lb_add_local_generated(p, dst, true);
  4206. lbValue gp = lb_addr_get_ptr(p, gen);
  4207. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  4208. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  4209. // @QuaternionLayout
  4210. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  4211. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  4212. return lb_addr_load(p, gen);
  4213. }
  4214. // float <-> integer
  4215. if (is_type_float(src) && is_type_integer(dst)) {
  4216. lbValue res = {};
  4217. res.type = t;
  4218. if (is_type_unsigned(dst)) {
  4219. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  4220. } else {
  4221. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  4222. }
  4223. return res;
  4224. }
  4225. if (is_type_integer(src) && is_type_float(dst)) {
  4226. lbValue res = {};
  4227. res.type = t;
  4228. if (is_type_unsigned(src)) {
  4229. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  4230. } else {
  4231. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  4232. }
  4233. return res;
  4234. }
  4235. // Pointer <-> uintptr
  4236. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4237. lbValue res = {};
  4238. res.type = t;
  4239. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4240. return res;
  4241. }
  4242. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4243. lbValue res = {};
  4244. res.type = t;
  4245. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4246. return res;
  4247. }
  4248. #if 1
  4249. if (is_type_union(dst)) {
  4250. for_array(i, dst->Union.variants) {
  4251. Type *vt = dst->Union.variants[i];
  4252. if (are_types_identical(vt, src_type)) {
  4253. lbAddr parent = lb_add_local_generated(p, t, true);
  4254. lb_emit_store_union_variant(p, parent.addr, value, vt);
  4255. return lb_addr_load(p, parent);
  4256. }
  4257. }
  4258. }
  4259. #endif
  4260. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  4261. // subtype polymorphism casting
  4262. if (check_is_assignable_to_using_subtype(src_type, t)) {
  4263. Type *st = type_deref(src_type);
  4264. Type *pst = st;
  4265. st = type_deref(st);
  4266. bool st_is_ptr = is_type_pointer(src_type);
  4267. st = base_type(st);
  4268. Type *dt = t;
  4269. bool dt_is_ptr = type_deref(dt) != dt;
  4270. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  4271. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  4272. if (field_name.len > 0) {
  4273. // NOTE(bill): It can be casted
  4274. Selection sel = lookup_field(st, field_name, false, true);
  4275. if (sel.entity != nullptr) {
  4276. if (st_is_ptr) {
  4277. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  4278. Type *rt = res.type;
  4279. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4280. res = lb_emit_load(p, res);
  4281. }
  4282. return res;
  4283. } else {
  4284. if (is_type_pointer(value.type)) {
  4285. Type *rt = value.type;
  4286. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  4287. value = lb_emit_load(p, value);
  4288. } else {
  4289. value = lb_emit_deep_field_gep(p, value, sel);
  4290. return lb_emit_load(p, value);
  4291. }
  4292. }
  4293. return lb_emit_deep_field_ev(p, value, sel);
  4294. }
  4295. } else {
  4296. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  4297. }
  4298. }
  4299. }
  4300. // Pointer <-> Pointer
  4301. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4302. lbValue res = {};
  4303. res.type = t;
  4304. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4305. return res;
  4306. }
  4307. // proc <-> proc
  4308. if (is_type_proc(src) && is_type_proc(dst)) {
  4309. lbValue res = {};
  4310. res.type = t;
  4311. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4312. return res;
  4313. }
  4314. // pointer -> proc
  4315. if (is_type_pointer(src) && is_type_proc(dst)) {
  4316. lbValue res = {};
  4317. res.type = t;
  4318. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4319. return res;
  4320. }
  4321. // proc -> pointer
  4322. if (is_type_proc(src) && is_type_pointer(dst)) {
  4323. lbValue res = {};
  4324. res.type = t;
  4325. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  4326. return res;
  4327. }
  4328. // []byte/[]u8 <-> string
  4329. if (is_type_u8_slice(src) && is_type_string(dst)) {
  4330. return lb_emit_transmute(p, value, t);
  4331. }
  4332. if (is_type_string(src) && is_type_u8_slice(dst)) {
  4333. return lb_emit_transmute(p, value, t);
  4334. }
  4335. if (is_type_array(dst)) {
  4336. Type *elem = dst->Array.elem;
  4337. lbValue e = lb_emit_conv(p, value, elem);
  4338. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4339. lbAddr v = lb_add_local_generated(p, t, false);
  4340. isize index_count = cast(isize)dst->Array.count;
  4341. for (isize i = 0; i < index_count; i++) {
  4342. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  4343. lb_emit_store(p, elem, e);
  4344. }
  4345. return lb_addr_load(p, v);
  4346. }
  4347. if (is_type_any(dst)) {
  4348. if (is_type_untyped_nil(src)) {
  4349. return lb_const_nil(p->module, t);
  4350. }
  4351. if (is_type_untyped_undef(src)) {
  4352. return lb_const_undef(p->module, t);
  4353. }
  4354. lbAddr result = lb_add_local_generated(p, t, true);
  4355. Type *st = default_type(src_type);
  4356. lbValue data = lb_address_from_load_or_generate_local(p, value);
  4357. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  4358. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  4359. data = lb_emit_conv(p, data, t_rawptr);
  4360. lbValue id = lb_typeid(p->module, st);
  4361. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  4362. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  4363. lb_emit_store(p, any_data, data);
  4364. lb_emit_store(p, any_id, id);
  4365. return lb_addr_load(p, result);
  4366. }
  4367. if (is_type_untyped(src)) {
  4368. if (is_type_string(src) && is_type_string(dst)) {
  4369. lbAddr result = lb_add_local_generated(p, t, false);
  4370. lb_addr_store(p, result, value);
  4371. return lb_addr_load(p, result);
  4372. }
  4373. }
  4374. gb_printf_err("%.*s\n", LIT(p->name));
  4375. gb_printf_err("lb_emit_conv: src -> dst\n");
  4376. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  4377. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  4378. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  4379. gb_printf_err("Not Identical %p != %p\n", src, dst);
  4380. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  4381. type_to_string(src_type), type_to_string(t),
  4382. LIT(p->name));
  4383. return {};
  4384. }
  4385. bool lb_is_type_aggregate(Type *t) {
  4386. t = base_type(t);
  4387. switch (t->kind) {
  4388. case Type_Basic:
  4389. switch (t->Basic.kind) {
  4390. case Basic_string:
  4391. case Basic_any:
  4392. return true;
  4393. // case Basic_complex32:
  4394. case Basic_complex64:
  4395. case Basic_complex128:
  4396. case Basic_quaternion128:
  4397. case Basic_quaternion256:
  4398. return true;
  4399. }
  4400. break;
  4401. case Type_Pointer:
  4402. return false;
  4403. case Type_Array:
  4404. case Type_Slice:
  4405. case Type_Struct:
  4406. case Type_Union:
  4407. case Type_Tuple:
  4408. case Type_DynamicArray:
  4409. case Type_Map:
  4410. case Type_BitField:
  4411. case Type_SimdVector:
  4412. return true;
  4413. case Type_Named:
  4414. return lb_is_type_aggregate(t->Named.base);
  4415. }
  4416. return false;
  4417. }
  4418. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  4419. Type *src_type = value.type;
  4420. if (are_types_identical(t, src_type)) {
  4421. return value;
  4422. }
  4423. lbValue res = {};
  4424. res.type = t;
  4425. Type *src = base_type(src_type);
  4426. Type *dst = base_type(t);
  4427. lbModule *m = p->module;
  4428. i64 sz = type_size_of(src);
  4429. i64 dz = type_size_of(dst);
  4430. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  4431. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  4432. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  4433. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4434. return res;
  4435. }
  4436. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  4437. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4438. return res;
  4439. }
  4440. if (is_type_uintptr(src) && is_type_proc(dst)) {
  4441. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4442. return res;
  4443. }
  4444. if (is_type_proc(src) && is_type_uintptr(dst)) {
  4445. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4446. return res;
  4447. }
  4448. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  4449. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  4450. return res;
  4451. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  4452. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  4453. return res;
  4454. }
  4455. if (is_type_pointer(src) && is_type_pointer(dst)) {
  4456. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  4457. return res;
  4458. }
  4459. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  4460. lbValue s = lb_address_from_load_or_generate_local(p, value);
  4461. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  4462. return lb_emit_load(p, d);
  4463. }
  4464. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  4465. // GB_PANIC("lb_emit_transmute");
  4466. return res;
  4467. }
  4468. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  4469. GB_ASSERT(addr.kind == lbAddr_Context);
  4470. GB_ASSERT(addr.ctx.sel.index.count == 0);
  4471. lbModule *m = p->module;
  4472. gbAllocator a = heap_allocator();
  4473. auto args = array_make<lbValue>(a, 1);
  4474. args[0] = addr.addr;
  4475. lb_emit_runtime_call(p, "__init_context", args);
  4476. }
  4477. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  4478. ctx.kind = lbAddr_Context;
  4479. lbContextData cd = {ctx, p->scope_index};
  4480. array_add(&p->context_stack, cd);
  4481. }
  4482. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  4483. if (p->context_stack.count > 0) {
  4484. return p->context_stack[p->context_stack.count-1].ctx;
  4485. }
  4486. lbAddr c = lb_add_local_generated(p, t_context, false);
  4487. c.kind = lbAddr_Context;
  4488. lb_push_context_onto_stack(p, c);
  4489. lb_addr_store(p, c, lb_addr_load(p, p->module->global_default_context));
  4490. lb_emit_init_context(p, c);
  4491. return c;
  4492. }
  4493. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  4494. if (LLVMIsALoadInst(value.value)) {
  4495. lbValue res = {};
  4496. res.value = LLVMGetOperand(value.value, 0);
  4497. res.type = alloc_type_pointer(value.type);
  4498. return res;
  4499. }
  4500. GB_ASSERT(is_type_typed(value.type));
  4501. lbAddr res = lb_add_local_generated(p, value.type, false);
  4502. lb_addr_store(p, res, value);
  4503. return res.addr;
  4504. }
  4505. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  4506. i64 type_alignment = type_align_of(new_type);
  4507. if (alignment < type_alignment) {
  4508. alignment = type_alignment;
  4509. }
  4510. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  4511. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  4512. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  4513. lb_addr_store(p, ptr, val);
  4514. ptr.kind = lbAddr_Context;
  4515. return ptr.addr;
  4516. }
  4517. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  4518. gbAllocator a = heap_allocator();
  4519. GB_ASSERT(is_type_pointer(s.type));
  4520. Type *t = base_type(type_deref(s.type));
  4521. Type *result_type = nullptr;
  4522. if (t->kind == Type_Opaque) {
  4523. t = t->Opaque.elem;
  4524. }
  4525. if (is_type_struct(t)) {
  4526. result_type = t->Struct.fields[index]->type;
  4527. } else if (is_type_union(t)) {
  4528. GB_ASSERT(index == -1);
  4529. return lb_emit_union_tag_ptr(p, s);
  4530. } else if (is_type_tuple(t)) {
  4531. GB_ASSERT(t->Tuple.variables.count > 0);
  4532. result_type = t->Tuple.variables[index]->type;
  4533. } else if (is_type_complex(t)) {
  4534. Type *ft = base_complex_elem_type(t);
  4535. switch (index) {
  4536. case 0: result_type = ft; break;
  4537. case 1: result_type = ft; break;
  4538. }
  4539. } else if (is_type_quaternion(t)) {
  4540. Type *ft = base_complex_elem_type(t);
  4541. switch (index) {
  4542. case 0: result_type = ft; break;
  4543. case 1: result_type = ft; break;
  4544. case 2: result_type = ft; break;
  4545. case 3: result_type = ft; break;
  4546. }
  4547. } else if (is_type_slice(t)) {
  4548. switch (index) {
  4549. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  4550. case 1: result_type = t_int; break;
  4551. }
  4552. } else if (is_type_string(t)) {
  4553. switch (index) {
  4554. case 0: result_type = t_u8_ptr; break;
  4555. case 1: result_type = t_int; break;
  4556. }
  4557. } else if (is_type_any(t)) {
  4558. switch (index) {
  4559. case 0: result_type = t_rawptr; break;
  4560. case 1: result_type = t_typeid; break;
  4561. }
  4562. } else if (is_type_dynamic_array(t)) {
  4563. switch (index) {
  4564. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  4565. case 1: result_type = t_int; break;
  4566. case 2: result_type = t_int; break;
  4567. case 3: result_type = t_allocator; break;
  4568. }
  4569. } else if (is_type_map(t)) {
  4570. init_map_internal_types(t);
  4571. Type *itp = alloc_type_pointer(t->Map.internal_type);
  4572. s = lb_emit_transmute(p, s, itp);
  4573. Type *gst = t->Map.internal_type;
  4574. GB_ASSERT(gst->kind == Type_Struct);
  4575. switch (index) {
  4576. case 0: result_type = gst->Struct.fields[0]->type; break;
  4577. case 1: result_type = gst->Struct.fields[1]->type; break;
  4578. }
  4579. } else if (is_type_array(t)) {
  4580. return lb_emit_array_epi(p, s, index);
  4581. } else {
  4582. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  4583. }
  4584. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  4585. lbValue res = {};
  4586. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  4587. res.type = alloc_type_pointer(result_type);
  4588. return res;
  4589. }
  4590. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  4591. if (LLVMIsALoadInst(s.value)) {
  4592. lbValue res = {};
  4593. res.value = LLVMGetOperand(s.value, 0);
  4594. res.type = alloc_type_pointer(s.type);
  4595. lbValue ptr = lb_emit_struct_ep(p, res, index);
  4596. return lb_emit_load(p, ptr);
  4597. }
  4598. gbAllocator a = heap_allocator();
  4599. Type *t = base_type(s.type);
  4600. Type *result_type = nullptr;
  4601. switch (t->kind) {
  4602. case Type_Basic:
  4603. switch (t->Basic.kind) {
  4604. case Basic_string:
  4605. switch (index) {
  4606. case 0: result_type = t_u8_ptr; break;
  4607. case 1: result_type = t_int; break;
  4608. }
  4609. break;
  4610. case Basic_any:
  4611. switch (index) {
  4612. case 0: result_type = t_rawptr; break;
  4613. case 1: result_type = t_typeid; break;
  4614. }
  4615. break;
  4616. case Basic_complex64: case Basic_complex128:
  4617. {
  4618. Type *ft = base_complex_elem_type(t);
  4619. switch (index) {
  4620. case 0: result_type = ft; break;
  4621. case 1: result_type = ft; break;
  4622. }
  4623. break;
  4624. }
  4625. case Basic_quaternion128: case Basic_quaternion256:
  4626. {
  4627. Type *ft = base_complex_elem_type(t);
  4628. switch (index) {
  4629. case 0: result_type = ft; break;
  4630. case 1: result_type = ft; break;
  4631. case 2: result_type = ft; break;
  4632. case 3: result_type = ft; break;
  4633. }
  4634. break;
  4635. }
  4636. }
  4637. break;
  4638. case Type_Struct:
  4639. result_type = t->Struct.fields[index]->type;
  4640. break;
  4641. case Type_Union:
  4642. GB_ASSERT(index == -1);
  4643. // return lb_emit_union_tag_value(p, s);
  4644. GB_PANIC("lb_emit_union_tag_value");
  4645. case Type_Tuple:
  4646. GB_ASSERT(t->Tuple.variables.count > 0);
  4647. result_type = t->Tuple.variables[index]->type;
  4648. if (t->Tuple.variables.count == 1) {
  4649. return s;
  4650. }
  4651. break;
  4652. case Type_Slice:
  4653. switch (index) {
  4654. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  4655. case 1: result_type = t_int; break;
  4656. }
  4657. break;
  4658. case Type_DynamicArray:
  4659. switch (index) {
  4660. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  4661. case 1: result_type = t_int; break;
  4662. case 2: result_type = t_int; break;
  4663. case 3: result_type = t_allocator; break;
  4664. }
  4665. break;
  4666. case Type_Map:
  4667. {
  4668. init_map_internal_types(t);
  4669. Type *gst = t->Map.generated_struct_type;
  4670. switch (index) {
  4671. case 0: result_type = gst->Struct.fields[0]->type; break;
  4672. case 1: result_type = gst->Struct.fields[1]->type; break;
  4673. }
  4674. }
  4675. break;
  4676. case Type_Array:
  4677. result_type = t->Array.elem;
  4678. break;
  4679. default:
  4680. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  4681. break;
  4682. }
  4683. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  4684. lbValue res = {};
  4685. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  4686. res.type = result_type;
  4687. return res;
  4688. }
  4689. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  4690. GB_ASSERT(sel.index.count > 0);
  4691. Type *type = type_deref(e.type);
  4692. gbAllocator a = heap_allocator();
  4693. for_array(i, sel.index) {
  4694. i32 index = cast(i32)sel.index[i];
  4695. if (is_type_pointer(type)) {
  4696. type = type_deref(type);
  4697. e = lb_emit_load(p, e);
  4698. }
  4699. type = core_type(type);
  4700. if (type->kind == Type_Opaque) {
  4701. type = type->Opaque.elem;
  4702. }
  4703. if (is_type_quaternion(type)) {
  4704. e = lb_emit_struct_ep(p, e, index);
  4705. } else if (is_type_raw_union(type)) {
  4706. type = type->Struct.fields[index]->type;
  4707. GB_ASSERT(is_type_pointer(e.type));
  4708. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  4709. } else if (is_type_struct(type)) {
  4710. type = type->Struct.fields[index]->type;
  4711. e = lb_emit_struct_ep(p, e, index);
  4712. } else if (type->kind == Type_Union) {
  4713. GB_ASSERT(index == -1);
  4714. type = t_type_info_ptr;
  4715. e = lb_emit_struct_ep(p, e, index);
  4716. } else if (type->kind == Type_Tuple) {
  4717. type = type->Tuple.variables[index]->type;
  4718. e = lb_emit_struct_ep(p, e, index);
  4719. } else if (type->kind == Type_Basic) {
  4720. switch (type->Basic.kind) {
  4721. case Basic_any: {
  4722. if (index == 0) {
  4723. type = t_rawptr;
  4724. } else if (index == 1) {
  4725. type = t_type_info_ptr;
  4726. }
  4727. e = lb_emit_struct_ep(p, e, index);
  4728. break;
  4729. }
  4730. case Basic_string:
  4731. e = lb_emit_struct_ep(p, e, index);
  4732. break;
  4733. default:
  4734. GB_PANIC("un-gep-able type");
  4735. break;
  4736. }
  4737. } else if (type->kind == Type_Slice) {
  4738. e = lb_emit_struct_ep(p, e, index);
  4739. } else if (type->kind == Type_DynamicArray) {
  4740. e = lb_emit_struct_ep(p, e, index);
  4741. } else if (type->kind == Type_Array) {
  4742. e = lb_emit_array_epi(p, e, index);
  4743. } else if (type->kind == Type_Map) {
  4744. e = lb_emit_struct_ep(p, e, index);
  4745. } else {
  4746. GB_PANIC("un-gep-able type %s", type_to_string(type));
  4747. }
  4748. }
  4749. return e;
  4750. }
  4751. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  4752. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  4753. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  4754. return lb_emit_load(p, res);
  4755. }
  4756. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  4757. // NOTE(bill): The prev block may defer injection before it's terminator
  4758. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  4759. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  4760. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  4761. return;
  4762. }
  4763. lbBlock *b = lb_create_block(p, "defer");
  4764. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  4765. lb_emit_jump(p, b);
  4766. }
  4767. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  4768. lb_emit_jump(p, b);
  4769. }
  4770. lb_start_block(p, b);
  4771. if (d.kind == lbDefer_Node) {
  4772. lb_build_stmt(p, d.stmt);
  4773. } else if (d.kind == lbDefer_Instr) {
  4774. // NOTE(bill): Need to make a new copy
  4775. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  4776. LLVMInsertIntoBuilder(p->builder, instr);
  4777. } else if (d.kind == lbDefer_Proc) {
  4778. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  4779. }
  4780. }
  4781. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  4782. isize count = p->defer_stmts.count;
  4783. isize i = count;
  4784. while (i --> 0) {
  4785. lbDefer d = p->defer_stmts[i];
  4786. if (kind == lbDeferExit_Default) {
  4787. if (p->scope_index == d.scope_index &&
  4788. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  4789. lb_build_defer_stmt(p, d);
  4790. array_pop(&p->defer_stmts);
  4791. continue;
  4792. } else {
  4793. break;
  4794. }
  4795. } else if (kind == lbDeferExit_Return) {
  4796. lb_build_defer_stmt(p, d);
  4797. } else if (kind == lbDeferExit_Branch) {
  4798. GB_ASSERT(block != nullptr);
  4799. isize lower_limit = block->scope_index;
  4800. if (lower_limit < d.scope_index) {
  4801. lb_build_defer_stmt(p, d);
  4802. }
  4803. }
  4804. }
  4805. }
  4806. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  4807. lbDefer d = {lbDefer_Node};
  4808. d.scope_index = scope_index;
  4809. d.context_stack_count = p->context_stack.count;
  4810. d.block = p->curr_block;
  4811. d.stmt = stmt;
  4812. array_add(&p->defer_stmts, d);
  4813. return d;
  4814. }
  4815. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  4816. lbDefer d = {lbDefer_Proc};
  4817. d.scope_index = p->scope_index;
  4818. d.block = p->curr_block;
  4819. d.proc.deferred = deferred;
  4820. d.proc.result_as_args = result_as_args;
  4821. array_add(&p->defer_stmts, d);
  4822. return d;
  4823. }
  4824. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  4825. Array<lbValue> array = {};
  4826. Type *t = base_type(value.type);
  4827. if (t == nullptr) {
  4828. // Do nothing
  4829. } else if (is_type_tuple(t)) {
  4830. GB_ASSERT(t->kind == Type_Tuple);
  4831. auto *rt = &t->Tuple;
  4832. if (rt->variables.count > 0) {
  4833. array = array_make<lbValue>(heap_allocator(), rt->variables.count);
  4834. for_array(i, rt->variables) {
  4835. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  4836. array[i] = elem;
  4837. }
  4838. }
  4839. } else {
  4840. array = array_make<lbValue>(heap_allocator(), 1);
  4841. array[0] = value;
  4842. }
  4843. return array;
  4844. }
  4845. 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) {
  4846. unsigned arg_count = cast(unsigned)processed_args.count;
  4847. if (return_ptr.value != nullptr) {
  4848. arg_count += 1;
  4849. }
  4850. if (context_ptr.addr.value != nullptr) {
  4851. arg_count += 1;
  4852. }
  4853. LLVMValueRef *args = gb_alloc_array(heap_allocator(), LLVMValueRef, arg_count);
  4854. isize arg_index = 0;
  4855. if (return_ptr.value != nullptr) {
  4856. args[arg_index++] = return_ptr.value;
  4857. }
  4858. for_array(i, processed_args) {
  4859. lbValue arg = processed_args[i];
  4860. args[arg_index++] = arg.value;
  4861. }
  4862. if (context_ptr.addr.value != nullptr) {
  4863. args[arg_index++] = context_ptr.addr.value;
  4864. }
  4865. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  4866. GB_ASSERT(curr_block != p->decl_block->block);
  4867. LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");;
  4868. lbValue res = {};
  4869. res.value = ret;
  4870. res.type = abi_rt;
  4871. return res;
  4872. }
  4873. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  4874. String name = make_string_c(c_name);
  4875. AstPackage *pkg = p->module->info->runtime_package;
  4876. Entity *e = scope_lookup_current(pkg->scope, name);
  4877. lbValue *found = nullptr;
  4878. if (p->module != e->code_gen_module) {
  4879. gb_mutex_lock(&p->module->mutex);
  4880. }
  4881. found = map_get(&e->code_gen_module->values, hash_entity(e));
  4882. if (p->module != e->code_gen_module) {
  4883. gb_mutex_unlock(&p->module->mutex);
  4884. }
  4885. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  4886. return lb_emit_call(p, *found, args);
  4887. }
  4888. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  4889. lbModule *m = p->module;
  4890. Type *pt = base_type(value.type);
  4891. GB_ASSERT(pt->kind == Type_Proc);
  4892. Type *results = pt->Proc.results;
  4893. if (p->entity != nullptr) {
  4894. if (p->entity->flags & EntityFlag_Disabled) {
  4895. return {};
  4896. }
  4897. }
  4898. lbAddr context_ptr = {};
  4899. if (pt->Proc.calling_convention == ProcCC_Odin) {
  4900. context_ptr = lb_find_or_generate_context_ptr(p);
  4901. }
  4902. set_procedure_abi_types(heap_allocator(), pt);
  4903. bool is_c_vararg = pt->Proc.c_vararg;
  4904. isize param_count = pt->Proc.param_count;
  4905. if (is_c_vararg) {
  4906. GB_ASSERT(param_count-1 <= args.count);
  4907. param_count -= 1;
  4908. } else {
  4909. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  4910. }
  4911. auto processed_args = array_make<lbValue>(heap_allocator(), 0, args.count);
  4912. for (isize i = 0; i < param_count; i++) {
  4913. Entity *e = pt->Proc.params->Tuple.variables[i];
  4914. if (e->kind != Entity_Variable) {
  4915. // array_add(&processed_args, args[i]);
  4916. continue;
  4917. }
  4918. GB_ASSERT(e->flags & EntityFlag_Param);
  4919. Type *original_type = e->type;
  4920. Type *new_type = pt->Proc.abi_compat_params[i];
  4921. Type *arg_type = args[i].type;
  4922. if (are_types_identical(arg_type, new_type)) {
  4923. // NOTE(bill): Done
  4924. array_add(&processed_args, args[i]);
  4925. } else if (!are_types_identical(original_type, new_type)) {
  4926. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  4927. if (e->flags&EntityFlag_ImplicitReference) {
  4928. array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i]));
  4929. } else if (!is_type_pointer(arg_type)) {
  4930. array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16));
  4931. }
  4932. } else if (is_type_integer(new_type) || is_type_float(new_type)) {
  4933. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  4934. } else if (new_type == t_llvm_bool) {
  4935. array_add(&processed_args, lb_emit_conv(p, args[i], new_type));
  4936. } else if (is_type_simd_vector(new_type)) {
  4937. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  4938. } else if (is_type_tuple(new_type)) {
  4939. Type *abi_type = pt->Proc.abi_compat_params[i];
  4940. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  4941. lbValue x = lb_emit_transmute(p, args[i], st);
  4942. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  4943. lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j);
  4944. array_add(&processed_args, xx);
  4945. }
  4946. }
  4947. } else {
  4948. lbValue x = lb_emit_conv(p, args[i], new_type);
  4949. array_add(&processed_args, x);
  4950. }
  4951. }
  4952. if (inlining == ProcInlining_none) {
  4953. inlining = p->inlining;
  4954. }
  4955. lbValue result = {};
  4956. Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type);
  4957. Type *rt = reduce_tuple_to_single_type(results);
  4958. if (pt->Proc.return_by_pointer) {
  4959. lbValue return_ptr = {};
  4960. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  4961. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  4962. return_ptr = p->return_ptr_hint_value;
  4963. p->return_ptr_hint_used = true;
  4964. }
  4965. }
  4966. if (return_ptr.value == nullptr) {
  4967. lbAddr r = lb_add_local_generated(p, rt, true);
  4968. return_ptr = r.addr;
  4969. }
  4970. GB_ASSERT(is_type_pointer(return_ptr.type));
  4971. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  4972. result = lb_emit_load(p, return_ptr);
  4973. } else {
  4974. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  4975. if (abi_rt != rt) {
  4976. result = lb_emit_transmute(p, result, rt);
  4977. }
  4978. }
  4979. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  4980. if (found != nullptr) {
  4981. Entity *e = *found;
  4982. if (e != nullptr && entity_has_deferred_procedure(e)) {
  4983. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  4984. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  4985. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  4986. GB_ASSERT(deferred_found != nullptr);
  4987. lbValue deferred = *deferred_found;
  4988. auto in_args = args;
  4989. Array<lbValue> result_as_args = {};
  4990. switch (kind) {
  4991. case DeferredProcedure_none:
  4992. break;
  4993. case DeferredProcedure_in:
  4994. result_as_args = in_args;
  4995. break;
  4996. case DeferredProcedure_out:
  4997. result_as_args = lb_value_to_array(p, result);
  4998. break;
  4999. }
  5000. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  5001. }
  5002. }
  5003. return result;
  5004. }
  5005. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  5006. Type *t = s.type;
  5007. GB_ASSERT(is_type_pointer(t));
  5008. Type *st = base_type(type_deref(t));
  5009. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  5010. LLVMValueRef indices[2] = {};
  5011. indices[0] = llvm_zero32(p->module);
  5012. indices[1] = lb_emit_conv(p, index, t_i32).value;
  5013. Type *ptr = base_array_type(st);
  5014. lbValue res = {};
  5015. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  5016. res.type = alloc_type_pointer(ptr);
  5017. return res;
  5018. }
  5019. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  5020. Type *t = s.type;
  5021. GB_ASSERT(is_type_pointer(t));
  5022. Type *st = base_type(type_deref(t));
  5023. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  5024. GB_ASSERT(0 <= index);
  5025. Type *ptr = base_array_type(st);
  5026. LLVMValueRef indices[2] = {
  5027. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  5028. LLVMConstInt(lb_type(p->module, t_int), index, true),
  5029. };
  5030. lbValue res = {};
  5031. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  5032. res.type = alloc_type_pointer(ptr);
  5033. return res;
  5034. }
  5035. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  5036. LLVMValueRef indices[1] = {index.value};
  5037. lbValue res = {};
  5038. res.type = ptr.type;
  5039. res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, type_deref(ptr.type)), ptr.value, indices, 1, "");
  5040. return res;
  5041. }
  5042. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  5043. Type *t = lb_addr_type(slice);
  5044. GB_ASSERT(is_type_slice(t));
  5045. lbValue ptr = lb_addr_get_ptr(p, slice);
  5046. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  5047. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  5048. }
  5049. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  5050. Type *t = lb_addr_type(string);
  5051. GB_ASSERT(is_type_string(t));
  5052. lbValue ptr = lb_addr_get_ptr(p, string);
  5053. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  5054. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  5055. }
  5056. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  5057. Type *t = base_type(string.type);
  5058. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  5059. return lb_emit_struct_ev(p, string, 0);
  5060. }
  5061. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  5062. Type *t = base_type(string.type);
  5063. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  5064. return lb_emit_struct_ev(p, string, 1);
  5065. }
  5066. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  5067. GB_ASSERT(is_type_cstring(value.type));
  5068. auto args = array_make<lbValue>(heap_allocator(), 1);
  5069. args[0] = lb_emit_conv(p, value, t_cstring);
  5070. return lb_emit_runtime_call(p, "cstring_len", args);
  5071. }
  5072. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  5073. Type *t = type_deref(array_ptr.type);
  5074. GB_ASSERT(is_type_array(t));
  5075. return lb_emit_struct_ep(p, array_ptr, 0);
  5076. }
  5077. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  5078. GB_ASSERT(is_type_slice(slice.type));
  5079. return lb_emit_struct_ev(p, slice, 0);
  5080. }
  5081. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  5082. GB_ASSERT(is_type_slice(slice.type));
  5083. return lb_emit_struct_ev(p, slice, 1);
  5084. }
  5085. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  5086. GB_ASSERT(is_type_dynamic_array(da.type));
  5087. return lb_emit_struct_ev(p, da, 0);
  5088. }
  5089. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  5090. GB_ASSERT(is_type_dynamic_array(da.type));
  5091. return lb_emit_struct_ev(p, da, 1);
  5092. }
  5093. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  5094. GB_ASSERT(is_type_dynamic_array(da.type));
  5095. return lb_emit_struct_ev(p, da, 2);
  5096. }
  5097. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  5098. GB_ASSERT(is_type_dynamic_array(da.type));
  5099. return lb_emit_struct_ev(p, da, 3);
  5100. }
  5101. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  5102. gbAllocator a = heap_allocator();
  5103. Type *t = base_type(value.type);
  5104. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  5105. init_map_internal_types(t);
  5106. Type *gst = t->Map.generated_struct_type;
  5107. i32 index = 1;
  5108. lbValue entries = lb_emit_struct_ev(p, value, index);
  5109. return entries;
  5110. }
  5111. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  5112. gbAllocator a = heap_allocator();
  5113. Type *t = base_type(type_deref(value.type));
  5114. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  5115. init_map_internal_types(t);
  5116. Type *gst = t->Map.generated_struct_type;
  5117. i32 index = 1;
  5118. lbValue entries = lb_emit_struct_ep(p, value, index);
  5119. return entries;
  5120. }
  5121. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  5122. lbValue entries = lb_map_entries(p, value);
  5123. return lb_dynamic_array_len(p, entries);
  5124. }
  5125. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  5126. lbValue entries = lb_map_entries(p, value);
  5127. return lb_dynamic_array_cap(p, entries);
  5128. }
  5129. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  5130. Type *t = base_type(value.type);
  5131. bool is_ptr = false;
  5132. if (is_type_pointer(t)) {
  5133. is_ptr = true;
  5134. t = base_type(type_deref(t));
  5135. }
  5136. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5137. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  5138. }
  5139. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  5140. t->Struct.soa_kind == StructSoa_Dynamic);
  5141. isize n = 0;
  5142. Type *elem = base_type(t->Struct.soa_elem);
  5143. if (elem->kind == Type_Struct) {
  5144. n = elem->Struct.fields.count;
  5145. } else if (elem->kind == Type_Array) {
  5146. n = elem->Array.count;
  5147. } else {
  5148. GB_PANIC("Unreachable");
  5149. }
  5150. if (is_ptr) {
  5151. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  5152. return lb_emit_load(p, v);
  5153. }
  5154. return lb_emit_struct_ev(p, value, cast(i32)n);
  5155. }
  5156. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  5157. Type *t = base_type(value.type);
  5158. bool is_ptr = false;
  5159. if (is_type_pointer(t)) {
  5160. is_ptr = true;
  5161. t = base_type(type_deref(t));
  5162. }
  5163. if (t->Struct.soa_kind == StructSoa_Fixed) {
  5164. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  5165. }
  5166. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  5167. isize n = 0;
  5168. Type *elem = base_type(t->Struct.soa_elem);
  5169. if (elem->kind == Type_Struct) {
  5170. n = elem->Struct.fields.count+1;
  5171. } else if (elem->kind == Type_Array) {
  5172. n = elem->Array.count+1;
  5173. } else {
  5174. GB_PANIC("Unreachable");
  5175. }
  5176. if (is_ptr) {
  5177. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  5178. return lb_emit_load(p, v);
  5179. }
  5180. return lb_emit_struct_ev(p, value, cast(i32)n);
  5181. }
  5182. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  5183. ast_node(ce, CallExpr, expr);
  5184. switch (id) {
  5185. case BuiltinProc_DIRECTIVE: {
  5186. ast_node(bd, BasicDirective, ce->proc);
  5187. String name = bd->name;
  5188. GB_ASSERT(name == "location");
  5189. String procedure = p->entity->token.string;
  5190. TokenPos pos = ast_token(ce->proc).pos;
  5191. if (ce->args.count > 0) {
  5192. Ast *ident = unselector_expr(ce->args[0]);
  5193. GB_ASSERT(ident->kind == Ast_Ident);
  5194. Entity *e = entity_of_ident(ident);
  5195. GB_ASSERT(e != nullptr);
  5196. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  5197. procedure = e->parent_proc_decl->entity->token.string;
  5198. } else {
  5199. procedure = str_lit("");
  5200. }
  5201. pos = e->token.pos;
  5202. }
  5203. return lb_emit_source_code_location(p, procedure, pos);
  5204. }
  5205. case BuiltinProc_type_info_of: {
  5206. Ast *arg = ce->args[0];
  5207. TypeAndValue tav = type_and_value_of_expr(arg);
  5208. if (tav.mode == Addressing_Type) {
  5209. Type *t = default_type(type_of_expr(arg));
  5210. return lb_type_info(p->module, t);
  5211. }
  5212. GB_ASSERT(is_type_typeid(tav.type));
  5213. auto args = array_make<lbValue>(heap_allocator(), 1);
  5214. args[0] = lb_build_expr(p, arg);
  5215. return lb_emit_runtime_call(p, "__type_info_of", args);
  5216. }
  5217. case BuiltinProc_typeid_of: {
  5218. Ast *arg = ce->args[0];
  5219. TypeAndValue tav = type_and_value_of_expr(arg);
  5220. if (tav.mode == Addressing_Type) {
  5221. Type *t = default_type(type_of_expr(arg));
  5222. return lb_typeid(p->module, t);
  5223. }
  5224. Type *t = base_type(tav.type);
  5225. GB_ASSERT(are_types_identical(t, t_type_info_ptr));
  5226. auto args = array_make<lbValue>(heap_allocator(), 1);
  5227. args[0] = lb_emit_conv(p, lb_build_expr(p, arg), t_type_info_ptr);
  5228. return lb_emit_runtime_call(p, "__typeid_of", args);
  5229. }
  5230. case BuiltinProc_len: {
  5231. lbValue v = lb_build_expr(p, ce->args[0]);
  5232. Type *t = base_type(v.type);
  5233. if (is_type_pointer(t)) {
  5234. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5235. v = lb_emit_load(p, v);
  5236. t = type_deref(t);
  5237. }
  5238. if (is_type_cstring(t)) {
  5239. return lb_cstring_len(p, v);
  5240. } else if (is_type_string(t)) {
  5241. return lb_string_len(p, v);
  5242. } else if (is_type_array(t)) {
  5243. GB_PANIC("Array lengths are constant");
  5244. } else if (is_type_slice(t)) {
  5245. return lb_slice_len(p, v);
  5246. } else if (is_type_dynamic_array(t)) {
  5247. return lb_dynamic_array_len(p, v);
  5248. } else if (is_type_map(t)) {
  5249. return lb_map_len(p, v);
  5250. } else if (is_type_soa_struct(t)) {
  5251. return lb_soa_struct_len(p, v);
  5252. }
  5253. GB_PANIC("Unreachable");
  5254. break;
  5255. }
  5256. case BuiltinProc_cap: {
  5257. lbValue v = lb_build_expr(p, ce->args[0]);
  5258. Type *t = base_type(v.type);
  5259. if (is_type_pointer(t)) {
  5260. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  5261. v = lb_emit_load(p, v);
  5262. t = type_deref(t);
  5263. }
  5264. if (is_type_string(t)) {
  5265. GB_PANIC("Unreachable");
  5266. } else if (is_type_array(t)) {
  5267. GB_PANIC("Array lengths are constant");
  5268. } else if (is_type_slice(t)) {
  5269. return lb_slice_len(p, v);
  5270. } else if (is_type_dynamic_array(t)) {
  5271. return lb_dynamic_array_cap(p, v);
  5272. } else if (is_type_map(t)) {
  5273. return lb_map_cap(p, v);
  5274. } else if (is_type_soa_struct(t)) {
  5275. return lb_soa_struct_cap(p, v);
  5276. }
  5277. GB_PANIC("Unreachable");
  5278. break;
  5279. }
  5280. case BuiltinProc_swizzle: {
  5281. lbAddr addr = lb_build_addr(p, ce->args[0]);
  5282. isize index_count = ce->args.count-1;
  5283. if (index_count == 0) {
  5284. return lb_addr_load(p, addr);
  5285. }
  5286. lbValue src = lb_addr_get_ptr(p, addr);
  5287. // TODO(bill): Should this be zeroed or not?
  5288. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  5289. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  5290. for (i32 i = 1; i < ce->args.count; i++) {
  5291. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  5292. GB_ASSERT(is_type_integer(tv.type));
  5293. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  5294. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  5295. i32 dst_index = i-1;
  5296. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  5297. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  5298. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  5299. }
  5300. return lb_addr_load(p, dst);
  5301. }
  5302. case BuiltinProc_complex: {
  5303. lbValue real = lb_build_expr(p, ce->args[0]);
  5304. lbValue imag = lb_build_expr(p, ce->args[1]);
  5305. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  5306. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  5307. Type *ft = base_complex_elem_type(tv.type);
  5308. real = lb_emit_conv(p, real, ft);
  5309. imag = lb_emit_conv(p, imag, ft);
  5310. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  5311. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  5312. return lb_emit_load(p, dst);
  5313. }
  5314. case BuiltinProc_quaternion: {
  5315. lbValue real = lb_build_expr(p, ce->args[0]);
  5316. lbValue imag = lb_build_expr(p, ce->args[1]);
  5317. lbValue jmag = lb_build_expr(p, ce->args[2]);
  5318. lbValue kmag = lb_build_expr(p, ce->args[3]);
  5319. // @QuaternionLayout
  5320. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  5321. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  5322. Type *ft = base_complex_elem_type(tv.type);
  5323. real = lb_emit_conv(p, real, ft);
  5324. imag = lb_emit_conv(p, imag, ft);
  5325. jmag = lb_emit_conv(p, jmag, ft);
  5326. kmag = lb_emit_conv(p, kmag, ft);
  5327. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  5328. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  5329. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  5330. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  5331. return lb_emit_load(p, dst);
  5332. }
  5333. case BuiltinProc_real: {
  5334. lbValue val = lb_build_expr(p, ce->args[0]);
  5335. if (is_type_complex(val.type)) {
  5336. lbValue real = lb_emit_struct_ev(p, val, 0);
  5337. return lb_emit_conv(p, real, tv.type);
  5338. } else if (is_type_quaternion(val.type)) {
  5339. // @QuaternionLayout
  5340. lbValue real = lb_emit_struct_ev(p, val, 3);
  5341. return lb_emit_conv(p, real, tv.type);
  5342. }
  5343. GB_PANIC("invalid type for real");
  5344. return {};
  5345. }
  5346. case BuiltinProc_imag: {
  5347. lbValue val = lb_build_expr(p, ce->args[0]);
  5348. if (is_type_complex(val.type)) {
  5349. lbValue imag = lb_emit_struct_ev(p, val, 1);
  5350. return lb_emit_conv(p, imag, tv.type);
  5351. } else if (is_type_quaternion(val.type)) {
  5352. // @QuaternionLayout
  5353. lbValue imag = lb_emit_struct_ev(p, val, 0);
  5354. return lb_emit_conv(p, imag, tv.type);
  5355. }
  5356. GB_PANIC("invalid type for imag");
  5357. return {};
  5358. }
  5359. case BuiltinProc_jmag: {
  5360. lbValue val = lb_build_expr(p, ce->args[0]);
  5361. if (is_type_quaternion(val.type)) {
  5362. // @QuaternionLayout
  5363. lbValue imag = lb_emit_struct_ev(p, val, 1);
  5364. return lb_emit_conv(p, imag, tv.type);
  5365. }
  5366. GB_PANIC("invalid type for jmag");
  5367. return {};
  5368. }
  5369. case BuiltinProc_kmag: {
  5370. lbValue val = lb_build_expr(p, ce->args[0]);
  5371. if (is_type_quaternion(val.type)) {
  5372. // @QuaternionLayout
  5373. lbValue imag = lb_emit_struct_ev(p, val, 2);
  5374. return lb_emit_conv(p, imag, tv.type);
  5375. }
  5376. GB_PANIC("invalid type for kmag");
  5377. return {};
  5378. }
  5379. case BuiltinProc_conj: {
  5380. lbValue val = lb_build_expr(p, ce->args[0]);
  5381. lbValue res = {};
  5382. Type *t = val.type;
  5383. if (is_type_complex(t)) {
  5384. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  5385. lbValue real = lb_emit_struct_ev(p, val, 0);
  5386. lbValue imag = lb_emit_struct_ev(p, val, 1);
  5387. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  5388. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  5389. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  5390. } else if (is_type_quaternion(t)) {
  5391. // @QuaternionLayout
  5392. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  5393. lbValue real = lb_emit_struct_ev(p, val, 3);
  5394. lbValue imag = lb_emit_struct_ev(p, val, 0);
  5395. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  5396. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  5397. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  5398. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  5399. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  5400. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  5401. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  5402. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  5403. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  5404. }
  5405. return lb_emit_load(p, res);
  5406. }
  5407. case BuiltinProc_expand_to_tuple: {
  5408. lbValue val = lb_build_expr(p, ce->args[0]);
  5409. Type *t = base_type(val.type);
  5410. if (!is_type_tuple(tv.type)) {
  5411. if (t->kind == Type_Struct) {
  5412. GB_ASSERT(t->Struct.fields.count == 1);
  5413. return lb_emit_struct_ev(p, val, 0);
  5414. } else if (t->kind == Type_Array) {
  5415. GB_ASSERT(t->Array.count == 1);
  5416. return lb_emit_array_epi(p, val, 0);
  5417. } else {
  5418. GB_PANIC("Unknown type of expand_to_tuple");
  5419. }
  5420. }
  5421. GB_ASSERT(is_type_tuple(tv.type));
  5422. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5423. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  5424. if (t->kind == Type_Struct) {
  5425. for_array(src_index, t->Struct.fields) {
  5426. Entity *field = t->Struct.fields[src_index];
  5427. i32 field_index = field->Variable.field_index;
  5428. lbValue f = lb_emit_struct_ev(p, val, field_index);
  5429. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  5430. lb_emit_store(p, ep, f);
  5431. }
  5432. } else if (t->kind == Type_Array) {
  5433. // TODO(bill): Clean-up this code
  5434. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  5435. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  5436. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  5437. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  5438. lb_emit_store(p, ep, f);
  5439. }
  5440. } else {
  5441. GB_PANIC("Unknown type of expand_to_tuple");
  5442. }
  5443. return lb_emit_load(p, tuple);
  5444. }
  5445. case BuiltinProc_min: {
  5446. Type *t = type_of_expr(expr);
  5447. if (ce->args.count == 2) {
  5448. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  5449. } else {
  5450. lbValue x = lb_build_expr(p, ce->args[0]);
  5451. for (isize i = 1; i < ce->args.count; i++) {
  5452. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  5453. }
  5454. return x;
  5455. }
  5456. }
  5457. case BuiltinProc_max: {
  5458. Type *t = type_of_expr(expr);
  5459. if (ce->args.count == 2) {
  5460. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  5461. } else {
  5462. lbValue x = lb_build_expr(p, ce->args[0]);
  5463. for (isize i = 1; i < ce->args.count; i++) {
  5464. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  5465. }
  5466. return x;
  5467. }
  5468. }
  5469. case BuiltinProc_abs: {
  5470. gbAllocator a = heap_allocator();
  5471. lbValue x = lb_build_expr(p, ce->args[0]);
  5472. Type *t = x.type;
  5473. if (is_type_unsigned(t)) {
  5474. return x;
  5475. }
  5476. if (is_type_quaternion(t)) {
  5477. i64 sz = 8*type_size_of(t);
  5478. auto args = array_make<lbValue>(heap_allocator(), 1);
  5479. args[0] = x;
  5480. switch (sz) {
  5481. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  5482. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  5483. }
  5484. GB_PANIC("Unknown complex type");
  5485. } else if (is_type_complex(t)) {
  5486. i64 sz = 8*type_size_of(t);
  5487. auto args = array_make<lbValue>(heap_allocator(), 1);
  5488. args[0] = x;
  5489. switch (sz) {
  5490. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  5491. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  5492. }
  5493. GB_PANIC("Unknown complex type");
  5494. } else if (is_type_float(t)) {
  5495. i64 sz = 8*type_size_of(t);
  5496. auto args = array_make<lbValue>(heap_allocator(), 1);
  5497. args[0] = x;
  5498. switch (sz) {
  5499. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  5500. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  5501. }
  5502. GB_PANIC("Unknown float type");
  5503. }
  5504. lbValue zero = lb_const_nil(p->module, t);
  5505. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  5506. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  5507. return lb_emit_select(p, cond, neg, x);
  5508. }
  5509. case BuiltinProc_clamp:
  5510. return lb_emit_clamp(p, type_of_expr(expr),
  5511. lb_build_expr(p, ce->args[0]),
  5512. lb_build_expr(p, ce->args[1]),
  5513. lb_build_expr(p, ce->args[2]));
  5514. // "Intrinsics"
  5515. case BuiltinProc_cpu_relax:
  5516. // TODO(bill): BuiltinProc_cpu_relax
  5517. // ir_write_str_lit(f, "call void asm sideeffect \"pause\", \"\"()");
  5518. return {};
  5519. case BuiltinProc_atomic_fence:
  5520. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  5521. return {};
  5522. case BuiltinProc_atomic_fence_acq:
  5523. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  5524. return {};
  5525. case BuiltinProc_atomic_fence_rel:
  5526. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  5527. return {};
  5528. case BuiltinProc_atomic_fence_acqrel:
  5529. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  5530. return {};
  5531. case BuiltinProc_atomic_store:
  5532. case BuiltinProc_atomic_store_rel:
  5533. case BuiltinProc_atomic_store_relaxed:
  5534. case BuiltinProc_atomic_store_unordered: {
  5535. lbValue dst = lb_build_expr(p, ce->args[0]);
  5536. lbValue val = lb_build_expr(p, ce->args[1]);
  5537. val = lb_emit_conv(p, val, type_deref(dst.type));
  5538. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  5539. switch (id) {
  5540. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  5541. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  5542. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  5543. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  5544. }
  5545. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  5546. return {};
  5547. }
  5548. case BuiltinProc_atomic_load:
  5549. case BuiltinProc_atomic_load_acq:
  5550. case BuiltinProc_atomic_load_relaxed:
  5551. case BuiltinProc_atomic_load_unordered: {
  5552. lbValue dst = lb_build_expr(p, ce->args[0]);
  5553. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  5554. switch (id) {
  5555. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  5556. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  5557. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  5558. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  5559. }
  5560. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  5561. lbValue res = {};
  5562. res.value = instr;
  5563. res.type = type_deref(dst.type);
  5564. return res;
  5565. }
  5566. case BuiltinProc_atomic_add:
  5567. case BuiltinProc_atomic_add_acq:
  5568. case BuiltinProc_atomic_add_rel:
  5569. case BuiltinProc_atomic_add_acqrel:
  5570. case BuiltinProc_atomic_add_relaxed:
  5571. case BuiltinProc_atomic_sub:
  5572. case BuiltinProc_atomic_sub_acq:
  5573. case BuiltinProc_atomic_sub_rel:
  5574. case BuiltinProc_atomic_sub_acqrel:
  5575. case BuiltinProc_atomic_sub_relaxed:
  5576. case BuiltinProc_atomic_and:
  5577. case BuiltinProc_atomic_and_acq:
  5578. case BuiltinProc_atomic_and_rel:
  5579. case BuiltinProc_atomic_and_acqrel:
  5580. case BuiltinProc_atomic_and_relaxed:
  5581. case BuiltinProc_atomic_nand:
  5582. case BuiltinProc_atomic_nand_acq:
  5583. case BuiltinProc_atomic_nand_rel:
  5584. case BuiltinProc_atomic_nand_acqrel:
  5585. case BuiltinProc_atomic_nand_relaxed:
  5586. case BuiltinProc_atomic_or:
  5587. case BuiltinProc_atomic_or_acq:
  5588. case BuiltinProc_atomic_or_rel:
  5589. case BuiltinProc_atomic_or_acqrel:
  5590. case BuiltinProc_atomic_or_relaxed:
  5591. case BuiltinProc_atomic_xor:
  5592. case BuiltinProc_atomic_xor_acq:
  5593. case BuiltinProc_atomic_xor_rel:
  5594. case BuiltinProc_atomic_xor_acqrel:
  5595. case BuiltinProc_atomic_xor_relaxed:
  5596. case BuiltinProc_atomic_xchg:
  5597. case BuiltinProc_atomic_xchg_acq:
  5598. case BuiltinProc_atomic_xchg_rel:
  5599. case BuiltinProc_atomic_xchg_acqrel:
  5600. case BuiltinProc_atomic_xchg_relaxed: {
  5601. lbValue dst = lb_build_expr(p, ce->args[0]);
  5602. lbValue val = lb_build_expr(p, ce->args[1]);
  5603. val = lb_emit_conv(p, val, type_deref(dst.type));
  5604. LLVMAtomicRMWBinOp op = {};
  5605. LLVMAtomicOrdering ordering = {};
  5606. switch (id) {
  5607. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5608. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  5609. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  5610. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5611. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  5612. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5613. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  5614. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  5615. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5616. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  5617. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5618. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  5619. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  5620. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5621. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  5622. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5623. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  5624. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  5625. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5626. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  5627. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5628. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  5629. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  5630. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5631. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  5632. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5633. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  5634. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  5635. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5636. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  5637. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  5638. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  5639. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  5640. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  5641. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  5642. }
  5643. LLVMValueRef instr = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  5644. return {};
  5645. }
  5646. case BuiltinProc_atomic_cxchg:
  5647. case BuiltinProc_atomic_cxchg_acq:
  5648. case BuiltinProc_atomic_cxchg_rel:
  5649. case BuiltinProc_atomic_cxchg_acqrel:
  5650. case BuiltinProc_atomic_cxchg_relaxed:
  5651. case BuiltinProc_atomic_cxchg_failrelaxed:
  5652. case BuiltinProc_atomic_cxchg_failacq:
  5653. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  5654. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  5655. case BuiltinProc_atomic_cxchgweak:
  5656. case BuiltinProc_atomic_cxchgweak_acq:
  5657. case BuiltinProc_atomic_cxchgweak_rel:
  5658. case BuiltinProc_atomic_cxchgweak_acqrel:
  5659. case BuiltinProc_atomic_cxchgweak_relaxed:
  5660. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  5661. case BuiltinProc_atomic_cxchgweak_failacq:
  5662. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  5663. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  5664. Type *type = expr->tav.type;
  5665. lbValue address = lb_build_expr(p, ce->args[0]);
  5666. Type *elem = type_deref(address.type);
  5667. lbValue old_value = lb_build_expr(p, ce->args[1]);
  5668. lbValue new_value = lb_build_expr(p, ce->args[2]);
  5669. old_value = lb_emit_conv(p, old_value, elem);
  5670. new_value = lb_emit_conv(p, new_value, elem);
  5671. LLVMAtomicOrdering success_ordering = {};
  5672. LLVMAtomicOrdering failure_ordering = {};
  5673. LLVMBool weak = false;
  5674. switch (id) {
  5675. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5676. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5677. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5678. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5679. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5680. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5681. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  5682. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5683. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  5684. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  5685. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  5686. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  5687. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  5688. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5689. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5690. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  5691. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5692. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  5693. }
  5694. // TODO(bill): Figure out how to make it weak
  5695. LLVMBool single_threaded = !weak;
  5696. LLVMValueRef instr = LLVMBuildAtomicCmpXchg(p->builder, address.value,
  5697. old_value.value, new_value.value,
  5698. success_ordering,
  5699. failure_ordering,
  5700. single_threaded);
  5701. return {};
  5702. }
  5703. }
  5704. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  5705. return {};
  5706. }
  5707. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  5708. lbModule *m = p->module;
  5709. TypeAndValue tv = type_and_value_of_expr(expr);
  5710. ast_node(ce, CallExpr, expr);
  5711. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  5712. AddressingMode proc_mode = proc_tv.mode;
  5713. if (proc_mode == Addressing_Type) {
  5714. GB_ASSERT(ce->args.count == 1);
  5715. lbValue x = lb_build_expr(p, ce->args[0]);
  5716. lbValue y = lb_emit_conv(p, x, tv.type);
  5717. return y;
  5718. }
  5719. Ast *pexpr = unparen_expr(ce->proc);
  5720. if (proc_mode == Addressing_Builtin) {
  5721. Entity *e = entity_of_node(pexpr);
  5722. BuiltinProcId id = BuiltinProc_Invalid;
  5723. if (e != nullptr) {
  5724. id = cast(BuiltinProcId)e->Builtin.id;
  5725. } else {
  5726. id = BuiltinProc_DIRECTIVE;
  5727. }
  5728. return lb_build_builtin_proc(p, expr, tv, id);
  5729. }
  5730. // NOTE(bill): Regular call
  5731. lbValue value = {};
  5732. Ast *proc_expr = unparen_expr(ce->proc);
  5733. if (proc_expr->tav.mode == Addressing_Constant) {
  5734. ExactValue v = proc_expr->tav.value;
  5735. switch (v.kind) {
  5736. case ExactValue_Integer:
  5737. {
  5738. u64 u = big_int_to_u64(&v.value_integer);
  5739. lbValue x = {};
  5740. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  5741. x.type = t_uintptr;
  5742. x = lb_emit_conv(p, x, t_rawptr);
  5743. value = lb_emit_conv(p, x, proc_expr->tav.type);
  5744. break;
  5745. }
  5746. case ExactValue_Pointer:
  5747. {
  5748. u64 u = cast(u64)v.value_pointer;
  5749. lbValue x = {};
  5750. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  5751. x.type = t_uintptr;
  5752. x = lb_emit_conv(p, x, t_rawptr);
  5753. value = lb_emit_conv(p, x, proc_expr->tav.type);
  5754. break;
  5755. }
  5756. }
  5757. }
  5758. if (value.value == nullptr) {
  5759. value = lb_build_expr(p, proc_expr);
  5760. }
  5761. GB_ASSERT(value.value != nullptr);
  5762. Type *proc_type_ = base_type(value.type);
  5763. GB_ASSERT(proc_type_->kind == Type_Proc);
  5764. TypeProc *pt = &proc_type_->Proc;
  5765. set_procedure_abi_types(heap_allocator(), proc_type_);
  5766. if (is_call_expr_field_value(ce)) {
  5767. auto args = array_make<lbValue>(heap_allocator(), pt->param_count);
  5768. for_array(arg_index, ce->args) {
  5769. Ast *arg = ce->args[arg_index];
  5770. ast_node(fv, FieldValue, arg);
  5771. GB_ASSERT(fv->field->kind == Ast_Ident);
  5772. String name = fv->field->Ident.token.string;
  5773. isize index = lookup_procedure_parameter(pt, name);
  5774. GB_ASSERT(index >= 0);
  5775. TypeAndValue tav = type_and_value_of_expr(fv->value);
  5776. if (tav.mode == Addressing_Type) {
  5777. args[index] = lb_const_nil(m, tav.type);
  5778. } else {
  5779. args[index] = lb_build_expr(p, fv->value);
  5780. }
  5781. }
  5782. TypeTuple *params = &pt->params->Tuple;
  5783. for (isize i = 0; i < args.count; i++) {
  5784. Entity *e = params->variables[i];
  5785. if (e->kind == Entity_TypeName) {
  5786. args[i] = lb_const_nil(m, e->type);
  5787. } else if (e->kind == Entity_Constant) {
  5788. continue;
  5789. } else {
  5790. GB_ASSERT(e->kind == Entity_Variable);
  5791. if (args[i].value == nullptr) {
  5792. switch (e->Variable.param_value.kind) {
  5793. case ParameterValue_Constant:
  5794. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  5795. break;
  5796. case ParameterValue_Nil:
  5797. args[i] = lb_const_nil(m, e->type);
  5798. break;
  5799. case ParameterValue_Location:
  5800. args[i] = lb_emit_source_code_location(p, p->entity->token.string, ast_token(expr).pos);
  5801. break;
  5802. case ParameterValue_Value:
  5803. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  5804. break;
  5805. }
  5806. } else {
  5807. args[i] = lb_emit_conv(p, args[i], e->type);
  5808. }
  5809. }
  5810. }
  5811. for (isize i = 0; i < args.count; i++) {
  5812. Entity *e = params->variables[i];
  5813. if (args[i].type == nullptr) {
  5814. continue;
  5815. } else if (is_type_untyped_nil(args[i].type)) {
  5816. args[i] = lb_const_nil(m, e->type);
  5817. } else if (is_type_untyped_undef(args[i].type)) {
  5818. args[i] = lb_const_undef(m, e->type);
  5819. }
  5820. }
  5821. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  5822. }
  5823. isize arg_index = 0;
  5824. isize arg_count = 0;
  5825. for_array(i, ce->args) {
  5826. Ast *arg = ce->args[i];
  5827. TypeAndValue tav = type_and_value_of_expr(arg);
  5828. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  5829. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  5830. Type *at = tav.type;
  5831. if (at->kind == Type_Tuple) {
  5832. arg_count += at->Tuple.variables.count;
  5833. } else {
  5834. arg_count++;
  5835. }
  5836. }
  5837. isize param_count = 0;
  5838. if (pt->params) {
  5839. GB_ASSERT(pt->params->kind == Type_Tuple);
  5840. param_count = pt->params->Tuple.variables.count;
  5841. }
  5842. auto args = array_make<lbValue>(heap_allocator(), cast(isize)gb_max(param_count, arg_count));
  5843. isize variadic_index = pt->variadic_index;
  5844. bool variadic = pt->variadic && variadic_index >= 0;
  5845. bool vari_expand = ce->ellipsis.pos.line != 0;
  5846. bool is_c_vararg = pt->c_vararg;
  5847. String proc_name = {};
  5848. if (p->entity != nullptr) {
  5849. proc_name = p->entity->token.string;
  5850. }
  5851. TokenPos pos = ast_token(ce->proc).pos;
  5852. TypeTuple *param_tuple = nullptr;
  5853. if (pt->params) {
  5854. GB_ASSERT(pt->params->kind == Type_Tuple);
  5855. param_tuple = &pt->params->Tuple;
  5856. }
  5857. for_array(i, ce->args) {
  5858. Ast *arg = ce->args[i];
  5859. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  5860. if (arg_tv.mode == Addressing_Type) {
  5861. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  5862. } else {
  5863. lbValue a = lb_build_expr(p, arg);
  5864. Type *at = a.type;
  5865. if (at->kind == Type_Tuple) {
  5866. for_array(i, at->Tuple.variables) {
  5867. Entity *e = at->Tuple.variables[i];
  5868. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  5869. args[arg_index++] = v;
  5870. }
  5871. } else {
  5872. args[arg_index++] = a;
  5873. }
  5874. }
  5875. }
  5876. if (param_count > 0) {
  5877. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  5878. GB_ASSERT(param_count < 1000000);
  5879. if (arg_count < param_count) {
  5880. isize end = cast(isize)param_count;
  5881. if (variadic) {
  5882. end = variadic_index;
  5883. }
  5884. while (arg_index < end) {
  5885. Entity *e = param_tuple->variables[arg_index];
  5886. GB_ASSERT(e->kind == Entity_Variable);
  5887. switch (e->Variable.param_value.kind) {
  5888. case ParameterValue_Constant:
  5889. args[arg_index++] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  5890. break;
  5891. case ParameterValue_Nil:
  5892. args[arg_index++] = lb_const_nil(m, e->type);
  5893. break;
  5894. case ParameterValue_Location:
  5895. args[arg_index++] = lb_emit_source_code_location(p, proc_name, pos);
  5896. break;
  5897. case ParameterValue_Value:
  5898. args[arg_index++] = lb_build_expr(p, e->Variable.param_value.ast_value);
  5899. break;
  5900. }
  5901. }
  5902. }
  5903. if (is_c_vararg) {
  5904. GB_ASSERT(variadic);
  5905. GB_ASSERT(!vari_expand);
  5906. isize i = 0;
  5907. for (; i < variadic_index; i++) {
  5908. Entity *e = param_tuple->variables[i];
  5909. if (e->kind == Entity_Variable) {
  5910. args[i] = lb_emit_conv(p, args[i], e->type);
  5911. }
  5912. }
  5913. Type *variadic_type = param_tuple->variables[i]->type;
  5914. GB_ASSERT(is_type_slice(variadic_type));
  5915. variadic_type = base_type(variadic_type)->Slice.elem;
  5916. if (!is_type_any(variadic_type)) {
  5917. for (; i < arg_count; i++) {
  5918. args[i] = lb_emit_conv(p, args[i], variadic_type);
  5919. }
  5920. } else {
  5921. for (; i < arg_count; i++) {
  5922. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  5923. }
  5924. }
  5925. } else if (variadic) {
  5926. isize i = 0;
  5927. for (; i < variadic_index; i++) {
  5928. Entity *e = param_tuple->variables[i];
  5929. if (e->kind == Entity_Variable) {
  5930. args[i] = lb_emit_conv(p, args[i], e->type);
  5931. }
  5932. }
  5933. if (!vari_expand) {
  5934. Type *variadic_type = param_tuple->variables[i]->type;
  5935. GB_ASSERT(is_type_slice(variadic_type));
  5936. variadic_type = base_type(variadic_type)->Slice.elem;
  5937. for (; i < arg_count; i++) {
  5938. args[i] = lb_emit_conv(p, args[i], variadic_type);
  5939. }
  5940. }
  5941. } else {
  5942. for (isize i = 0; i < param_count; i++) {
  5943. Entity *e = param_tuple->variables[i];
  5944. if (e->kind == Entity_Variable) {
  5945. if (args[i].value == nullptr) {
  5946. continue;
  5947. }
  5948. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  5949. args[i] = lb_emit_conv(p, args[i], e->type);
  5950. }
  5951. }
  5952. }
  5953. if (variadic && !vari_expand && !is_c_vararg) {
  5954. // variadic call argument generation
  5955. gbAllocator allocator = heap_allocator();
  5956. Type *slice_type = param_tuple->variables[variadic_index]->type;
  5957. Type *elem_type = base_type(slice_type)->Slice.elem;
  5958. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  5959. isize slice_len = arg_count+1 - (variadic_index+1);
  5960. if (slice_len > 0) {
  5961. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  5962. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  5963. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  5964. lb_emit_store(p, addr, args[i]);
  5965. }
  5966. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  5967. lbValue len = lb_const_int(m, t_int, slice_len);
  5968. lb_fill_slice(p, slice, base_elem, len);
  5969. }
  5970. arg_count = param_count;
  5971. args[variadic_index] = lb_addr_load(p, slice);
  5972. }
  5973. }
  5974. if (variadic && variadic_index+1 < param_count) {
  5975. for (isize i = variadic_index+1; i < param_count; i++) {
  5976. Entity *e = param_tuple->variables[i];
  5977. switch (e->Variable.param_value.kind) {
  5978. case ParameterValue_Constant:
  5979. args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value);
  5980. break;
  5981. case ParameterValue_Nil:
  5982. args[i] = lb_const_nil(m, e->type);
  5983. break;
  5984. case ParameterValue_Location:
  5985. args[i] = lb_emit_source_code_location(p, proc_name, pos);
  5986. break;
  5987. case ParameterValue_Value:
  5988. args[i] = lb_build_expr(p, e->Variable.param_value.ast_value);
  5989. break;
  5990. }
  5991. }
  5992. }
  5993. isize final_count = param_count;
  5994. if (is_c_vararg) {
  5995. final_count = arg_count;
  5996. }
  5997. if (param_tuple != nullptr) {
  5998. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  5999. Entity *e = param_tuple->variables[i];
  6000. if (args[i].type == nullptr) {
  6001. continue;
  6002. } else if (is_type_untyped_nil(args[i].type)) {
  6003. args[i] = lb_const_nil(m, e->type);
  6004. } else if (is_type_untyped_undef(args[i].type)) {
  6005. args[i] = lb_const_undef(m, e->type);
  6006. }
  6007. }
  6008. }
  6009. auto call_args = array_slice(args, 0, final_count);
  6010. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  6011. }
  6012. bool lb_is_const(lbValue value) {
  6013. LLVMValueRef v = value.value;
  6014. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  6015. // TODO(bill): Is this correct behaviour?
  6016. return true;
  6017. }
  6018. if (LLVMIsConstant(v)) {
  6019. return true;
  6020. }
  6021. return false;
  6022. }
  6023. bool lb_is_const_nil(lbValue value) {
  6024. LLVMValueRef v = value.value;
  6025. if (LLVMIsConstant(v)) {
  6026. if (LLVMIsAConstantAggregateZero(v)) {
  6027. return true;
  6028. } else if (LLVMIsAConstantPointerNull(v)) {
  6029. return true;
  6030. }
  6031. }
  6032. return false;
  6033. }
  6034. String lb_get_const_string(lbModule *m, lbValue value) {
  6035. GB_ASSERT(lb_is_const(value));
  6036. Type *t = base_type(value.type);
  6037. GB_ASSERT(are_types_identical(t, t_string));
  6038. unsigned ptr_indices[1] = {0};
  6039. unsigned len_indices[1] = {1};
  6040. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  6041. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  6042. size_t length = 0;
  6043. char const *text = LLVMGetAsString(underlying_ptr, &length);
  6044. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  6045. return make_string(cast(u8 const *)text, real_length);
  6046. }
  6047. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  6048. GB_ASSERT(is_type_pointer(addr.type));
  6049. Type *type = type_deref(addr.type);
  6050. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  6051. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  6052. }
  6053. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  6054. Type *vt = core_type(value.type);
  6055. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  6056. GB_ASSERT(is_type_integer(vt));
  6057. // TODO(bill): lb_emit_byte_swap
  6058. lbValue res = {};
  6059. res.type = platform_type;
  6060. res.value = value.value;
  6061. // int sz = cast(int)type_size_of(vt);
  6062. // if (sz > 1) {
  6063. // char buf[32] = {};
  6064. // gb_snprintf(buf, gb_count_of(buf), "llvm.bswap.i%d", sz*8);
  6065. // unsigned id = LLVMLookupIntrinsicID(buf, gb_strlen(buf));
  6066. // gb_printf(">>> %s %u\n", buf, id);
  6067. // LLVMTypeRef types[2] = {};
  6068. // types[0] = lb_type(p->module, value.type);
  6069. // types[1] = lb_type(p->module, value.type);
  6070. // LLVMValueRef fn = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  6071. // res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  6072. // }
  6073. return res;
  6074. }
  6075. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  6076. lbLoopData data = {};
  6077. lbValue max = lb_const_int(p->module, t_int, count);
  6078. data.idx_addr = lb_add_local_generated(p, index_type, true);
  6079. data.body = lb_create_block(p, "loop.body");
  6080. data.done = lb_create_block(p, "loop.done");
  6081. data.loop = lb_create_block(p, "loop.loop");
  6082. lb_emit_jump(p, data.loop);
  6083. lb_start_block(p, data.loop);
  6084. data.idx = lb_addr_load(p, data.idx_addr);
  6085. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  6086. lb_emit_if(p, cond, data.body, data.done);
  6087. lb_start_block(p, data.body);
  6088. return data;
  6089. }
  6090. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  6091. if (data.idx_addr.addr.value != nullptr) {
  6092. lb_emit_increment(p, data.idx_addr.addr);
  6093. lb_emit_jump(p, data.loop);
  6094. lb_start_block(p, data.done);
  6095. }
  6096. }
  6097. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  6098. lbValue res = {};
  6099. res.type = t_llvm_bool;
  6100. Type *t = x.type;
  6101. if (is_type_pointer(t)) {
  6102. if (op_kind == Token_CmpEq) {
  6103. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  6104. } else if (op_kind == Token_NotEq) {
  6105. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  6106. }
  6107. return res;
  6108. } else if (is_type_cstring(t)) {
  6109. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  6110. if (op_kind == Token_CmpEq) {
  6111. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  6112. } else if (op_kind == Token_NotEq) {
  6113. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  6114. }
  6115. return res;
  6116. } else if (is_type_any(t)) {
  6117. lbValue data = lb_emit_struct_ev(p, x, 0);
  6118. lbValue ti = lb_emit_struct_ev(p, x, 1);
  6119. if (op_kind == Token_CmpEq) {
  6120. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6121. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  6122. res.value = LLVMBuildOr(p->builder, a, b, "");
  6123. return res;
  6124. } else if (op_kind == Token_NotEq) {
  6125. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6126. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  6127. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6128. return res;
  6129. }
  6130. } else if (is_type_slice(t)) {
  6131. lbValue data = lb_emit_struct_ev(p, x, 0);
  6132. lbValue cap = lb_emit_struct_ev(p, x, 1);
  6133. if (op_kind == Token_CmpEq) {
  6134. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6135. LLVMValueRef b = LLVMBuildIsNull(p->builder, cap.value, "");
  6136. res.value = LLVMBuildOr(p->builder, a, b, "");
  6137. return res;
  6138. } else if (op_kind == Token_NotEq) {
  6139. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6140. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, cap.value, "");
  6141. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6142. return res;
  6143. }
  6144. } else if (is_type_dynamic_array(t)) {
  6145. lbValue data = lb_emit_struct_ev(p, x, 0);
  6146. lbValue cap = lb_emit_struct_ev(p, x, 2);
  6147. if (op_kind == Token_CmpEq) {
  6148. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  6149. LLVMValueRef b = LLVMBuildIsNull(p->builder, cap.value, "");
  6150. res.value = LLVMBuildOr(p->builder, a, b, "");
  6151. return res;
  6152. } else if (op_kind == Token_NotEq) {
  6153. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  6154. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, cap.value, "");
  6155. res.value = LLVMBuildAnd(p->builder, a, b, "");
  6156. return res;
  6157. }
  6158. } else if (is_type_map(t)) {
  6159. GB_PANIC("map nil comparison");
  6160. // lbValue len = lb_map_len(p, x);
  6161. // return lb_emit_comp(p, op_kind, len, v_zero);
  6162. } else if (is_type_union(t)) {
  6163. if (type_size_of(t) == 0) {
  6164. if (op_kind == Token_CmpEq) {
  6165. return lb_const_bool(p->module, t_llvm_bool, true);
  6166. } else if (op_kind == Token_NotEq) {
  6167. return lb_const_bool(p->module, t_llvm_bool, false);
  6168. }
  6169. } else {
  6170. GB_PANIC("lb_emit_union_tag_value");
  6171. // lbValue tag = lb_emit_union_tag_value(p, x);
  6172. // return lb_emit_comp(p, op_kind, tag, v_zero);
  6173. }
  6174. } else if (is_type_typeid(t)) {
  6175. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  6176. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  6177. } else if (is_type_bit_field(t)) {
  6178. auto args = array_make<lbValue>(heap_allocator(), 2);
  6179. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  6180. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  6181. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  6182. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  6183. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  6184. return res;
  6185. } else if (is_type_soa_struct(t)) {
  6186. GB_PANIC("#soa struct nil comparison");
  6187. // Type *bt = base_type(t);
  6188. // if (bt->Struct.soa_kind == StructSoa_Slice) {
  6189. // lbValue len = lb_soa_struct_len(p, x);
  6190. // if (bt->Struct.fields.count > 1) {
  6191. // lbValue data = lb_emit_struct_ev(p, x, 0);
  6192. // if (op_kind == Token_CmpEq) {
  6193. // lbValue a = lb_emit_comp(p, Token_CmpEq, data, v_raw_nil);
  6194. // lbValue b = lb_emit_comp(p, Token_CmpEq, len, v_zero);
  6195. // return lb_emit_arith(p, Token_Or, a, b, t_bool);
  6196. // } else if (op_kind == Token_NotEq) {
  6197. // lbValue a = lb_emit_comp(p, Token_NotEq, data, v_raw_nil);
  6198. // lbValue b = lb_emit_comp(p, Token_NotEq, len, v_zero);
  6199. // return lb_emit_arith(p, Token_And, a, b, t_bool);
  6200. // }
  6201. // } else {
  6202. // return lb_emit_comp(p, op_kind, len, v_zero);
  6203. // }
  6204. // } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  6205. // lbValue cap = lb_soa_struct_len(p, x);
  6206. // if (bt->Struct.fields.count > 1) {
  6207. // lbValue data = lb_emit_struct_ev(p, x, 0);
  6208. // if (op_kind == Token_CmpEq) {
  6209. // lbValue a = lb_emit_comp(p, Token_CmpEq, data, v_raw_nil);
  6210. // lbValue b = lb_emit_comp(p, Token_CmpEq, cap, v_zero);
  6211. // return lb_emit_arith(p, Token_Or, a, b, t_bool);
  6212. // } else if (op_kind == Token_NotEq) {
  6213. // lbValue a = lb_emit_comp(p, Token_NotEq, data, v_raw_nil);
  6214. // lbValue b = lb_emit_comp(p, Token_NotEq, cap, v_zero);
  6215. // return lb_emit_arith(p, Token_And, a, b, t_bool);
  6216. // }
  6217. // } else {
  6218. // return lb_emit_comp(p, op_kind, cap, v_zero);
  6219. // }
  6220. // }
  6221. }
  6222. return {};
  6223. }
  6224. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  6225. Type *a = base_type(left.type);
  6226. Type *b = base_type(right.type);
  6227. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  6228. lbValue nil_check = {};
  6229. if (is_type_untyped_nil(left.type)) {
  6230. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  6231. } else if (is_type_untyped_nil(right.type)) {
  6232. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  6233. }
  6234. if (nil_check.value != nullptr) {
  6235. return nil_check;
  6236. }
  6237. if (are_types_identical(a, b)) {
  6238. // NOTE(bill): No need for a conversion
  6239. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  6240. left = lb_emit_conv(p, left, right.type);
  6241. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  6242. right = lb_emit_conv(p, right, left.type);
  6243. } else {
  6244. gbAllocator a = heap_allocator();
  6245. Type *lt = left.type;
  6246. Type *rt = right.type;
  6247. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  6248. Type *blt = base_type(lt);
  6249. Type *brt = base_type(rt);
  6250. GB_ASSERT(is_type_bit_field_value(blt));
  6251. GB_ASSERT(is_type_bit_field_value(brt));
  6252. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  6253. i64 bytes = bits / 8;
  6254. switch (bytes) {
  6255. case 1:
  6256. left = lb_emit_conv(p, left, t_u8);
  6257. right = lb_emit_conv(p, right, t_u8);
  6258. break;
  6259. case 2:
  6260. left = lb_emit_conv(p, left, t_u16);
  6261. right = lb_emit_conv(p, right, t_u16);
  6262. break;
  6263. case 4:
  6264. left = lb_emit_conv(p, left, t_u32);
  6265. right = lb_emit_conv(p, right, t_u32);
  6266. break;
  6267. case 8:
  6268. left = lb_emit_conv(p, left, t_u64);
  6269. right = lb_emit_conv(p, right, t_u64);
  6270. break;
  6271. default: GB_PANIC("Unknown integer size"); break;
  6272. }
  6273. }
  6274. lt = left.type;
  6275. rt = right.type;
  6276. i64 ls = type_size_of(lt);
  6277. i64 rs = type_size_of(rt);
  6278. if (ls < rs) {
  6279. left = lb_emit_conv(p, left, rt);
  6280. } else if (ls > rs) {
  6281. right = lb_emit_conv(p, right, lt);
  6282. } else {
  6283. right = lb_emit_conv(p, right, lt);
  6284. }
  6285. }
  6286. if (is_type_array(a)) {
  6287. Type *tl = base_type(a);
  6288. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  6289. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  6290. TokenKind cmp_op = Token_And;
  6291. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  6292. if (op_kind == Token_NotEq) {
  6293. res = lb_const_bool(p->module, t_llvm_bool, false);
  6294. cmp_op = Token_Or;
  6295. } else if (op_kind == Token_CmpEq) {
  6296. res = lb_const_bool(p->module, t_llvm_bool, true);
  6297. cmp_op = Token_And;
  6298. }
  6299. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  6300. i32 count = cast(i32)tl->Array.count;
  6301. if (inline_array_arith) {
  6302. // inline
  6303. lbAddr val = lb_add_local_generated(p, t_bool, false);
  6304. lb_addr_store(p, val, res);
  6305. for (i32 i = 0; i < count; i++) {
  6306. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  6307. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  6308. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  6309. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  6310. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  6311. }
  6312. return lb_addr_load(p, val);
  6313. } else {
  6314. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  6315. // TODO(bill): Test to see if this is actually faster!!!!
  6316. auto args = array_make<lbValue>(heap_allocator(), 3);
  6317. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  6318. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  6319. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  6320. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  6321. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  6322. return lb_emit_conv(p, res, t_bool);
  6323. } else {
  6324. lbAddr val = lb_add_local_generated(p, t_bool, false);
  6325. lb_addr_store(p, val, res);
  6326. auto loop_data = lb_loop_start(p, count, t_i32);
  6327. {
  6328. lbValue i = loop_data.idx;
  6329. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  6330. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  6331. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  6332. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  6333. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  6334. }
  6335. lb_loop_end(p, loop_data);
  6336. return lb_addr_load(p, val);
  6337. }
  6338. }
  6339. }
  6340. if (is_type_string(a)) {
  6341. if (is_type_cstring(a)) {
  6342. left = lb_emit_conv(p, left, t_string);
  6343. right = lb_emit_conv(p, right, t_string);
  6344. }
  6345. char const *runtime_procedure = nullptr;
  6346. switch (op_kind) {
  6347. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  6348. case Token_NotEq: runtime_procedure = "string_ne"; break;
  6349. case Token_Lt: runtime_procedure = "string_lt"; break;
  6350. case Token_Gt: runtime_procedure = "string_gt"; break;
  6351. case Token_LtEq: runtime_procedure = "string_le"; break;
  6352. case Token_GtEq: runtime_procedure = "string_gt"; break;
  6353. }
  6354. GB_ASSERT(runtime_procedure != nullptr);
  6355. auto args = array_make<lbValue>(heap_allocator(), 2);
  6356. args[0] = left;
  6357. args[1] = right;
  6358. return lb_emit_runtime_call(p, runtime_procedure, args);
  6359. }
  6360. if (is_type_complex(a)) {
  6361. char const *runtime_procedure = "";
  6362. i64 sz = 8*type_size_of(a);
  6363. switch (sz) {
  6364. case 64:
  6365. switch (op_kind) {
  6366. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  6367. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  6368. }
  6369. break;
  6370. case 128:
  6371. switch (op_kind) {
  6372. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  6373. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  6374. }
  6375. break;
  6376. }
  6377. GB_ASSERT(runtime_procedure != nullptr);
  6378. auto args = array_make<lbValue>(heap_allocator(), 2);
  6379. args[0] = left;
  6380. args[1] = right;
  6381. return lb_emit_runtime_call(p, runtime_procedure, args);
  6382. }
  6383. if (is_type_quaternion(a)) {
  6384. char const *runtime_procedure = "";
  6385. i64 sz = 8*type_size_of(a);
  6386. switch (sz) {
  6387. case 128:
  6388. switch (op_kind) {
  6389. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  6390. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  6391. }
  6392. break;
  6393. case 256:
  6394. switch (op_kind) {
  6395. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  6396. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  6397. }
  6398. break;
  6399. }
  6400. GB_ASSERT(runtime_procedure != nullptr);
  6401. auto args = array_make<lbValue>(heap_allocator(), 2);
  6402. args[0] = left;
  6403. args[1] = right;
  6404. return lb_emit_runtime_call(p, runtime_procedure, args);
  6405. }
  6406. if (is_type_bit_set(a)) {
  6407. switch (op_kind) {
  6408. case Token_Lt:
  6409. case Token_LtEq:
  6410. case Token_Gt:
  6411. case Token_GtEq:
  6412. {
  6413. Type *it = bit_set_to_int(a);
  6414. lbValue lhs = lb_emit_transmute(p, left, it);
  6415. lbValue rhs = lb_emit_transmute(p, right, it);
  6416. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  6417. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  6418. // (lhs & rhs) == lhs
  6419. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  6420. res.type = t_llvm_bool;
  6421. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  6422. // (lhs & rhs) == rhs
  6423. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  6424. res.type = t_llvm_bool;
  6425. }
  6426. // NOTE(bill): Strict subsets
  6427. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  6428. // res &~ (lhs == rhs)
  6429. lbValue eq = {};
  6430. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  6431. eq.type = t_llvm_bool;
  6432. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  6433. }
  6434. return res;
  6435. }
  6436. }
  6437. }
  6438. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  6439. Type *t = left.type;
  6440. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  6441. Type *platform_type = integer_endian_type_to_platform_type(t);
  6442. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  6443. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  6444. left = x;
  6445. right = y;
  6446. }
  6447. }
  6448. lbValue res = {};
  6449. res.type = t_llvm_bool;
  6450. if (is_type_integer(left.type) || is_type_boolean(left.type) || is_type_pointer(left.type) || is_type_proc(left.type) || is_type_enum(left.type)) {
  6451. LLVMIntPredicate pred = {};
  6452. if (is_type_unsigned(left.type)) {
  6453. switch (op_kind) {
  6454. case Token_Gt: pred = LLVMIntUGT; break;
  6455. case Token_GtEq: pred = LLVMIntUGE; break;
  6456. case Token_Lt: pred = LLVMIntULT; break;
  6457. case Token_LtEq: pred = LLVMIntULE; break;
  6458. }
  6459. } else {
  6460. switch (op_kind) {
  6461. case Token_Gt: pred = LLVMIntSGT; break;
  6462. case Token_GtEq: pred = LLVMIntSGE; break;
  6463. case Token_Lt: pred = LLVMIntSLT; break;
  6464. case Token_LtEq: pred = LLVMIntSLE; break;
  6465. }
  6466. }
  6467. switch (op_kind) {
  6468. case Token_CmpEq: pred = LLVMIntEQ; break;
  6469. case Token_NotEq: pred = LLVMIntNE; break;
  6470. }
  6471. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  6472. } else if (is_type_float(left.type)) {
  6473. LLVMRealPredicate pred = {};
  6474. switch (op_kind) {
  6475. case Token_CmpEq: pred = LLVMRealOEQ; break;
  6476. case Token_Gt: pred = LLVMRealOGT; break;
  6477. case Token_GtEq: pred = LLVMRealOGE; break;
  6478. case Token_Lt: pred = LLVMRealOLT; break;
  6479. case Token_LtEq: pred = LLVMRealOLE; break;
  6480. case Token_NotEq: pred = LLVMRealONE; break;
  6481. }
  6482. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  6483. } else if (is_type_typeid(left.type)) {
  6484. LLVMIntPredicate pred = {};
  6485. switch (op_kind) {
  6486. case Token_Gt: pred = LLVMIntUGT; break;
  6487. case Token_GtEq: pred = LLVMIntUGE; break;
  6488. case Token_Lt: pred = LLVMIntULT; break;
  6489. case Token_LtEq: pred = LLVMIntULE; break;
  6490. case Token_CmpEq: pred = LLVMIntEQ; break;
  6491. case Token_NotEq: pred = LLVMIntNE; break;
  6492. }
  6493. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  6494. } else {
  6495. GB_PANIC("Unhandled comparison kind %s %.*s %s", type_to_string(left.type), LIT(token_strings[op_kind]), type_to_string(right.type));
  6496. }
  6497. return res;
  6498. }
  6499. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  6500. ast_node(pl, ProcLit, expr);
  6501. // NOTE(bill): Generate a new name
  6502. // parent$count
  6503. isize name_len = prefix_name.len + 1 + 8 + 1;
  6504. char *name_text = gb_alloc_array(heap_allocator(), char, name_len);
  6505. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  6506. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  6507. String name = make_string((u8 *)name_text, name_len-1);
  6508. Type *type = type_of_expr(expr);
  6509. set_procedure_abi_types(heap_allocator(), type);
  6510. Token token = {};
  6511. token.pos = ast_token(expr).pos;
  6512. token.kind = Token_Ident;
  6513. token.string = name;
  6514. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  6515. e->decl_info = pl->decl;
  6516. lbProcedure *p = lb_create_procedure(m, e);
  6517. lbValue value = {};
  6518. value.value = p->value;
  6519. value.type = p->type;
  6520. array_add(&m->procedures_to_generate, p);
  6521. if (parent != nullptr) {
  6522. array_add(&parent->children, p);
  6523. } else {
  6524. map_set(&m->members, hash_string(name), value);
  6525. }
  6526. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  6527. return value;
  6528. }
  6529. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  6530. lbModule *m = p->module;
  6531. Type *src_type = value.type;
  6532. bool is_ptr = is_type_pointer(src_type);
  6533. bool is_tuple = true;
  6534. Type *tuple = type;
  6535. if (type->kind != Type_Tuple) {
  6536. is_tuple = false;
  6537. tuple = make_optional_ok_type(type);
  6538. }
  6539. lbAddr v = lb_add_local_generated(p, tuple, true);
  6540. if (is_ptr) {
  6541. value = lb_emit_load(p, value);
  6542. }
  6543. Type *src = base_type(type_deref(src_type));
  6544. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  6545. Type *dst = tuple->Tuple.variables[0]->type;
  6546. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  6547. lbValue tag = {};
  6548. lbValue dst_tag = {};
  6549. lbValue cond = {};
  6550. lbValue data = {};
  6551. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  6552. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  6553. if (is_type_union_maybe_pointer(src)) {
  6554. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  6555. } else {
  6556. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  6557. dst_tag = lb_const_union_tag(m, src, dst);
  6558. }
  6559. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  6560. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  6561. if (data.value != nullptr) {
  6562. GB_ASSERT(is_type_union_maybe_pointer(src));
  6563. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  6564. } else {
  6565. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  6566. }
  6567. lb_emit_if(p, cond, ok_block, end_block);
  6568. lb_start_block(p, ok_block);
  6569. if (data.value == nullptr) {
  6570. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  6571. }
  6572. lb_emit_store(p, gep0, data);
  6573. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  6574. lb_emit_jump(p, end_block);
  6575. lb_start_block(p, end_block);
  6576. if (!is_tuple) {
  6577. if (do_conversion_check) {
  6578. // NOTE(bill): Panic on invalid conversion
  6579. Type *dst_type = tuple->Tuple.variables[0]->type;
  6580. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  6581. auto args = array_make<lbValue>(heap_allocator(), 6);
  6582. args[0] = ok;
  6583. args[1] = lb_const_string(m, pos.file);
  6584. args[2] = lb_const_int(m, t_int, pos.line);
  6585. args[3] = lb_const_int(m, t_int, pos.column);
  6586. args[4] = lb_typeid(m, src_type);
  6587. args[5] = lb_typeid(m, dst_type);
  6588. lb_emit_runtime_call(p, "type_assertion_check", args);
  6589. }
  6590. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  6591. }
  6592. return lb_addr_load(p, v);
  6593. }
  6594. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  6595. lbModule *m = p->module;
  6596. Type *src_type = value.type;
  6597. if (is_type_pointer(src_type)) {
  6598. value = lb_emit_load(p, value);
  6599. }
  6600. bool is_tuple = true;
  6601. Type *tuple = type;
  6602. if (type->kind != Type_Tuple) {
  6603. is_tuple = false;
  6604. tuple = make_optional_ok_type(type);
  6605. }
  6606. Type *dst_type = tuple->Tuple.variables[0]->type;
  6607. lbAddr v = lb_add_local_generated(p, tuple, true);
  6608. lbValue dst_typeid = lb_typeid(m, dst_type);
  6609. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  6610. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  6611. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  6612. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  6613. lb_emit_if(p, cond, ok_block, end_block);
  6614. lb_start_block(p, ok_block);
  6615. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  6616. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  6617. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  6618. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  6619. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  6620. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  6621. lb_emit_jump(p, end_block);
  6622. lb_start_block(p, end_block);
  6623. if (!is_tuple) {
  6624. // NOTE(bill): Panic on invalid conversion
  6625. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  6626. auto args = array_make<lbValue>(heap_allocator(), 6);
  6627. args[0] = ok;
  6628. args[1] = lb_const_string(m, pos.file);
  6629. args[2] = lb_const_int(m, t_int, pos.line);
  6630. args[3] = lb_const_int(m, t_int, pos.column);
  6631. args[4] = any_typeid;
  6632. args[5] = dst_typeid;
  6633. lb_emit_runtime_call(p, "type_assertion_check", args);
  6634. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  6635. }
  6636. return v;
  6637. }
  6638. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  6639. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  6640. }
  6641. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  6642. lbModule *m = p->module;
  6643. expr = unparen_expr(expr);
  6644. TypeAndValue tv = type_and_value_of_expr(expr);
  6645. GB_ASSERT(tv.mode != Addressing_Invalid);
  6646. GB_ASSERT(tv.mode != Addressing_Type);
  6647. if (tv.value.kind != ExactValue_Invalid) {
  6648. // NOTE(bill): Short on constant values
  6649. return lb_const_value(p->module, tv.type, tv.value);
  6650. }
  6651. switch (expr->kind) {
  6652. case_ast_node(bl, BasicLit, expr);
  6653. TokenPos pos = bl->token.pos;
  6654. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  6655. case_end;
  6656. case_ast_node(bd, BasicDirective, expr);
  6657. TokenPos pos = bd->token.pos;
  6658. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  6659. case_end;
  6660. case_ast_node(i, Implicit, expr);
  6661. return lb_addr_load(p, lb_build_addr(p, expr));
  6662. case_end;
  6663. case_ast_node(u, Undef, expr)
  6664. lbValue res = {};
  6665. if (is_type_untyped(tv.type)) {
  6666. res.value = nullptr;
  6667. res.type = t_untyped_undef;
  6668. } else {
  6669. res.value = LLVMGetUndef(lb_type(m, tv.type));
  6670. res.type = tv.type;
  6671. }
  6672. return res;
  6673. case_end;
  6674. case_ast_node(i, Ident, expr);
  6675. Entity *e = entity_of_ident(expr);
  6676. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  6677. if (e->kind == Entity_Builtin) {
  6678. Token token = ast_token(expr);
  6679. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  6680. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  6681. LIT(token.pos.file), token.pos.line, token.pos.column);
  6682. return {};
  6683. } else if (e->kind == Entity_Nil) {
  6684. lbValue res = {};
  6685. res.value = nullptr;
  6686. res.type = e->type;
  6687. return res;
  6688. }
  6689. GB_ASSERT(e->kind != Entity_ProcGroup);
  6690. auto *found = map_get(&p->module->values, hash_entity(e));
  6691. if (found) {
  6692. auto v = *found;
  6693. // NOTE(bill): This is because pointers are already pointers in LLVM
  6694. if (is_type_proc(v.type)) {
  6695. return v;
  6696. }
  6697. return lb_emit_load(p, v);
  6698. } else if (e != nullptr && e->kind == Entity_Variable) {
  6699. return lb_addr_load(p, lb_build_addr(p, expr));
  6700. }
  6701. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  6702. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(e->pkg->name), LIT(e->token.string), e, type_to_string(e->type), expr);
  6703. return {};
  6704. case_end;
  6705. case_ast_node(de, DerefExpr, expr);
  6706. return lb_addr_load(p, lb_build_addr(p, expr));
  6707. case_end;
  6708. case_ast_node(se, SelectorExpr, expr);
  6709. TypeAndValue tav = type_and_value_of_expr(expr);
  6710. GB_ASSERT(tav.mode != Addressing_Invalid);
  6711. return lb_addr_load(p, lb_build_addr(p, expr));
  6712. case_end;
  6713. case_ast_node(ise, ImplicitSelectorExpr, expr);
  6714. TypeAndValue tav = type_and_value_of_expr(expr);
  6715. GB_ASSERT(tav.mode == Addressing_Constant);
  6716. return lb_const_value(p->module, tv.type, tv.value);
  6717. case_end;
  6718. case_ast_node(te, TernaryExpr, expr);
  6719. LLVMValueRef incoming_values[2] = {};
  6720. LLVMBasicBlockRef incoming_blocks[2] = {};
  6721. GB_ASSERT(te->y != nullptr);
  6722. lbBlock *then = lb_create_block(p, "if.then");
  6723. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  6724. lbBlock *else_ = lb_create_block(p, "if.else");
  6725. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  6726. lb_start_block(p, then);
  6727. Type *type = default_type(type_of_expr(expr));
  6728. lb_open_scope(p);
  6729. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  6730. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6731. lb_emit_jump(p, done);
  6732. lb_start_block(p, else_);
  6733. lb_open_scope(p);
  6734. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  6735. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6736. lb_emit_jump(p, done);
  6737. lb_start_block(p, done);
  6738. lbValue res = {};
  6739. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  6740. res.type = type;
  6741. GB_ASSERT(p->curr_block->preds.count >= 2);
  6742. incoming_blocks[0] = p->curr_block->preds[0]->block;
  6743. incoming_blocks[1] = p->curr_block->preds[1]->block;
  6744. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  6745. return res;
  6746. case_end;
  6747. case_ast_node(te, TernaryIfExpr, expr);
  6748. LLVMValueRef incoming_values[2] = {};
  6749. LLVMBasicBlockRef incoming_blocks[2] = {};
  6750. GB_ASSERT(te->y != nullptr);
  6751. lbBlock *then = lb_create_block(p, "if.then");
  6752. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  6753. lbBlock *else_ = lb_create_block(p, "if.else");
  6754. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  6755. lb_start_block(p, then);
  6756. Type *type = default_type(type_of_expr(expr));
  6757. lb_open_scope(p);
  6758. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  6759. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6760. lb_emit_jump(p, done);
  6761. lb_start_block(p, else_);
  6762. lb_open_scope(p);
  6763. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  6764. lb_close_scope(p, lbDeferExit_Default, nullptr);
  6765. lb_emit_jump(p, done);
  6766. lb_start_block(p, done);
  6767. lbValue res = {};
  6768. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  6769. res.type = type;
  6770. GB_ASSERT(p->curr_block->preds.count >= 2);
  6771. incoming_blocks[0] = p->curr_block->preds[0]->block;
  6772. incoming_blocks[1] = p->curr_block->preds[1]->block;
  6773. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  6774. return res;
  6775. case_end;
  6776. case_ast_node(te, TernaryWhenExpr, expr);
  6777. TypeAndValue tav = type_and_value_of_expr(te->cond);
  6778. GB_ASSERT(tav.mode == Addressing_Constant);
  6779. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  6780. if (tav.value.value_bool) {
  6781. return lb_build_expr(p, te->x);
  6782. } else {
  6783. return lb_build_expr(p, te->y);
  6784. }
  6785. case_end;
  6786. case_ast_node(ta, TypeAssertion, expr);
  6787. TokenPos pos = ast_token(expr).pos;
  6788. Type *type = tv.type;
  6789. lbValue e = lb_build_expr(p, ta->expr);
  6790. Type *t = type_deref(e.type);
  6791. if (is_type_union(t)) {
  6792. return lb_emit_union_cast(p, e, type, pos);
  6793. } else if (is_type_any(t)) {
  6794. return lb_emit_any_cast(p, e, type, pos);
  6795. } else {
  6796. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  6797. }
  6798. case_end;
  6799. case_ast_node(tc, TypeCast, expr);
  6800. lbValue e = lb_build_expr(p, tc->expr);
  6801. switch (tc->token.kind) {
  6802. case Token_cast:
  6803. return lb_emit_conv(p, e, tv.type);
  6804. case Token_transmute:
  6805. return lb_emit_transmute(p, e, tv.type);
  6806. }
  6807. GB_PANIC("Invalid AST TypeCast");
  6808. case_end;
  6809. case_ast_node(ac, AutoCast, expr);
  6810. return lb_build_expr(p, ac->expr);
  6811. case_end;
  6812. case_ast_node(ue, UnaryExpr, expr);
  6813. switch (ue->op.kind) {
  6814. case Token_And: {
  6815. Ast *ue_expr = unparen_expr(ue->expr);
  6816. if (ue_expr->kind == Ast_TypeAssertion) {
  6817. gbAllocator a = heap_allocator();
  6818. GB_ASSERT(is_type_pointer(tv.type));
  6819. ast_node(ta, TypeAssertion, ue_expr);
  6820. TokenPos pos = ast_token(expr).pos;
  6821. Type *type = type_of_expr(ue_expr);
  6822. GB_ASSERT(!is_type_tuple(type));
  6823. lbValue e = lb_build_expr(p, ta->expr);
  6824. Type *t = type_deref(e.type);
  6825. if (is_type_union(t)) {
  6826. lbValue v = e;
  6827. if (!is_type_pointer(v.type)) {
  6828. v = lb_address_from_load_or_generate_local(p, v);
  6829. }
  6830. Type *src_type = type_deref(v.type);
  6831. Type *dst_type = type;
  6832. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  6833. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  6834. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  6835. auto args = array_make<lbValue>(heap_allocator(), 6);
  6836. args[0] = ok;
  6837. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  6838. args[2] = lb_const_int(p->module, t_int, pos.line);
  6839. args[3] = lb_const_int(p->module, t_int, pos.column);
  6840. args[4] = lb_typeid(p->module, src_type);
  6841. args[5] = lb_typeid(p->module, dst_type);
  6842. lb_emit_runtime_call(p, "type_assertion_check", args);
  6843. lbValue data_ptr = v;
  6844. return lb_emit_conv(p, data_ptr, tv.type);
  6845. } else if (is_type_any(t)) {
  6846. lbValue v = e;
  6847. if (is_type_pointer(v.type)) {
  6848. v = lb_emit_load(p, v);
  6849. }
  6850. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  6851. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  6852. lbValue id = lb_typeid(p->module, type);
  6853. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  6854. auto args = array_make<lbValue>(heap_allocator(), 6);
  6855. args[0] = ok;
  6856. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  6857. args[2] = lb_const_int(p->module, t_int, pos.line);
  6858. args[3] = lb_const_int(p->module, t_int, pos.column);
  6859. args[4] = any_id;
  6860. args[5] = id;
  6861. lb_emit_runtime_call(p, "type_assertion_check", args);
  6862. return lb_emit_conv(p, data_ptr, tv.type);
  6863. } else {
  6864. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  6865. }
  6866. }
  6867. return lb_build_addr_ptr(p, ue->expr);
  6868. }
  6869. default:
  6870. {
  6871. lbValue v = lb_build_expr(p, ue->expr);
  6872. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  6873. }
  6874. }
  6875. case_end;
  6876. case_ast_node(be, BinaryExpr, expr);
  6877. return lb_build_binary_expr(p, expr);
  6878. case_end;
  6879. case_ast_node(pl, ProcLit, expr);
  6880. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  6881. case_end;
  6882. case_ast_node(cl, CompoundLit, expr);
  6883. return lb_addr_load(p, lb_build_addr(p, expr));
  6884. case_end;
  6885. case_ast_node(ce, CallExpr, expr);
  6886. return lb_build_call_expr(p, expr);
  6887. case_end;
  6888. case_ast_node(se, SliceExpr, expr);
  6889. return lb_addr_load(p, lb_build_addr(p, expr));
  6890. case_end;
  6891. case_ast_node(ie, IndexExpr, expr);
  6892. return lb_addr_load(p, lb_build_addr(p, expr));
  6893. case_end;
  6894. }
  6895. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  6896. return {};
  6897. }
  6898. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  6899. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  6900. String name = e->token.string;
  6901. Entity *parent = e->using_parent;
  6902. Selection sel = lookup_field(parent->type, name, false);
  6903. GB_ASSERT(sel.entity != nullptr);
  6904. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  6905. lbValue v = {};
  6906. if (pv != nullptr) {
  6907. v = *pv;
  6908. } else {
  6909. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  6910. v = lb_build_addr_ptr(p, e->using_expr);
  6911. }
  6912. GB_ASSERT(v.value != nullptr);
  6913. GB_ASSERT(parent->type == type_deref(v.type));
  6914. return lb_emit_deep_field_gep(p, v, sel);
  6915. }
  6916. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  6917. GB_ASSERT(e != nullptr);
  6918. if (e->kind == Entity_Constant) {
  6919. Type *t = default_type(type_of_expr(expr));
  6920. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  6921. lbAddr g = lb_add_global_generated(p->module, t, v);
  6922. return g;
  6923. }
  6924. lbValue v = {};
  6925. lbValue *found = map_get(&p->module->values, hash_entity(e));
  6926. if (found) {
  6927. v = *found;
  6928. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  6929. // NOTE(bill): Calculate the using variable every time
  6930. v = lb_get_using_variable(p, e);
  6931. }
  6932. if (v.value == nullptr) {
  6933. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  6934. LIT(p->name),
  6935. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  6936. GB_PANIC("Unknown value");
  6937. }
  6938. return lb_addr(v);
  6939. }
  6940. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  6941. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  6942. gbAllocator a = heap_allocator();
  6943. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  6944. map_type = base_type(map_type);
  6945. GB_ASSERT(map_type->kind == Type_Map);
  6946. Type *key_type = map_type->Map.key;
  6947. Type *val_type = map_type->Map.value;
  6948. // NOTE(bill): Removes unnecessary allocation if split gep
  6949. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  6950. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  6951. lb_emit_store(p, gep0, m);
  6952. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_const_bool(p->module, t_bool, is_type_string(key_type)));
  6953. i64 entry_size = type_size_of (map_type->Map.entry_type);
  6954. i64 entry_align = type_align_of (map_type->Map.entry_type);
  6955. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  6956. i64 value_size = type_size_of (map_type->Map.value);
  6957. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  6958. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  6959. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, value_offset));
  6960. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, value_size));
  6961. return lb_addr_load(p, h);
  6962. }
  6963. lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) {
  6964. Type *hash_type = t_u64;
  6965. lbAddr v = lb_add_local_generated(p, t_map_key, true);
  6966. Type *t = base_type(key.type);
  6967. key = lb_emit_conv(p, key, key_type);
  6968. if (is_type_integer(t)) {
  6969. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type));
  6970. } else if (is_type_enum(t)) {
  6971. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type));
  6972. } else if (is_type_typeid(t)) {
  6973. lbValue i = lb_emit_transmute(p, key, t_uint);
  6974. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, i, hash_type));
  6975. } else if (is_type_pointer(t)) {
  6976. lbValue ptr = lb_emit_conv(p, key, t_uintptr);
  6977. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, ptr, hash_type));
  6978. } else if (is_type_float(t)) {
  6979. lbValue bits = {};
  6980. i64 size = type_size_of(t);
  6981. switch (8*size) {
  6982. case 32: bits = lb_emit_transmute(p, key, t_u32); break;
  6983. case 64: bits = lb_emit_transmute(p, key, t_u64); break;
  6984. default: GB_PANIC("Unhandled float size: %lld bits", size); break;
  6985. }
  6986. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, bits, hash_type));
  6987. } else if (is_type_string(t)) {
  6988. lbValue str = lb_emit_conv(p, key, t_string);
  6989. lbValue hashed_str = {};
  6990. if (false && lb_is_const(str)) {
  6991. String value = lb_get_const_string(p->module, str);
  6992. u64 hs = fnv64a(value.text, value.len);
  6993. hashed_str = lb_const_value(p->module, t_u64, exact_value_u64(hs));
  6994. } else {
  6995. auto args = array_make<lbValue>(heap_allocator(), 1);
  6996. args[0] = str;
  6997. hashed_str = lb_emit_runtime_call(p, "default_hash_string", args);
  6998. }
  6999. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), hashed_str);
  7000. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), str);
  7001. } else {
  7002. GB_PANIC("Unhandled map key type");
  7003. }
  7004. return lb_addr_load(p, v);
  7005. }
  7006. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  7007. lbValue map_key, lbValue map_value) {
  7008. map_type = base_type(map_type);
  7009. GB_ASSERT(map_type->kind == Type_Map);
  7010. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  7011. lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key);
  7012. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  7013. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  7014. lb_addr_store(p, value_addr, v);
  7015. auto args = array_make<lbValue>(heap_allocator(), 4);
  7016. args[0] = h;
  7017. args[1] = key;
  7018. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  7019. args[3] = lb_emit_source_code_location(p, nullptr);
  7020. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  7021. }
  7022. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  7023. expr = unparen_expr(expr);
  7024. switch (expr->kind) {
  7025. case_ast_node(i, Implicit, expr);
  7026. lbAddr v = {};
  7027. switch (i->kind) {
  7028. case Token_context:
  7029. v = lb_find_or_generate_context_ptr(p);
  7030. break;
  7031. }
  7032. GB_ASSERT(v.addr.value != nullptr);
  7033. return v;
  7034. case_end;
  7035. case_ast_node(i, Ident, expr);
  7036. if (is_blank_ident(expr)) {
  7037. lbAddr val = {};
  7038. return val;
  7039. }
  7040. String name = i->token.string;
  7041. Entity *e = entity_of_ident(expr);
  7042. return lb_build_addr_from_entity(p, e, expr);
  7043. case_end;
  7044. case_ast_node(se, SelectorExpr, expr);
  7045. Ast *sel = unparen_expr(se->selector);
  7046. if (sel->kind == Ast_Ident) {
  7047. String selector = sel->Ident.token.string;
  7048. TypeAndValue tav = type_and_value_of_expr(se->expr);
  7049. if (tav.mode == Addressing_Invalid) {
  7050. // NOTE(bill): Imports
  7051. Entity *imp = entity_of_ident(se->expr);
  7052. if (imp != nullptr) {
  7053. GB_ASSERT(imp->kind == Entity_ImportName);
  7054. }
  7055. return lb_build_addr(p, unparen_expr(se->selector));
  7056. }
  7057. Type *type = base_type(tav.type);
  7058. if (tav.mode == Addressing_Type) { // Addressing_Type
  7059. Selection sel = lookup_field(type, selector, true);
  7060. Entity *e = sel.entity;
  7061. GB_ASSERT(e->kind == Entity_Variable);
  7062. GB_ASSERT(e->flags & EntityFlag_TypeField);
  7063. String name = e->token.string;
  7064. /*if (name == "names") {
  7065. lbValue ti_ptr = lb_type_info(m, type);
  7066. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  7067. lbValue names_ptr = nullptr;
  7068. if (is_type_enum(type)) {
  7069. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  7070. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  7071. } else if (type->kind == Type_Struct) {
  7072. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  7073. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  7074. }
  7075. return ir_addr(names_ptr);
  7076. } else */{
  7077. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  7078. }
  7079. GB_PANIC("Unreachable");
  7080. }
  7081. Selection sel = lookup_field(type, selector, false);
  7082. GB_ASSERT(sel.entity != nullptr);
  7083. if (sel.entity->type->kind == Type_BitFieldValue) {
  7084. lbAddr addr = lb_build_addr(p, se->expr);
  7085. Type *bft = type_deref(lb_addr_type(addr));
  7086. if (sel.index.count == 1) {
  7087. GB_ASSERT(is_type_bit_field(bft));
  7088. i32 index = sel.index[0];
  7089. return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index);
  7090. } else {
  7091. Selection s = sel;
  7092. s.index.count--;
  7093. i32 index = s.index[s.index.count-1];
  7094. lbValue a = lb_addr_get_ptr(p, addr);
  7095. a = lb_emit_deep_field_gep(p, a, s);
  7096. return lb_addr_bit_field(a, index);
  7097. }
  7098. } else {
  7099. lbAddr addr = lb_build_addr(p, se->expr);
  7100. if (addr.kind == lbAddr_Context) {
  7101. GB_ASSERT(sel.index.count > 0);
  7102. if (addr.ctx.sel.index.count >= 0) {
  7103. sel = selection_combine(addr.ctx.sel, sel);
  7104. }
  7105. addr.ctx.sel = sel;
  7106. addr.kind = lbAddr_Context;
  7107. return addr;
  7108. } else if (addr.kind == lbAddr_SoaVariable) {
  7109. lbValue index = addr.soa.index;
  7110. i32 first_index = sel.index[0];
  7111. Selection sub_sel = sel;
  7112. sub_sel.index.data += 1;
  7113. sub_sel.index.count -= 1;
  7114. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  7115. Type *t = base_type(type_deref(addr.addr.type));
  7116. GB_ASSERT(is_type_soa_struct(t));
  7117. // TODO(bill): Bounds check
  7118. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  7119. lbValue len = lb_soa_struct_len(p, addr.addr);
  7120. // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  7121. }
  7122. lbValue item = {};
  7123. if (t->Struct.soa_kind == StructSoa_Fixed) {
  7124. item = lb_emit_array_ep(p, arr, index);
  7125. } else {
  7126. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  7127. }
  7128. if (sub_sel.index.count > 0) {
  7129. item = lb_emit_deep_field_gep(p, item, sub_sel);
  7130. }
  7131. return lb_addr(item);
  7132. }
  7133. lbValue a = lb_addr_get_ptr(p, addr);
  7134. a = lb_emit_deep_field_gep(p, a, sel);
  7135. return lb_addr(a);
  7136. }
  7137. } else {
  7138. GB_PANIC("Unsupported selector expression");
  7139. }
  7140. case_end;
  7141. case_ast_node(ta, TypeAssertion, expr);
  7142. gbAllocator a = heap_allocator();
  7143. TokenPos pos = ast_token(expr).pos;
  7144. lbValue e = lb_build_expr(p, ta->expr);
  7145. Type *t = type_deref(e.type);
  7146. if (is_type_union(t)) {
  7147. Type *type = type_of_expr(expr);
  7148. lbAddr v = lb_add_local_generated(p, type, false);
  7149. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  7150. return v;
  7151. } else if (is_type_any(t)) {
  7152. Type *type = type_of_expr(expr);
  7153. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  7154. } else {
  7155. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  7156. }
  7157. case_end;
  7158. case_ast_node(ue, UnaryExpr, expr);
  7159. switch (ue->op.kind) {
  7160. case Token_And: {
  7161. return lb_build_addr(p, ue->expr);
  7162. }
  7163. default:
  7164. GB_PANIC("Invalid unary expression for lb_build_addr");
  7165. }
  7166. case_end;
  7167. case_ast_node(be, BinaryExpr, expr);
  7168. lbValue v = lb_build_expr(p, expr);
  7169. Type *t = v.type;
  7170. if (is_type_pointer(t)) {
  7171. return lb_addr(v);
  7172. }
  7173. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  7174. case_end;
  7175. case_ast_node(ie, IndexExpr, expr);
  7176. Type *t = base_type(type_of_expr(ie->expr));
  7177. gbAllocator a = heap_allocator();
  7178. bool deref = is_type_pointer(t);
  7179. t = base_type(type_deref(t));
  7180. if (is_type_soa_struct(t)) {
  7181. // SOA STRUCTURES!!!!
  7182. lbValue val = lb_build_addr_ptr(p, ie->expr);
  7183. if (deref) {
  7184. val = lb_emit_load(p, val);
  7185. }
  7186. lbValue index = lb_build_expr(p, ie->index);
  7187. return lb_addr_soa_variable(val, index, ie->index);
  7188. }
  7189. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  7190. // SOA Structures for slices/dynamic arrays
  7191. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  7192. lbValue field = lb_build_expr(p, ie->expr);
  7193. lbValue index = lb_build_expr(p, ie->index);
  7194. if (!build_context.no_bounds_check) {
  7195. // // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  7196. // GB_ASSERT(LLVMIsALoadInst(field.value));
  7197. // lbValue a = {};
  7198. // a.value = LLVMGetOperand(field.value, 0);
  7199. // a.type = alloc_type_pointer(field.type);
  7200. // irInstr *b = &a->Instr;
  7201. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  7202. // lbValue base_struct = b->StructElementPtr.address;
  7203. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  7204. // lbValue len = ir_soa_struct_len(p, base_struct);
  7205. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7206. }
  7207. lbValue val = lb_emit_ptr_offset(p, field, index);
  7208. return lb_addr(val);
  7209. }
  7210. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  7211. if (is_type_map(t)) {
  7212. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  7213. if (deref) {
  7214. map_val = lb_emit_load(p, map_val);
  7215. }
  7216. lbValue key = lb_build_expr(p, ie->index);
  7217. key = lb_emit_conv(p, key, t->Map.key);
  7218. Type *result_type = type_of_expr(expr);
  7219. return lb_addr_map(map_val, key, t, result_type);
  7220. }
  7221. lbValue using_addr = {};
  7222. switch (t->kind) {
  7223. case Type_Array: {
  7224. lbValue array = {};
  7225. if (using_addr.value != nullptr) {
  7226. array = using_addr;
  7227. } else {
  7228. array = lb_build_addr_ptr(p, ie->expr);
  7229. if (deref) {
  7230. array = lb_emit_load(p, array);
  7231. }
  7232. }
  7233. lbValue index = lb_build_expr(p, ie->index);
  7234. index = lb_emit_conv(p, index, t_int);
  7235. lbValue elem = lb_emit_array_ep(p, array, index);
  7236. auto index_tv = type_and_value_of_expr(ie->index);
  7237. if (index_tv.mode != Addressing_Constant) {
  7238. // lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  7239. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7240. }
  7241. return lb_addr(elem);
  7242. }
  7243. case Type_EnumeratedArray: {
  7244. lbValue array = {};
  7245. if (using_addr.value != nullptr) {
  7246. array = using_addr;
  7247. } else {
  7248. array = lb_build_addr_ptr(p, ie->expr);
  7249. if (deref) {
  7250. array = lb_emit_load(p, array);
  7251. }
  7252. }
  7253. Type *index_type = t->EnumeratedArray.index;
  7254. auto index_tv = type_and_value_of_expr(ie->index);
  7255. lbValue index = {};
  7256. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  7257. if (index_tv.mode == Addressing_Constant) {
  7258. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  7259. index = lb_const_value(p->module, index_type, idx);
  7260. } else {
  7261. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7262. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  7263. }
  7264. } else {
  7265. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7266. }
  7267. lbValue elem = lb_emit_array_ep(p, array, index);
  7268. if (index_tv.mode != Addressing_Constant) {
  7269. // lbValue len = ir_const_int(t->EnumeratedArray.count);
  7270. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7271. }
  7272. return lb_addr(elem);
  7273. }
  7274. case Type_Slice: {
  7275. lbValue slice = {};
  7276. if (using_addr.value != nullptr) {
  7277. slice = lb_emit_load(p, using_addr);
  7278. } else {
  7279. slice = lb_build_expr(p, ie->expr);
  7280. if (deref) {
  7281. slice = lb_emit_load(p, slice);
  7282. }
  7283. }
  7284. lbValue elem = lb_slice_elem(p, slice);
  7285. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7286. lbValue len = lb_slice_len(p, slice);
  7287. // ir_emit_bounds_check(p, ast_token(ie->index), index, len);
  7288. lbValue v = lb_emit_ptr_offset(p, elem, index);
  7289. return lb_addr(v);
  7290. }
  7291. case Type_DynamicArray: {
  7292. lbValue dynamic_array = {};
  7293. if (using_addr.value != nullptr) {
  7294. dynamic_array = lb_emit_load(p, using_addr);
  7295. } else {
  7296. dynamic_array = lb_build_expr(p, ie->expr);
  7297. if (deref) {
  7298. dynamic_array = lb_emit_load(p, dynamic_array);
  7299. }
  7300. }
  7301. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  7302. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  7303. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7304. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  7305. lbValue v = lb_emit_ptr_offset(p, elem, index);
  7306. return lb_addr(v);
  7307. }
  7308. case Type_Basic: { // Basic_string
  7309. lbValue str;
  7310. lbValue elem;
  7311. lbValue len;
  7312. lbValue index;
  7313. if (using_addr.value != nullptr) {
  7314. str = lb_emit_load(p, using_addr);
  7315. } else {
  7316. str = lb_build_expr(p, ie->expr);
  7317. if (deref) {
  7318. str = lb_emit_load(p, str);
  7319. }
  7320. }
  7321. elem = lb_string_elem(p, str);
  7322. len = lb_string_len(p, str);
  7323. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  7324. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  7325. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  7326. }
  7327. }
  7328. case_end;
  7329. case_ast_node(se, SliceExpr, expr);
  7330. gbAllocator a = heap_allocator();
  7331. lbValue low = lb_const_int(p->module, t_int, 0);
  7332. lbValue high = {};
  7333. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  7334. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  7335. bool no_indices = se->low == nullptr && se->high == nullptr;
  7336. lbValue addr = lb_build_addr_ptr(p, se->expr);
  7337. lbValue base = lb_emit_load(p, addr);
  7338. Type *type = base_type(base.type);
  7339. if (is_type_pointer(type)) {
  7340. type = base_type(type_deref(type));
  7341. addr = base;
  7342. base = lb_emit_load(p, base);
  7343. }
  7344. // TODO(bill): Cleanup like mad!
  7345. switch (type->kind) {
  7346. case Type_Slice: {
  7347. Type *slice_type = type;
  7348. lbValue len = lb_slice_len(p, base);
  7349. if (high.value == nullptr) high = len;
  7350. if (!no_indices) {
  7351. // ir_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7352. }
  7353. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  7354. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7355. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  7356. lb_fill_slice(p, slice, elem, new_len);
  7357. return slice;
  7358. }
  7359. case Type_DynamicArray: {
  7360. Type *elem_type = type->DynamicArray.elem;
  7361. Type *slice_type = alloc_type_slice(elem_type);
  7362. lbValue len = lb_dynamic_array_len(p, base);
  7363. if (high.value == nullptr) high = len;
  7364. if (!no_indices) {
  7365. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7366. }
  7367. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  7368. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7369. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  7370. lb_fill_slice(p, slice, elem, new_len);
  7371. return slice;
  7372. }
  7373. case Type_Array: {
  7374. Type *slice_type = alloc_type_slice(type->Array.elem);
  7375. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  7376. if (high.value == nullptr) high = len;
  7377. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  7378. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  7379. if (!low_const || !high_const) {
  7380. if (!no_indices) {
  7381. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7382. }
  7383. }
  7384. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, addr), low);
  7385. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7386. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  7387. lb_fill_slice(p, slice, elem, new_len);
  7388. return slice;
  7389. }
  7390. case Type_Basic: {
  7391. GB_ASSERT(type == t_string);
  7392. lbValue len = lb_string_len(p, base);
  7393. if (high.value == nullptr) high = len;
  7394. if (!no_indices) {
  7395. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7396. }
  7397. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  7398. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7399. lbAddr str = lb_add_local_generated(p, t_string, false);
  7400. lb_fill_string(p, str, elem, new_len);
  7401. return str;
  7402. }
  7403. case Type_Struct:
  7404. if (is_type_soa_struct(type)) {
  7405. lbValue len = lb_soa_struct_len(p, addr);
  7406. if (high.value == nullptr) high = len;
  7407. if (!no_indices) {
  7408. // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  7409. }
  7410. #if 1
  7411. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  7412. if (type->Struct.soa_kind == StructSoa_Fixed) {
  7413. i32 field_count = cast(i32)type->Struct.fields.count;
  7414. for (i32 i = 0; i < field_count; i++) {
  7415. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  7416. lbValue field_src = lb_emit_struct_ep(p, addr, i);
  7417. field_src = lb_emit_array_ep(p, field_src, low);
  7418. lb_emit_store(p, field_dst, field_src);
  7419. }
  7420. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  7421. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7422. lb_emit_store(p, len_dst, new_len);
  7423. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  7424. if (no_indices) {
  7425. lb_addr_store(p, dst, base);
  7426. } else {
  7427. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  7428. for (i32 i = 0; i < field_count; i++) {
  7429. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  7430. lbValue field_src = lb_emit_struct_ev(p, base, i);
  7431. field_src = lb_emit_ptr_offset(p, field_src, low);
  7432. lb_emit_store(p, field_dst, field_src);
  7433. }
  7434. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  7435. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7436. lb_emit_store(p, len_dst, new_len);
  7437. }
  7438. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  7439. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  7440. for (i32 i = 0; i < field_count; i++) {
  7441. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  7442. lbValue field_src = lb_emit_struct_ev(p, base, i);
  7443. field_src = lb_emit_ptr_offset(p, field_src, low);
  7444. lb_emit_store(p, field_dst, field_src);
  7445. }
  7446. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  7447. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  7448. lb_emit_store(p, len_dst, new_len);
  7449. }
  7450. return dst;
  7451. #endif
  7452. }
  7453. break;
  7454. }
  7455. GB_PANIC("Unknown slicable type");
  7456. case_end;
  7457. case_ast_node(de, DerefExpr, expr);
  7458. lbValue addr = lb_build_expr(p, de->expr);
  7459. return lb_addr(addr);
  7460. case_end;
  7461. case_ast_node(ce, CallExpr, expr);
  7462. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  7463. lbValue e = lb_build_expr(p, expr);
  7464. lbAddr v = lb_add_local_generated(p, e.type, false);
  7465. lb_addr_store(p, v, e);
  7466. return v;
  7467. case_end;
  7468. case_ast_node(cl, CompoundLit, expr);
  7469. Type *type = type_of_expr(expr);
  7470. Type *bt = base_type(type);
  7471. lbAddr v = lb_add_local_generated(p, type, true);
  7472. Type *et = nullptr;
  7473. switch (bt->kind) {
  7474. case Type_Array: et = bt->Array.elem; break;
  7475. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  7476. case Type_Slice: et = bt->Slice.elem; break;
  7477. case Type_BitSet: et = bt->BitSet.elem; break;
  7478. case Type_SimdVector: et = bt->SimdVector.elem; break;
  7479. }
  7480. String proc_name = {};
  7481. if (p->entity) {
  7482. proc_name = p->entity->token.string;
  7483. }
  7484. TokenPos pos = ast_token(expr).pos;
  7485. switch (bt->kind) {
  7486. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  7487. case Type_Struct: {
  7488. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  7489. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  7490. bool is_raw_union = is_type_raw_union(bt);
  7491. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  7492. TypeStruct *st = &bt->Struct;
  7493. if (cl->elems.count > 0) {
  7494. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7495. for_array(field_index, cl->elems) {
  7496. Ast *elem = cl->elems[field_index];
  7497. lbValue field_expr = {};
  7498. Entity *field = nullptr;
  7499. isize index = field_index;
  7500. if (elem->kind == Ast_FieldValue) {
  7501. ast_node(fv, FieldValue, elem);
  7502. String name = fv->field->Ident.token.string;
  7503. Selection sel = lookup_field(bt, name, false);
  7504. index = sel.index[0];
  7505. elem = fv->value;
  7506. TypeAndValue tav = type_and_value_of_expr(elem);
  7507. } else {
  7508. TypeAndValue tav = type_and_value_of_expr(elem);
  7509. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  7510. index = sel.index[0];
  7511. }
  7512. field = st->fields[index];
  7513. Type *ft = field->type;
  7514. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  7515. continue;
  7516. }
  7517. field_expr = lb_build_expr(p, elem);
  7518. Type *fet = field_expr.type;
  7519. GB_ASSERT(fet->kind != Type_Tuple);
  7520. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  7521. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  7522. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  7523. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  7524. lb_emit_store_union_variant(p, gep, field_expr, fet);
  7525. } else {
  7526. lbValue fv = lb_emit_conv(p, field_expr, ft);
  7527. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  7528. lb_emit_store(p, gep, fv);
  7529. }
  7530. }
  7531. }
  7532. break;
  7533. }
  7534. case Type_Map: {
  7535. if (cl->elems.count == 0) {
  7536. break;
  7537. }
  7538. gbAllocator a = heap_allocator();
  7539. {
  7540. auto args = array_make<lbValue>(a, 3);
  7541. args[0] = lb_gen_map_header(p, v.addr, type);
  7542. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  7543. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  7544. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  7545. }
  7546. for_array(field_index, cl->elems) {
  7547. Ast *elem = cl->elems[field_index];
  7548. ast_node(fv, FieldValue, elem);
  7549. lbValue key = lb_build_expr(p, fv->field);
  7550. lbValue value = lb_build_expr(p, fv->value);
  7551. lb_insert_dynamic_map_key_and_value(p, v, type, key, value);
  7552. }
  7553. break;
  7554. }
  7555. case Type_Array: {
  7556. if (cl->elems.count > 0) {
  7557. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7558. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7559. defer (array_free(&temp_data));
  7560. // NOTE(bill): Separate value, gep, store into their own chunks
  7561. for_array(i, cl->elems) {
  7562. Ast *elem = cl->elems[i];
  7563. if (elem->kind == Ast_FieldValue) {
  7564. ast_node(fv, FieldValue, elem);
  7565. if (lb_is_elem_const(fv->value, et)) {
  7566. continue;
  7567. }
  7568. if (is_ast_range(fv->field)) {
  7569. ast_node(ie, BinaryExpr, fv->field);
  7570. TypeAndValue lo_tav = ie->left->tav;
  7571. TypeAndValue hi_tav = ie->right->tav;
  7572. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7573. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7574. TokenKind op = ie->op.kind;
  7575. i64 lo = exact_value_to_i64(lo_tav.value);
  7576. i64 hi = exact_value_to_i64(hi_tav.value);
  7577. if (op == Token_Ellipsis) {
  7578. hi += 1;
  7579. }
  7580. lbValue value = lb_build_expr(p, fv->value);
  7581. for (i64 k = lo; k < hi; k++) {
  7582. lbCompoundLitElemTempData data = {};
  7583. data.value = value;
  7584. data.elem_index = cast(i32)k;
  7585. array_add(&temp_data, data);
  7586. }
  7587. } else {
  7588. auto tav = fv->field->tav;
  7589. GB_ASSERT(tav.mode == Addressing_Constant);
  7590. i64 index = exact_value_to_i64(tav.value);
  7591. lbValue value = lb_build_expr(p, fv->value);
  7592. lbCompoundLitElemTempData data = {};
  7593. data.value = lb_emit_conv(p, value, et);
  7594. data.expr = fv->value;
  7595. data.elem_index = cast(i32)index;
  7596. array_add(&temp_data, data);
  7597. }
  7598. } else {
  7599. if (lb_is_elem_const(elem, et)) {
  7600. continue;
  7601. }
  7602. lbCompoundLitElemTempData data = {};
  7603. data.expr = elem;
  7604. data.elem_index = cast(i32)i;
  7605. array_add(&temp_data, data);
  7606. }
  7607. }
  7608. for_array(i, temp_data) {
  7609. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  7610. }
  7611. for_array(i, temp_data) {
  7612. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  7613. auto return_ptr_hint_value = p->return_ptr_hint_value;
  7614. auto return_ptr_hint_used = p->return_ptr_hint_used;
  7615. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  7616. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  7617. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  7618. lbValue field_expr = temp_data[i].value;
  7619. Ast *expr = temp_data[i].expr;
  7620. p->return_ptr_hint_value = temp_data[i].gep;
  7621. p->return_ptr_hint_ast = unparen_expr(expr);
  7622. if (field_expr.value == nullptr) {
  7623. field_expr = lb_build_expr(p, expr);
  7624. }
  7625. Type *t = field_expr.type;
  7626. GB_ASSERT(t->kind != Type_Tuple);
  7627. lbValue ev = lb_emit_conv(p, field_expr, et);
  7628. if (!p->return_ptr_hint_used) {
  7629. temp_data[i].value = ev;
  7630. }
  7631. }
  7632. for_array(i, temp_data) {
  7633. if (temp_data[i].value.value != nullptr) {
  7634. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  7635. }
  7636. }
  7637. }
  7638. break;
  7639. }
  7640. case Type_EnumeratedArray: {
  7641. if (cl->elems.count > 0) {
  7642. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7643. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7644. defer (array_free(&temp_data));
  7645. // NOTE(bill): Separate value, gep, store into their own chunks
  7646. for_array(i, cl->elems) {
  7647. Ast *elem = cl->elems[i];
  7648. if (elem->kind == Ast_FieldValue) {
  7649. ast_node(fv, FieldValue, elem);
  7650. if (lb_is_elem_const(fv->value, et)) {
  7651. continue;
  7652. }
  7653. if (is_ast_range(fv->field)) {
  7654. ast_node(ie, BinaryExpr, fv->field);
  7655. TypeAndValue lo_tav = ie->left->tav;
  7656. TypeAndValue hi_tav = ie->right->tav;
  7657. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7658. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7659. TokenKind op = ie->op.kind;
  7660. i64 lo = exact_value_to_i64(lo_tav.value);
  7661. i64 hi = exact_value_to_i64(hi_tav.value);
  7662. if (op == Token_Ellipsis) {
  7663. hi += 1;
  7664. }
  7665. lbValue value = lb_build_expr(p, fv->value);
  7666. for (i64 k = lo; k < hi; k++) {
  7667. lbCompoundLitElemTempData data = {};
  7668. data.value = value;
  7669. data.elem_index = cast(i32)k;
  7670. array_add(&temp_data, data);
  7671. }
  7672. } else {
  7673. auto tav = fv->field->tav;
  7674. GB_ASSERT(tav.mode == Addressing_Constant);
  7675. i64 index = exact_value_to_i64(tav.value);
  7676. lbValue value = lb_build_expr(p, fv->value);
  7677. lbCompoundLitElemTempData data = {};
  7678. data.value = lb_emit_conv(p, value, et);
  7679. data.expr = fv->value;
  7680. data.elem_index = cast(i32)index;
  7681. array_add(&temp_data, data);
  7682. }
  7683. } else {
  7684. if (lb_is_elem_const(elem, et)) {
  7685. continue;
  7686. }
  7687. lbCompoundLitElemTempData data = {};
  7688. data.expr = elem;
  7689. data.elem_index = cast(i32)i;
  7690. array_add(&temp_data, data);
  7691. }
  7692. }
  7693. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  7694. for_array(i, temp_data) {
  7695. i32 index = temp_data[i].elem_index - index_offset;
  7696. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  7697. }
  7698. for_array(i, temp_data) {
  7699. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  7700. auto return_ptr_hint_value = p->return_ptr_hint_value;
  7701. auto return_ptr_hint_used = p->return_ptr_hint_used;
  7702. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  7703. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  7704. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  7705. lbValue field_expr = temp_data[i].value;
  7706. Ast *expr = temp_data[i].expr;
  7707. p->return_ptr_hint_value = temp_data[i].gep;
  7708. p->return_ptr_hint_ast = unparen_expr(expr);
  7709. if (field_expr.value == nullptr) {
  7710. field_expr = lb_build_expr(p, expr);
  7711. }
  7712. Type *t = field_expr.type;
  7713. GB_ASSERT(t->kind != Type_Tuple);
  7714. lbValue ev = lb_emit_conv(p, field_expr, et);
  7715. if (!p->return_ptr_hint_used) {
  7716. temp_data[i].value = ev;
  7717. }
  7718. }
  7719. for_array(i, temp_data) {
  7720. if (temp_data[i].value.value != nullptr) {
  7721. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  7722. }
  7723. }
  7724. }
  7725. break;
  7726. }
  7727. case Type_Slice: {
  7728. if (cl->elems.count > 0) {
  7729. Type *elem_type = bt->Slice.elem;
  7730. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  7731. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  7732. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  7733. lbValue data = lb_slice_elem(p, slice);
  7734. auto temp_data = array_make<lbCompoundLitElemTempData>(heap_allocator(), 0, cl->elems.count);
  7735. defer (array_free(&temp_data));
  7736. for_array(i, cl->elems) {
  7737. Ast *elem = cl->elems[i];
  7738. if (elem->kind == Ast_FieldValue) {
  7739. ast_node(fv, FieldValue, elem);
  7740. if (lb_is_elem_const(fv->value, et)) {
  7741. continue;
  7742. }
  7743. if (is_ast_range(fv->field)) {
  7744. ast_node(ie, BinaryExpr, fv->field);
  7745. TypeAndValue lo_tav = ie->left->tav;
  7746. TypeAndValue hi_tav = ie->right->tav;
  7747. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7748. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7749. TokenKind op = ie->op.kind;
  7750. i64 lo = exact_value_to_i64(lo_tav.value);
  7751. i64 hi = exact_value_to_i64(hi_tav.value);
  7752. if (op == Token_Ellipsis) {
  7753. hi += 1;
  7754. }
  7755. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  7756. for (i64 k = lo; k < hi; k++) {
  7757. lbCompoundLitElemTempData data = {};
  7758. data.value = value;
  7759. data.elem_index = cast(i32)k;
  7760. array_add(&temp_data, data);
  7761. }
  7762. } else {
  7763. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7764. i64 index = exact_value_to_i64(fv->field->tav.value);
  7765. lbValue field_expr = lb_build_expr(p, fv->value);
  7766. GB_ASSERT(!is_type_tuple(field_expr.type));
  7767. lbValue ev = lb_emit_conv(p, field_expr, et);
  7768. lbCompoundLitElemTempData data = {};
  7769. data.value = ev;
  7770. data.elem_index = cast(i32)index;
  7771. array_add(&temp_data, data);
  7772. }
  7773. } else {
  7774. if (lb_is_elem_const(elem, et)) {
  7775. continue;
  7776. }
  7777. lbValue field_expr = lb_build_expr(p, elem);
  7778. GB_ASSERT(!is_type_tuple(field_expr.type));
  7779. lbValue ev = lb_emit_conv(p, field_expr, et);
  7780. lbCompoundLitElemTempData data = {};
  7781. data.value = ev;
  7782. data.elem_index = cast(i32)i;
  7783. array_add(&temp_data, data);
  7784. }
  7785. }
  7786. for_array(i, temp_data) {
  7787. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  7788. }
  7789. for_array(i, temp_data) {
  7790. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  7791. }
  7792. {
  7793. GB_ASSERT(lb_is_const(slice));
  7794. unsigned indices[1] = {1};
  7795. lbValue count = {};
  7796. count.type = t_int;
  7797. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  7798. lb_fill_slice(p, v, data, count);
  7799. }
  7800. }
  7801. break;
  7802. }
  7803. case Type_DynamicArray: {
  7804. if (cl->elems.count == 0) {
  7805. break;
  7806. }
  7807. Type *et = bt->DynamicArray.elem;
  7808. gbAllocator a = heap_allocator();
  7809. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  7810. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  7811. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  7812. {
  7813. auto args = array_make<lbValue>(a, 5);
  7814. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  7815. args[1] = size;
  7816. args[2] = align;
  7817. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  7818. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  7819. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  7820. }
  7821. lbValue items = lb_generate_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  7822. for_array(i, cl->elems) {
  7823. Ast *elem = cl->elems[i];
  7824. if (elem->kind == Ast_FieldValue) {
  7825. ast_node(fv, FieldValue, elem);
  7826. if (is_ast_range(fv->field)) {
  7827. ast_node(ie, BinaryExpr, fv->field);
  7828. TypeAndValue lo_tav = ie->left->tav;
  7829. TypeAndValue hi_tav = ie->right->tav;
  7830. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  7831. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  7832. TokenKind op = ie->op.kind;
  7833. i64 lo = exact_value_to_i64(lo_tav.value);
  7834. i64 hi = exact_value_to_i64(hi_tav.value);
  7835. if (op == Token_Ellipsis) {
  7836. hi += 1;
  7837. }
  7838. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  7839. for (i64 k = lo; k < hi; k++) {
  7840. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  7841. lb_emit_store(p, ep, value);
  7842. }
  7843. } else {
  7844. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  7845. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  7846. lbValue ev = lb_build_expr(p, fv->value);
  7847. lbValue value = lb_emit_conv(p, ev, et);
  7848. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  7849. lb_emit_store(p, ep, value);
  7850. }
  7851. } else {
  7852. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  7853. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  7854. lb_emit_store(p, ep, value);
  7855. }
  7856. }
  7857. {
  7858. auto args = array_make<lbValue>(a, 6);
  7859. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  7860. args[1] = size;
  7861. args[2] = align;
  7862. args[3] = lb_emit_conv(p, items, t_rawptr);
  7863. args[4] = lb_const_int(p->module, t_int, item_count);
  7864. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  7865. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  7866. }
  7867. break;
  7868. }
  7869. case Type_Basic: {
  7870. GB_ASSERT(is_type_any(bt));
  7871. if (cl->elems.count > 0) {
  7872. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7873. String field_names[2] = {
  7874. str_lit("data"),
  7875. str_lit("id"),
  7876. };
  7877. Type *field_types[2] = {
  7878. t_rawptr,
  7879. t_typeid,
  7880. };
  7881. for_array(field_index, cl->elems) {
  7882. Ast *elem = cl->elems[field_index];
  7883. lbValue field_expr = {};
  7884. isize index = field_index;
  7885. if (elem->kind == Ast_FieldValue) {
  7886. ast_node(fv, FieldValue, elem);
  7887. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  7888. index = sel.index[0];
  7889. elem = fv->value;
  7890. } else {
  7891. TypeAndValue tav = type_and_value_of_expr(elem);
  7892. Selection sel = lookup_field(bt, field_names[field_index], false);
  7893. index = sel.index[0];
  7894. }
  7895. field_expr = lb_build_expr(p, elem);
  7896. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  7897. Type *ft = field_types[index];
  7898. lbValue fv = lb_emit_conv(p, field_expr, ft);
  7899. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  7900. lb_emit_store(p, gep, fv);
  7901. }
  7902. }
  7903. break;
  7904. }
  7905. case Type_BitSet: {
  7906. i64 sz = type_size_of(type);
  7907. if (cl->elems.count > 0 && sz > 0) {
  7908. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  7909. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  7910. for_array(i, cl->elems) {
  7911. Ast *elem = cl->elems[i];
  7912. GB_ASSERT(elem->kind != Ast_FieldValue);
  7913. if (lb_is_elem_const(elem, et)) {
  7914. continue;
  7915. }
  7916. lbValue expr = lb_build_expr(p, elem);
  7917. GB_ASSERT(expr.type->kind != Type_Tuple);
  7918. Type *it = bit_set_to_int(bt);
  7919. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  7920. lbValue e = lb_emit_conv(p, expr, it);
  7921. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  7922. e = lb_emit_arith(p, Token_Shl, one, e, it);
  7923. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  7924. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  7925. new_value = lb_emit_transmute(p, new_value, type);
  7926. lb_addr_store(p, v, new_value);
  7927. }
  7928. }
  7929. break;
  7930. }
  7931. }
  7932. return v;
  7933. case_end;
  7934. case_ast_node(tc, TypeCast, expr);
  7935. Type *type = type_of_expr(expr);
  7936. lbValue x = lb_build_expr(p, tc->expr);
  7937. lbValue e = {};
  7938. switch (tc->token.kind) {
  7939. case Token_cast:
  7940. e = lb_emit_conv(p, x, type);
  7941. break;
  7942. case Token_transmute:
  7943. e = lb_emit_transmute(p, x, type);
  7944. break;
  7945. default:
  7946. GB_PANIC("Invalid AST TypeCast");
  7947. }
  7948. lbAddr v = lb_add_local_generated(p, type, false);
  7949. lb_addr_store(p, v, e);
  7950. return v;
  7951. case_end;
  7952. case_ast_node(ac, AutoCast, expr);
  7953. return lb_build_addr(p, ac->expr);
  7954. case_end;
  7955. }
  7956. TokenPos token_pos = ast_token(expr).pos;
  7957. GB_PANIC("Unexpected address expression\n"
  7958. "\tAst: %.*s @ "
  7959. "%.*s(%td:%td)\n",
  7960. LIT(ast_strings[expr->kind]),
  7961. LIT(token_pos.file), token_pos.line, token_pos.column);
  7962. return {};
  7963. }
  7964. void lb_init_module(lbModule *m, Checker *c) {
  7965. m->info = &c->info;
  7966. m->ctx = LLVMGetGlobalContext();
  7967. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  7968. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  7969. gb_mutex_init(&m->mutex);
  7970. gbAllocator a = heap_allocator();
  7971. map_init(&m->types, a);
  7972. map_init(&m->values, a);
  7973. map_init(&m->members, a);
  7974. map_init(&m->procedure_values, a);
  7975. map_init(&m->procedures, a);
  7976. map_init(&m->const_strings, a);
  7977. map_init(&m->anonymous_proc_lits, a);
  7978. array_init(&m->procedures_to_generate, a);
  7979. array_init(&m->foreign_library_paths, a);
  7980. map_init(&m->debug_values, a);
  7981. }
  7982. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  7983. if (global_error_collector.count != 0) {
  7984. return false;
  7985. }
  7986. isize tc = c->parser->total_token_count;
  7987. if (tc < 2) {
  7988. return false;
  7989. }
  7990. String init_fullpath = c->parser->init_fullpath;
  7991. if (build_context.out_filepath.len == 0) {
  7992. gen->output_name = remove_directory_from_path(init_fullpath);
  7993. gen->output_name = remove_extension_from_path(gen->output_name);
  7994. gen->output_base = gen->output_name;
  7995. } else {
  7996. gen->output_name = build_context.out_filepath;
  7997. isize pos = string_extension_position(gen->output_name);
  7998. if (pos < 0) {
  7999. gen->output_base = gen->output_name;
  8000. } else {
  8001. gen->output_base = substring(gen->output_name, 0, pos);
  8002. }
  8003. }
  8004. gbAllocator ha = heap_allocator();
  8005. array_init(&gen->output_object_paths, ha);
  8006. gen->output_base = path_to_full_path(ha, gen->output_base);
  8007. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  8008. output_file_path = gb_string_appendc(output_file_path, ".obj");
  8009. defer (gb_string_free(output_file_path));
  8010. gen->info = &c->info;
  8011. lb_init_module(&gen->module, c);
  8012. return true;
  8013. }
  8014. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  8015. GB_ASSERT(type != nullptr);
  8016. type = default_type(type);
  8017. isize max_len = 7+8+1;
  8018. u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len);
  8019. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  8020. m->global_generated_index++;
  8021. String name = make_string(str, len-1);
  8022. Scope *scope = nullptr;
  8023. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  8024. lbValue g = {};
  8025. g.type = alloc_type_pointer(type);
  8026. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  8027. if (value.value != nullptr) {
  8028. GB_ASSERT(LLVMIsConstant(value.value));
  8029. LLVMSetInitializer(g.value, value.value);
  8030. } else {
  8031. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  8032. }
  8033. lb_add_entity(m, e, g);
  8034. lb_add_member(m, name, g);
  8035. return lb_addr(g);
  8036. }
  8037. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  8038. AstPackage *p = m->info->runtime_package;
  8039. Entity *e = scope_lookup_current(p->scope, name);
  8040. lbValue *found = map_get(&m->values, hash_entity(e));
  8041. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  8042. lbValue value = *found;
  8043. return value;
  8044. }
  8045. lbValue lb_get_type_info_ptr(lbProcedure *p, Type *type) {
  8046. i32 index = cast(i32)lb_type_info_index(p->module->info, type);
  8047. // gb_printf_err("%d %s\n", index, type_to_string(type));
  8048. lbValue ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, index);
  8049. return lb_emit_transmute(p, ptr, t_type_info_ptr);
  8050. }
  8051. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  8052. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  8053. lb_global_type_info_member_types_index += cast(i32)count;
  8054. return offset;
  8055. }
  8056. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  8057. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  8058. lb_global_type_info_member_names_index += cast(i32)count;
  8059. return offset;
  8060. }
  8061. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  8062. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  8063. lb_global_type_info_member_offsets_index += cast(i32)count;
  8064. return offset;
  8065. }
  8066. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  8067. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  8068. lb_global_type_info_member_usings_index += cast(i32)count;
  8069. return offset;
  8070. }
  8071. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  8072. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  8073. lb_global_type_info_member_tags_index += cast(i32)count;
  8074. return offset;
  8075. }
  8076. lbValue lb_generate_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  8077. gbAllocator a = heap_allocator();
  8078. Token token = {Token_Ident};
  8079. isize name_len = prefix.len + 1 + 20;
  8080. auto suffix_id = cast(unsigned long long)id;
  8081. char *text = gb_alloc_array(a, char, name_len+1);
  8082. gb_snprintf(text, name_len,
  8083. "%.*s-%llu", LIT(prefix), suffix_id);
  8084. text[name_len] = 0;
  8085. String s = make_string_c(text);
  8086. Type *t = alloc_type_array(elem_type, count);
  8087. lbValue g = {};
  8088. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  8089. g.type = alloc_type_pointer(t);
  8090. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  8091. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  8092. map_set(&m->members, hash_string(s), g);
  8093. return g;
  8094. }
  8095. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  8096. lbModule *m = p->module;
  8097. LLVMContextRef ctx = m->ctx;
  8098. gbAllocator a = heap_allocator();
  8099. CheckerInfo *info = m->info;
  8100. {
  8101. // NOTE(bill): Set the type_table slice with the global backing array
  8102. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  8103. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  8104. GB_ASSERT(is_type_array(type));
  8105. LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)};
  8106. LLVMValueRef values[2] = {
  8107. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  8108. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  8109. };
  8110. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  8111. LLVMSetInitializer(global_type_table.value, slice);
  8112. }
  8113. // Useful types
  8114. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  8115. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  8116. i32 type_info_member_types_index = 0;
  8117. i32 type_info_member_names_index = 0;
  8118. i32 type_info_member_offsets_index = 0;
  8119. for_array(type_info_type_index, info->type_info_types) {
  8120. Type *t = info->type_info_types[type_info_type_index];
  8121. t = default_type(t);
  8122. if (t == t_invalid) {
  8123. continue;
  8124. }
  8125. isize entry_index = lb_type_info_index(info, t, false);
  8126. if (entry_index <= 0) {
  8127. continue;
  8128. }
  8129. // gb_printf_err("%s @ %td | %.*s\n", type_to_string(t), entry_index, LIT(type_strings[t->kind
  8130. lbValue tag = {};
  8131. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  8132. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 3);
  8133. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  8134. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  8135. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), lb_typeid(m, t));
  8136. switch (t->kind) {
  8137. case Type_Named: {
  8138. tag = lb_emit_conv(p, variant_ptr, t_type_info_named_ptr);
  8139. lbValue name = lb_const_string(p->module, t->Named.type_name->token.string);
  8140. lbValue gtip = lb_get_type_info_ptr(p, t->Named.base);
  8141. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), name);
  8142. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), gtip);
  8143. break;
  8144. }
  8145. case Type_Basic:
  8146. switch (t->Basic.kind) {
  8147. case Basic_bool:
  8148. case Basic_b8:
  8149. case Basic_b16:
  8150. case Basic_b32:
  8151. case Basic_b64:
  8152. tag = lb_emit_conv(p, variant_ptr, t_type_info_boolean_ptr);
  8153. break;
  8154. case Basic_i8:
  8155. case Basic_u8:
  8156. case Basic_i16:
  8157. case Basic_u16:
  8158. case Basic_i32:
  8159. case Basic_u32:
  8160. case Basic_i64:
  8161. case Basic_u64:
  8162. case Basic_i128:
  8163. case Basic_u128:
  8164. case Basic_i16le:
  8165. case Basic_u16le:
  8166. case Basic_i32le:
  8167. case Basic_u32le:
  8168. case Basic_i64le:
  8169. case Basic_u64le:
  8170. case Basic_i128le:
  8171. case Basic_u128le:
  8172. case Basic_i16be:
  8173. case Basic_u16be:
  8174. case Basic_i32be:
  8175. case Basic_u32be:
  8176. case Basic_i64be:
  8177. case Basic_u64be:
  8178. case Basic_i128be:
  8179. case Basic_u128be:
  8180. case Basic_int:
  8181. case Basic_uint:
  8182. case Basic_uintptr: {
  8183. tag = lb_emit_conv(p, variant_ptr, t_type_info_integer_ptr);
  8184. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  8185. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), is_signed);
  8186. // NOTE(bill): This is matches the runtime layout
  8187. u8 endianness_value = 0;
  8188. if (t->Basic.flags & BasicFlag_EndianLittle) {
  8189. endianness_value = 1;
  8190. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  8191. endianness_value = 2;
  8192. }
  8193. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  8194. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), endianness);
  8195. break;
  8196. }
  8197. case Basic_rune:
  8198. tag = lb_emit_conv(p, variant_ptr, t_type_info_rune_ptr);
  8199. break;
  8200. // case Basic_f16:
  8201. case Basic_f32:
  8202. case Basic_f64:
  8203. tag = lb_emit_conv(p, variant_ptr, t_type_info_float_ptr);
  8204. break;
  8205. // case Basic_complex32:
  8206. case Basic_complex64:
  8207. case Basic_complex128:
  8208. tag = lb_emit_conv(p, variant_ptr, t_type_info_complex_ptr);
  8209. break;
  8210. case Basic_quaternion128:
  8211. case Basic_quaternion256:
  8212. tag = lb_emit_conv(p, variant_ptr, t_type_info_quaternion_ptr);
  8213. break;
  8214. case Basic_rawptr:
  8215. tag = lb_emit_conv(p, variant_ptr, t_type_info_pointer_ptr);
  8216. break;
  8217. case Basic_string:
  8218. tag = lb_emit_conv(p, variant_ptr, t_type_info_string_ptr);
  8219. break;
  8220. case Basic_cstring:
  8221. tag = lb_emit_conv(p, variant_ptr, t_type_info_string_ptr);
  8222. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_const_bool(m, t_bool, true)); // is_cstring
  8223. break;
  8224. case Basic_any:
  8225. tag = lb_emit_conv(p, variant_ptr, t_type_info_any_ptr);
  8226. break;
  8227. case Basic_typeid:
  8228. tag = lb_emit_conv(p, variant_ptr, t_type_info_typeid_ptr);
  8229. break;
  8230. }
  8231. break;
  8232. case Type_Pointer: {
  8233. tag = lb_emit_conv(p, variant_ptr, t_type_info_pointer_ptr);
  8234. lbValue gep = lb_get_type_info_ptr(p, t->Pointer.elem);
  8235. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep);
  8236. break;
  8237. }
  8238. case Type_Array: {
  8239. tag = lb_emit_conv(p, variant_ptr, t_type_info_array_ptr);
  8240. lbValue gep = lb_get_type_info_ptr(p, t->Array.elem);
  8241. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep);
  8242. i64 ez = type_size_of(t->Array.elem);
  8243. lbValue elem_size = lb_emit_struct_ep(p, tag, 1);
  8244. lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez));
  8245. lbValue count = lb_emit_struct_ep(p, tag, 2);
  8246. lb_emit_store(p, count, lb_const_int(m, t_int, t->Array.count));
  8247. break;
  8248. }
  8249. case Type_EnumeratedArray: {
  8250. tag = lb_emit_conv(p, variant_ptr, t_type_info_enumerated_array_ptr);
  8251. lbValue elem = lb_get_type_info_ptr(p, t->EnumeratedArray.elem);
  8252. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), elem);
  8253. lbValue index = lb_get_type_info_ptr(p, t->EnumeratedArray.index);
  8254. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), index);
  8255. i64 ez = type_size_of(t->EnumeratedArray.elem);
  8256. lbValue elem_size = lb_emit_struct_ep(p, tag, 2);
  8257. lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez));
  8258. lbValue count = lb_emit_struct_ep(p, tag, 3);
  8259. lb_emit_store(p, count, lb_const_int(m, t_int, t->EnumeratedArray.count));
  8260. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  8261. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  8262. lbValue min_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.min_value);
  8263. lbValue max_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.max_value);
  8264. lb_emit_store_union_variant(p, min_value, min_v, min_v.type);
  8265. lb_emit_store_union_variant(p, max_value, max_v, max_v.type);
  8266. break;
  8267. }
  8268. case Type_DynamicArray: {
  8269. tag = lb_emit_conv(p, variant_ptr, t_type_info_dynamic_array_ptr);
  8270. lbValue gep = lb_get_type_info_ptr(p, t->DynamicArray.elem);
  8271. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep);
  8272. i64 ez = type_size_of(t->DynamicArray.elem);
  8273. lbValue elem_size = lb_emit_struct_ep(p, tag, 1);
  8274. lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez));
  8275. break;
  8276. }
  8277. case Type_Slice: {
  8278. tag = lb_emit_conv(p, variant_ptr, t_type_info_slice_ptr);
  8279. lbValue gep = lb_get_type_info_ptr(p, t->Slice.elem);
  8280. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep);
  8281. i64 ez = type_size_of(t->Slice.elem);
  8282. lbValue elem_size = lb_emit_struct_ep(p, tag, 1);
  8283. lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez));
  8284. break;
  8285. }
  8286. case Type_Proc: {
  8287. tag = lb_emit_conv(p, variant_ptr, t_type_info_procedure_ptr);
  8288. lbValue params = lb_emit_struct_ep(p, tag, 0);
  8289. lbValue results = lb_emit_struct_ep(p, tag, 1);
  8290. lbValue variadic = lb_emit_struct_ep(p, tag, 2);
  8291. lbValue convention = lb_emit_struct_ep(p, tag, 3);
  8292. if (t->Proc.params != nullptr) {
  8293. lb_emit_store(p, params, lb_get_type_info_ptr(p, t->Proc.params));
  8294. }
  8295. if (t->Proc.results != nullptr) {
  8296. lb_emit_store(p, results, lb_get_type_info_ptr(p, t->Proc.results));
  8297. }
  8298. lb_emit_store(p, variadic, lb_const_bool(m, t_bool, t->Proc.variadic));
  8299. lb_emit_store(p, convention, lb_const_int(m, t_u8, t->Proc.calling_convention));
  8300. // TODO(bill): TypeInfo for procedures
  8301. break;
  8302. }
  8303. case Type_Tuple: {
  8304. tag = lb_emit_conv(p, variant_ptr, t_type_info_tuple_ptr);
  8305. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  8306. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  8307. for_array(i, t->Tuple.variables) {
  8308. // NOTE(bill): offset is not used for tuples
  8309. Entity *f = t->Tuple.variables[i];
  8310. lbValue index = lb_const_int(m, t_int, i);
  8311. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  8312. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  8313. if (f->token.string.len > 0) {
  8314. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  8315. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  8316. }
  8317. }
  8318. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  8319. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 0)), memory_types, count);
  8320. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 1)), memory_names, count);
  8321. break;
  8322. }
  8323. case Type_Enum:
  8324. tag = lb_emit_conv(p, variant_ptr, t_type_info_enum_ptr);
  8325. {
  8326. GB_ASSERT(t->Enum.base_type != nullptr);
  8327. lbValue base = lb_type_info(m, t->Enum.base_type);
  8328. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), base);
  8329. if (t->Enum.fields.count > 0) {
  8330. auto fields = t->Enum.fields;
  8331. lbValue name_array = lb_generate_array(m, t_string, fields.count,
  8332. str_lit("$enum_names"), cast(i64)entry_index);
  8333. lbValue value_array = lb_generate_array(m, t_type_info_enum_value, fields.count,
  8334. str_lit("$enum_values"), cast(i64)entry_index);
  8335. GB_ASSERT(is_type_integer(t->Enum.base_type));
  8336. for_array(i, fields) {
  8337. lbValue name_ep = lb_emit_array_epi(p, name_array, i);
  8338. lbValue value_ep = lb_emit_array_epi(p, value_array, i);
  8339. ExactValue value = fields[i]->Constant.value;
  8340. lbValue v = lb_const_value(m, t->Enum.base_type, value);
  8341. lb_emit_store_union_variant(p, value_ep, v, v.type);
  8342. lb_emit_store(p, name_ep, lb_const_string(m, fields[i]->token.string));
  8343. }
  8344. lbValue v_count = lb_const_int(m, t_int, fields.count);
  8345. lbValue names = lb_emit_struct_ep(p, tag, 1);
  8346. lbValue name_array_elem = lb_array_elem(p, name_array);
  8347. lb_fill_slice(p, lb_addr(names), name_array_elem, v_count);
  8348. lbValue values = lb_emit_struct_ep(p, tag, 2);
  8349. lbValue value_array_elem = lb_array_elem(p, value_array);
  8350. lb_fill_slice(p, lb_addr(values), value_array_elem, v_count);
  8351. }
  8352. }
  8353. break;
  8354. case Type_Union: {
  8355. tag = lb_emit_conv(p, variant_ptr, t_type_info_union_ptr);
  8356. {
  8357. lbValue variant_types = lb_emit_struct_ep(p, tag, 0);
  8358. lbValue tag_offset_ptr = lb_emit_struct_ep(p, tag, 1);
  8359. lbValue tag_type_ptr = lb_emit_struct_ep(p, tag, 2);
  8360. lbValue custom_align_ptr = lb_emit_struct_ep(p, tag, 3);
  8361. lbValue no_nil_ptr = lb_emit_struct_ep(p, tag, 4);
  8362. lbValue maybe_ptr = lb_emit_struct_ep(p, tag, 5);
  8363. isize variant_count = gb_max(0, t->Union.variants.count);
  8364. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  8365. // NOTE(bill): Zeroth is nil so ignore it
  8366. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  8367. Type *vt = t->Union.variants[variant_index];
  8368. lbValue tip = lb_get_type_info_ptr(p, vt);
  8369. lbValue index = lb_const_int(m, t_int, variant_index);
  8370. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  8371. lb_emit_store(p, type_info, lb_type_info(m, vt));
  8372. }
  8373. lbValue count = lb_const_int(m, t_int, variant_count);
  8374. lb_fill_slice(p, lb_addr(variant_types), memory_types, count);
  8375. i64 tag_size = union_tag_size(t);
  8376. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  8377. if (tag_size > 0) {
  8378. lb_emit_store(p, tag_offset_ptr, lb_const_int(m, t_uintptr, tag_offset));
  8379. lb_emit_store(p, tag_type_ptr, lb_type_info(m, union_tag_type(t)));
  8380. }
  8381. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Union.custom_align != 0);
  8382. lb_emit_store(p, custom_align_ptr, is_custom_align);
  8383. lb_emit_store(p, no_nil_ptr, lb_const_bool(m, t_bool, t->Union.no_nil));
  8384. lb_emit_store(p, maybe_ptr, lb_const_bool(m, t_bool, t->Union.maybe));
  8385. }
  8386. break;
  8387. }
  8388. case Type_Struct: {
  8389. tag = lb_emit_conv(p, variant_ptr, t_type_info_struct_ptr);
  8390. {
  8391. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  8392. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  8393. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  8394. lb_emit_store(p, lb_emit_struct_ep(p, tag, 5), is_packed);
  8395. lb_emit_store(p, lb_emit_struct_ep(p, tag, 6), is_raw_union);
  8396. lb_emit_store(p, lb_emit_struct_ep(p, tag, 7), is_custom_align);
  8397. if (t->Struct.soa_kind != StructSoa_None) {
  8398. lbValue kind = lb_emit_struct_ep(p, tag, 8);
  8399. Type *kind_type = type_deref(kind.type);
  8400. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  8401. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  8402. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  8403. lb_emit_store(p, kind, soa_kind);
  8404. lb_emit_store(p, lb_emit_struct_ep(p, tag, 9), soa_type);
  8405. lb_emit_store(p, lb_emit_struct_ep(p, tag, 10), soa_len);
  8406. }
  8407. }
  8408. isize count = t->Struct.fields.count;
  8409. if (count > 0) {
  8410. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  8411. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  8412. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  8413. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  8414. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  8415. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  8416. for (isize source_index = 0; source_index < count; source_index++) {
  8417. // TODO(bill): Order fields in source order not layout order
  8418. Entity *f = t->Struct.fields[source_index];
  8419. lbValue tip = lb_get_type_info_ptr(p, f->type);
  8420. i64 foffset = 0;
  8421. if (!t->Struct.is_raw_union) {
  8422. foffset = t->Struct.offsets[f->Variable.field_index];
  8423. }
  8424. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  8425. lbValue index = lb_const_int(m, t_int, source_index);
  8426. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  8427. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  8428. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  8429. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  8430. if (f->token.string.len > 0) {
  8431. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  8432. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  8433. }
  8434. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  8435. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  8436. if (t->Struct.tags.count > 0) {
  8437. String tag_string = t->Struct.tags[source_index];
  8438. if (tag_string.len > 0) {
  8439. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  8440. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  8441. }
  8442. }
  8443. }
  8444. lbValue cv = lb_const_int(m, t_int, count);
  8445. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 0)), memory_types, cv);
  8446. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 1)), memory_names, cv);
  8447. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 2)), memory_offsets, cv);
  8448. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 3)), memory_usings, cv);
  8449. lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 4)), memory_tags, cv);
  8450. }
  8451. break;
  8452. }
  8453. case Type_Map: {
  8454. tag = lb_emit_conv(p, variant_ptr, t_type_info_map_ptr);
  8455. init_map_internal_types(t);
  8456. lbValue key = lb_emit_struct_ep(p, tag, 0);
  8457. lbValue value = lb_emit_struct_ep(p, tag, 1);
  8458. lbValue generated_struct = lb_emit_struct_ep(p, tag, 2);
  8459. lb_emit_store(p, key, lb_get_type_info_ptr(p, t->Map.key));
  8460. lb_emit_store(p, value, lb_get_type_info_ptr(p, t->Map.value));
  8461. lb_emit_store(p, generated_struct, lb_get_type_info_ptr(p, t->Map.generated_struct_type));
  8462. break;
  8463. }
  8464. case Type_BitField: {
  8465. tag = lb_emit_conv(p, variant_ptr, t_type_info_bit_field_ptr);
  8466. // names: []string;
  8467. // bits: []u32;
  8468. // offsets: []u32;
  8469. isize count = t->BitField.fields.count;
  8470. if (count > 0) {
  8471. auto fields = t->BitField.fields;
  8472. lbValue name_array = lb_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  8473. lbValue bit_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  8474. lbValue offset_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  8475. for (isize i = 0; i < count; i++) {
  8476. Entity *f = fields[i];
  8477. GB_ASSERT(f->type != nullptr);
  8478. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  8479. lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i);
  8480. lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i);
  8481. lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i);
  8482. lb_emit_store(p, name_ep, lb_const_string(m, f->token.string));
  8483. lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits));
  8484. lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i]));
  8485. }
  8486. lbValue v_count = lb_const_int(m, t_int, count);
  8487. lbValue names = lb_emit_struct_ep(p, tag, 0);
  8488. lbValue name_array_elem = lb_array_elem(p, name_array);
  8489. lb_fill_slice(p, lb_addr(names), name_array_elem, v_count);
  8490. lbValue bits = lb_emit_struct_ep(p, tag, 1);
  8491. lbValue bit_array_elem = lb_array_elem(p, bit_array);
  8492. lb_fill_slice(p, lb_addr(bits), bit_array_elem, v_count);
  8493. lbValue offsets = lb_emit_struct_ep(p, tag, 2);
  8494. lbValue offset_array_elem = lb_array_elem(p, offset_array);
  8495. lb_fill_slice(p, lb_addr(offsets), offset_array_elem, v_count);
  8496. }
  8497. break;
  8498. }
  8499. case Type_BitSet:
  8500. tag = lb_emit_conv(p, variant_ptr, t_type_info_bit_set_ptr);
  8501. GB_ASSERT(is_type_typed(t->BitSet.elem));
  8502. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->BitSet.elem));
  8503. if (t->BitSet.underlying != nullptr) {
  8504. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), lb_get_type_info_ptr(p, t->BitSet.underlying));
  8505. }
  8506. lb_emit_store(p, lb_emit_struct_ep(p, tag, 2), lb_const_int(m, t_i64, t->BitSet.lower));
  8507. lb_emit_store(p, lb_emit_struct_ep(p, tag, 3), lb_const_int(m, t_i64, t->BitSet.upper));
  8508. break;
  8509. case Type_Opaque:
  8510. tag = lb_emit_conv(p, variant_ptr, t_type_info_opaque_ptr);
  8511. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->Opaque.elem));
  8512. break;
  8513. case Type_SimdVector:
  8514. tag = lb_emit_conv(p, variant_ptr, t_type_info_simd_vector_ptr);
  8515. if (t->SimdVector.is_x86_mmx) {
  8516. lb_emit_store(p, lb_emit_struct_ep(p, tag, 3), lb_const_bool(m, t_bool, true));
  8517. } else {
  8518. lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->SimdVector.elem));
  8519. lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)));
  8520. lb_emit_store(p, lb_emit_struct_ep(p, tag, 2), lb_const_int(m, t_int, t->SimdVector.count));
  8521. }
  8522. break;
  8523. }
  8524. if (tag.value != nullptr) {
  8525. Type *tag_type = type_deref(tag.type);
  8526. GB_ASSERT(is_type_named(tag_type));
  8527. lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  8528. } else {
  8529. if (t != t_llvm_bool) {
  8530. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  8531. }
  8532. }
  8533. }
  8534. }
  8535. void lb_generate_code(lbGenerator *gen) {
  8536. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  8537. TIME_SECTION("LLVM Global Variables");
  8538. lbModule *m = &gen->module;
  8539. LLVMModuleRef mod = gen->module.mod;
  8540. CheckerInfo *info = gen->info;
  8541. Arena temp_arena = {};
  8542. arena_init(&temp_arena, heap_allocator());
  8543. gbAllocator temp_allocator = arena_allocator(&temp_arena);
  8544. gen->module.global_default_context = lb_add_global_generated(m, t_context, {});
  8545. gen->module.global_default_context.kind = lbAddr_Context;
  8546. auto *min_dep_set = &info->minimum_dependency_set;
  8547. { // Debug Info
  8548. for_array(i, info->files.entries) {
  8549. AstFile *f = info->files.entries[i].value;
  8550. String fullpath = f->fullpath;
  8551. String filename = filename_from_path(fullpath);
  8552. String directory = directory_from_path(fullpath);
  8553. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  8554. cast(char const *)filename.text, filename.len,
  8555. cast(char const *)directory.text, directory.len);
  8556. map_set(&m->debug_values, hash_pointer(f), res);
  8557. f->llvm_metadata = res;
  8558. }
  8559. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  8560. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  8561. "odin", 4,
  8562. false, "", 0,
  8563. 1, "", 0,
  8564. LLVMDWARFEmissionFull, 0, true,
  8565. true
  8566. );
  8567. }
  8568. {
  8569. { // Add type info data
  8570. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  8571. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  8572. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  8573. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8574. LLVMSetLinkage(g, LLVMInternalLinkage);
  8575. lbValue value = {};
  8576. value.value = g;
  8577. value.type = alloc_type_pointer(t);
  8578. lb_global_type_info_data = lb_addr(value);
  8579. }
  8580. { // Type info member buffer
  8581. // NOTE(bill): Removes need for heap allocation by making it global memory
  8582. isize count = 0;
  8583. for_array(entry_index, m->info->type_info_types) {
  8584. Type *t = m->info->type_info_types[entry_index];
  8585. isize index = lb_type_info_index(m->info, t, false);
  8586. if (index < 0) {
  8587. continue;
  8588. }
  8589. switch (t->kind) {
  8590. case Type_Union:
  8591. count += t->Union.variants.count;
  8592. break;
  8593. case Type_Struct:
  8594. count += t->Struct.fields.count;
  8595. break;
  8596. case Type_Tuple:
  8597. count += t->Tuple.variables.count;
  8598. break;
  8599. }
  8600. }
  8601. if (count > 0) {
  8602. {
  8603. char const *name = LB_TYPE_INFO_TYPES_NAME;
  8604. Type *t = alloc_type_array(t_type_info_ptr, count);
  8605. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8606. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8607. LLVMSetLinkage(g, LLVMInternalLinkage);
  8608. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  8609. }
  8610. {
  8611. char const *name = LB_TYPE_INFO_NAMES_NAME;
  8612. Type *t = alloc_type_array(t_string, count);
  8613. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8614. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8615. LLVMSetLinkage(g, LLVMInternalLinkage);
  8616. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  8617. }
  8618. {
  8619. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  8620. Type *t = alloc_type_array(t_uintptr, count);
  8621. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8622. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8623. LLVMSetLinkage(g, LLVMInternalLinkage);
  8624. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  8625. }
  8626. {
  8627. char const *name = LB_TYPE_INFO_USINGS_NAME;
  8628. Type *t = alloc_type_array(t_bool, count);
  8629. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8630. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8631. LLVMSetLinkage(g, LLVMInternalLinkage);
  8632. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  8633. }
  8634. {
  8635. char const *name = LB_TYPE_INFO_TAGS_NAME;
  8636. Type *t = alloc_type_array(t_string, count);
  8637. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  8638. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  8639. LLVMSetLinkage(g, LLVMInternalLinkage);
  8640. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  8641. }
  8642. }
  8643. }
  8644. }
  8645. isize global_variable_max_count = 0;
  8646. Entity *entry_point = info->entry_point;
  8647. bool has_dll_main = false;
  8648. bool has_win_main = false;
  8649. for_array(i, info->entities) {
  8650. Entity *e = info->entities[i];
  8651. String name = e->token.string;
  8652. bool is_global = e->pkg != nullptr;
  8653. if (e->kind == Entity_Variable) {
  8654. global_variable_max_count++;
  8655. } else if (e->kind == Entity_Procedure && !is_global) {
  8656. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  8657. GB_ASSERT(e == entry_point);
  8658. // entry_point = e;
  8659. }
  8660. if (e->Procedure.is_export ||
  8661. (e->Procedure.link_name.len > 0) ||
  8662. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  8663. if (!has_dll_main && name == "DllMain") {
  8664. has_dll_main = true;
  8665. } else if (!has_win_main && name == "WinMain") {
  8666. has_win_main = true;
  8667. }
  8668. }
  8669. }
  8670. }
  8671. struct GlobalVariable {
  8672. lbValue var;
  8673. lbValue init;
  8674. DeclInfo *decl;
  8675. };
  8676. auto global_variables = array_make<GlobalVariable>(heap_allocator(), 0, global_variable_max_count);
  8677. for_array(i, info->variable_init_order) {
  8678. DeclInfo *d = info->variable_init_order[i];
  8679. Entity *e = d->entity;
  8680. if ((e->scope->flags & ScopeFlag_File) == 0) {
  8681. continue;
  8682. }
  8683. if (!ptr_set_exists(min_dep_set, e)) {
  8684. continue;
  8685. }
  8686. DeclInfo *decl = decl_info_of_entity(e);
  8687. if (decl == nullptr) {
  8688. continue;
  8689. }
  8690. GB_ASSERT(e->kind == Entity_Variable);
  8691. bool is_foreign = e->Variable.is_foreign;
  8692. bool is_export = e->Variable.is_export;
  8693. String name = lb_get_entity_name(m, e);
  8694. lbValue g = {};
  8695. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(heap_allocator(), name));
  8696. g.type = alloc_type_pointer(e->type);
  8697. if (e->Variable.thread_local_model != "") {
  8698. LLVMSetThreadLocal(g.value, true);
  8699. String m = e->Variable.thread_local_model;
  8700. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  8701. if (m == "default") {
  8702. mode = LLVMGeneralDynamicTLSModel;
  8703. } else if (m == "localdynamic") {
  8704. mode = LLVMLocalDynamicTLSModel;
  8705. } else if (m == "initialexec") {
  8706. mode = LLVMInitialExecTLSModel;
  8707. } else if (m == "localexec") {
  8708. mode = LLVMLocalExecTLSModel;
  8709. } else {
  8710. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  8711. }
  8712. LLVMSetThreadLocalMode(g.value, mode);
  8713. }
  8714. if (is_foreign) {
  8715. LLVMSetExternallyInitialized(g.value, true);
  8716. } else {
  8717. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  8718. }
  8719. if (is_export) {
  8720. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  8721. }
  8722. GlobalVariable var = {};
  8723. var.var = g;
  8724. var.decl = decl;
  8725. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  8726. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  8727. if (tav.mode != Addressing_Invalid) {
  8728. if (tav.value.kind != ExactValue_Invalid) {
  8729. ExactValue v = tav.value;
  8730. lbValue init = lb_const_value(m, tav.type, v);
  8731. LLVMSetInitializer(g.value, init.value);
  8732. }
  8733. }
  8734. }
  8735. array_add(&global_variables, var);
  8736. lb_add_entity(m, e, g);
  8737. lb_add_member(m, name, g);
  8738. }
  8739. TIME_SECTION("LLVM Global Procedures and Types");
  8740. for_array(i, info->entities) {
  8741. // arena_free_all(&temp_arena);
  8742. // gbAllocator a = temp_allocator;
  8743. Entity *e = info->entities[i];
  8744. String name = e->token.string;
  8745. DeclInfo *decl = e->decl_info;
  8746. Scope * scope = e->scope;
  8747. if ((scope->flags & ScopeFlag_File) == 0) {
  8748. continue;
  8749. }
  8750. Scope *package_scope = scope->parent;
  8751. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  8752. switch (e->kind) {
  8753. case Entity_Variable:
  8754. // NOTE(bill): Handled above as it requires a specific load order
  8755. continue;
  8756. case Entity_ProcGroup:
  8757. continue;
  8758. case Entity_TypeName:
  8759. case Entity_Procedure:
  8760. break;
  8761. }
  8762. bool polymorphic_struct = false;
  8763. if (e->type != nullptr && e->kind == Entity_TypeName) {
  8764. Type *bt = base_type(e->type);
  8765. if (bt->kind == Type_Struct) {
  8766. polymorphic_struct = is_type_polymorphic(bt);
  8767. }
  8768. }
  8769. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  8770. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  8771. continue;
  8772. }
  8773. String mangled_name = lb_get_entity_name(m, e);
  8774. switch (e->kind) {
  8775. case Entity_TypeName:
  8776. lb_type(m, e->type);
  8777. break;
  8778. case Entity_Procedure:
  8779. {
  8780. lbProcedure *p = lb_create_procedure(m, e);
  8781. array_add(&m->procedures_to_generate, p);
  8782. }
  8783. break;
  8784. }
  8785. }
  8786. TIME_SECTION("LLVM Procedure Generation");
  8787. for_array(i, m->procedures_to_generate) {
  8788. lbProcedure *p = m->procedures_to_generate[i];
  8789. if (p->is_done) {
  8790. continue;
  8791. }
  8792. if (p->body != nullptr) { // Build Procedure
  8793. lb_begin_procedure_body(p);
  8794. lb_build_stmt(p, p->body);
  8795. lb_end_procedure_body(p);
  8796. p->is_done = true;
  8797. }
  8798. lb_end_procedure(p);
  8799. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  8800. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  8801. LLVMDumpValue(p->value);
  8802. gb_printf_err("\n\n\n\n");
  8803. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  8804. }
  8805. }
  8806. TIME_SECTION("LLVM Function Pass");
  8807. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  8808. LLVMPassManagerRef function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  8809. defer (LLVMDisposePassManager(function_pass_manager));
  8810. LLVMAddPromoteMemoryToRegisterPass(function_pass_manager);
  8811. LLVMAddMergedLoadStoreMotionPass(function_pass_manager);
  8812. LLVMAddDeadStoreEliminationPass(function_pass_manager);
  8813. LLVMAddAggressiveInstCombinerPass(function_pass_manager);
  8814. LLVMAddConstantPropagationPass(function_pass_manager);
  8815. LLVMAddAggressiveDCEPass(function_pass_manager);
  8816. LLVMAddMergedLoadStoreMotionPass(function_pass_manager);
  8817. LLVMAddPromoteMemoryToRegisterPass(function_pass_manager);
  8818. // LLVMAddUnifyFunctionExitNodesPass(function_pass_manager);
  8819. for_array(i, m->procedures_to_generate) {
  8820. lbProcedure *p = m->procedures_to_generate[i];
  8821. if (p->body != nullptr) { // Build Procedure
  8822. LLVMRunFunctionPassManager(function_pass_manager, p->value);
  8823. }
  8824. }
  8825. TIME_SECTION("LLVM Runtime Creation");
  8826. lbProcedure *startup_runtime = nullptr;
  8827. { // Startup Runtime
  8828. Type *params = alloc_type_tuple();
  8829. Type *results = alloc_type_tuple();
  8830. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  8831. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  8832. startup_runtime = p;
  8833. lb_begin_procedure_body(p);
  8834. lb_setup_type_info_data(p);
  8835. for_array(i, global_variables) {
  8836. auto *var = &global_variables[i];
  8837. if (var->decl->init_expr != nullptr) {
  8838. var->init = lb_build_expr(p, var->decl->init_expr);
  8839. }
  8840. Entity *e = var->decl->entity;
  8841. GB_ASSERT(e->kind == Entity_Variable);
  8842. if (e->Variable.is_foreign) {
  8843. Entity *fl = e->Procedure.foreign_library;
  8844. lb_add_foreign_library_path(m, fl);
  8845. }
  8846. if (e->flags & EntityFlag_Static) {
  8847. LLVMSetLinkage(var->var.value, LLVMInternalLinkage);
  8848. }
  8849. if (var->init.value != nullptr) {
  8850. Type *t = type_deref(var->var.type);
  8851. if (is_type_any(t)) {
  8852. // NOTE(bill): Edge case for 'any' type
  8853. Type *var_type = default_type(var->init.type);
  8854. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  8855. lb_addr_store(p, g, var->init);
  8856. lbValue gp = lb_addr_get_ptr(p, g);
  8857. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  8858. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  8859. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  8860. lb_emit_store(p, ti, lb_type_info(m, var_type));
  8861. } else {
  8862. lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t));
  8863. }
  8864. }
  8865. }
  8866. lb_emit_init_context(p, p->module->global_default_context);
  8867. lb_end_procedure_body(p);
  8868. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  8869. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  8870. LLVMDumpValue(p->value);
  8871. gb_printf_err("\n\n\n\n");
  8872. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  8873. }
  8874. LLVMRunFunctionPassManager(function_pass_manager, p->value);
  8875. }
  8876. if (!(build_context.is_dll && !has_dll_main)) {
  8877. Type *params = alloc_type_tuple();
  8878. Type *results = alloc_type_tuple();
  8879. array_init(&params->Tuple.variables, heap_allocator(), 2);
  8880. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  8881. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  8882. array_init(&results->Tuple.variables, heap_allocator(), 1);
  8883. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  8884. Type *proc_type = alloc_type_proc(nullptr, params, 2, results, 1, false, ProcCC_CDecl);
  8885. lbProcedure *p = lb_create_dummy_procedure(m, str_lit("main"), proc_type);
  8886. lb_begin_procedure_body(p);
  8887. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  8888. GB_ASSERT(found != nullptr);
  8889. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  8890. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  8891. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  8892. lb_end_procedure_body(p);
  8893. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  8894. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  8895. LLVMDumpValue(p->value);
  8896. gb_printf_err("\n\n\n\n");
  8897. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  8898. }
  8899. LLVMRunFunctionPassManager(function_pass_manager, p->value);
  8900. }
  8901. TIME_SECTION("LLVM Module Pass");
  8902. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  8903. defer (LLVMDisposePassManager(module_pass_manager));
  8904. LLVMAddAlwaysInlinerPass(module_pass_manager);
  8905. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  8906. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  8907. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  8908. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  8909. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  8910. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  8911. LLVMRunPassManager(module_pass_manager, mod);
  8912. char *llvm_error = nullptr;
  8913. defer (LLVMDisposeMessage(llvm_error));
  8914. String filepath_ll = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".ll"));
  8915. defer (gb_free(heap_allocator(), filepath_ll.text));
  8916. String filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".obj"));
  8917. if (build_context.keep_temp_files) {
  8918. TIME_SECTION("LLVM Print Module to File");
  8919. LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error);
  8920. }
  8921. LLVMDIBuilderFinalize(m->debug_builder);
  8922. LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error);
  8923. llvm_error = nullptr;
  8924. TIME_SECTION("LLVM Initializtion");
  8925. LLVMInitializeAllTargetInfos();
  8926. LLVMInitializeAllTargets();
  8927. LLVMInitializeAllTargetMCs();
  8928. LLVMInitializeAllAsmPrinters();
  8929. LLVMInitializeAllAsmParsers();
  8930. LLVMInitializeAllDisassemblers();
  8931. LLVMInitializeNativeTarget();
  8932. char const *target_triple = "x86_64-pc-windows-msvc";
  8933. char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128";
  8934. LLVMSetTarget(mod, target_triple);
  8935. LLVMTargetRef target = {};
  8936. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  8937. GB_ASSERT(target != nullptr);
  8938. TIME_SECTION("LLVM Create Target Machine");
  8939. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault);
  8940. defer (LLVMDisposeTargetMachine(target_machine));
  8941. TIME_SECTION("LLVM Object Generation");
  8942. LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error);
  8943. if (ok) {
  8944. gb_printf_err("LLVM Error: %s\n", llvm_error);
  8945. gb_exit(1);
  8946. return;
  8947. }
  8948. array_add(&gen->output_object_paths, filepath_obj);
  8949. #undef TIME_SECTION
  8950. }