llvm_backend.cpp 435 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924
  1. #include "llvm_backend.hpp"
  2. #include "llvm_abi.cpp"
  3. #include "llvm_backend_opt.cpp"
  4. gb_global lbAddr lb_global_type_info_data = {};
  5. gb_global lbAddr lb_global_type_info_member_types = {};
  6. gb_global lbAddr lb_global_type_info_member_names = {};
  7. gb_global lbAddr lb_global_type_info_member_offsets = {};
  8. gb_global lbAddr lb_global_type_info_member_usings = {};
  9. gb_global lbAddr lb_global_type_info_member_tags = {};
  10. gb_global isize lb_global_type_info_data_index = 0;
  11. gb_global isize lb_global_type_info_member_types_index = 0;
  12. gb_global isize lb_global_type_info_member_names_index = 0;
  13. gb_global isize lb_global_type_info_member_offsets_index = 0;
  14. gb_global isize lb_global_type_info_member_usings_index = 0;
  15. gb_global isize lb_global_type_info_member_tags_index = 0;
  16. struct lbLoopData {
  17. lbAddr idx_addr;
  18. lbValue idx;
  19. lbBlock *body;
  20. lbBlock *done;
  21. lbBlock *loop;
  22. };
  23. struct lbCompoundLitElemTempData {
  24. Ast * expr;
  25. lbValue value;
  26. i32 elem_index;
  27. lbValue gep;
  28. };
  29. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  30. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  31. LLVMValueRef llvm_zero(lbModule *m) {
  32. return LLVMConstInt(lb_type(m, t_int), 0, false);
  33. }
  34. LLVMValueRef llvm_one(lbModule *m) {
  35. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  36. }
  37. lbValue lb_zero(lbModule *m, Type *t) {
  38. lbValue v = {};
  39. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  40. v.type = t;
  41. return v;
  42. }
  43. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  44. lbValue v = lb_find_or_add_entity_string(m, str);
  45. unsigned indices[1] = {0};
  46. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  47. }
  48. bool lb_is_instr_terminating(LLVMValueRef instr) {
  49. if (instr != nullptr) {
  50. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  51. switch (op) {
  52. case LLVMRet:
  53. case LLVMBr:
  54. case LLVMSwitch:
  55. case LLVMIndirectBr:
  56. case LLVMInvoke:
  57. case LLVMUnreachable:
  58. case LLVMCallBr:
  59. return true;
  60. }
  61. }
  62. return false;
  63. }
  64. lbAddr lb_addr(lbValue addr) {
  65. lbAddr v = {lbAddr_Default, addr};
  66. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  67. GB_ASSERT(is_type_pointer(addr.type));
  68. v.kind = lbAddr_RelativePointer;
  69. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  70. GB_ASSERT(is_type_pointer(addr.type));
  71. v.kind = lbAddr_RelativeSlice;
  72. }
  73. return v;
  74. }
  75. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  76. lbAddr v = {lbAddr_Map, addr};
  77. v.map.key = map_key;
  78. v.map.type = map_type;
  79. v.map.result = map_result;
  80. return v;
  81. }
  82. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  83. lbAddr v = {lbAddr_SoaVariable, addr};
  84. v.soa.index = index;
  85. v.soa.index_expr = index_expr;
  86. return v;
  87. }
  88. Type *lb_addr_type(lbAddr const &addr) {
  89. if (addr.addr.value == nullptr) {
  90. return nullptr;
  91. }
  92. if (addr.kind == lbAddr_Map) {
  93. Type *t = base_type(addr.map.type);
  94. GB_ASSERT(is_type_map(t));
  95. return t->Map.value;
  96. }
  97. return type_deref(addr.addr.type);
  98. }
  99. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  100. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  101. }
  102. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  103. if (addr.addr.value == nullptr) {
  104. GB_PANIC("Illegal addr -> nullptr");
  105. return {};
  106. }
  107. switch (addr.kind) {
  108. case lbAddr_Map: {
  109. Type *map_type = base_type(addr.map.type);
  110. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  111. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  112. auto args = array_make<lbValue>(permanent_allocator(), 2);
  113. args[0] = h;
  114. args[1] = key;
  115. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  116. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  117. }
  118. case lbAddr_RelativePointer: {
  119. Type *rel_ptr = base_type(lb_addr_type(addr));
  120. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  121. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  122. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  123. offset = lb_emit_load(p, offset);
  124. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  125. offset = lb_emit_conv(p, offset, t_i64);
  126. }
  127. offset = lb_emit_conv(p, offset, t_uintptr);
  128. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  129. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  130. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  131. // NOTE(bill): nil check
  132. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  133. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  134. return final_ptr;
  135. }
  136. case lbAddr_SoaVariable: {
  137. // TODO(bill): FIX THIS HACK
  138. return lb_address_from_load(p, lb_addr_load(p, addr));
  139. }
  140. case lbAddr_Context:
  141. GB_PANIC("lbAddr_Context should be handled elsewhere");
  142. }
  143. return addr.addr;
  144. }
  145. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  146. lbAddr addr = lb_build_addr(p, expr);
  147. return lb_addr_get_ptr(p, addr);
  148. }
  149. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  150. if (build_context.no_bounds_check) {
  151. return;
  152. }
  153. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  154. return;
  155. }
  156. index = lb_emit_conv(p, index, t_int);
  157. len = lb_emit_conv(p, len, t_int);
  158. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  159. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  160. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  161. auto args = array_make<lbValue>(permanent_allocator(), 5);
  162. args[0] = file;
  163. args[1] = line;
  164. args[2] = column;
  165. args[3] = index;
  166. args[4] = len;
  167. lb_emit_runtime_call(p, "bounds_check_error", args);
  168. }
  169. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  170. if (build_context.no_bounds_check) {
  171. return;
  172. }
  173. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  174. return;
  175. }
  176. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  177. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  178. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  179. high = lb_emit_conv(p, high, t_int);
  180. if (!lower_value_used) {
  181. auto args = array_make<lbValue>(permanent_allocator(), 5);
  182. args[0] = file;
  183. args[1] = line;
  184. args[2] = column;
  185. args[3] = high;
  186. args[4] = len;
  187. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  188. } else {
  189. // No need to convert unless used
  190. low = lb_emit_conv(p, low, t_int);
  191. auto args = array_make<lbValue>(permanent_allocator(), 6);
  192. args[0] = file;
  193. args[1] = line;
  194. args[2] = column;
  195. args[3] = low;
  196. args[4] = high;
  197. args[5] = len;
  198. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  199. }
  200. }
  201. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  202. if (addr.addr.value == nullptr) {
  203. return;
  204. }
  205. GB_ASSERT(value.type != nullptr);
  206. if (is_type_untyped_undef(value.type)) {
  207. Type *t = lb_addr_type(addr);
  208. value.type = t;
  209. value.value = LLVMGetUndef(lb_type(p->module, t));
  210. } else if (is_type_untyped_nil(value.type)) {
  211. Type *t = lb_addr_type(addr);
  212. value.type = t;
  213. value.value = LLVMConstNull(lb_type(p->module, t));
  214. }
  215. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  216. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  217. }
  218. if (addr.kind == lbAddr_RelativePointer) {
  219. Type *rel_ptr = base_type(lb_addr_type(addr));
  220. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  221. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  222. GB_ASSERT(is_type_pointer(addr.addr.type));
  223. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  224. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  225. lbValue offset = {};
  226. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  227. offset.type = t_uintptr;
  228. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  229. offset = lb_emit_conv(p, offset, t_i64);
  230. }
  231. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  232. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  233. offset = lb_emit_select(p,
  234. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  235. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  236. offset
  237. );
  238. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  239. return;
  240. } else if (addr.kind == lbAddr_RelativeSlice) {
  241. Type *rel_ptr = base_type(lb_addr_type(addr));
  242. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  243. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  244. GB_ASSERT(is_type_pointer(addr.addr.type));
  245. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  246. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  247. lbValue offset = {};
  248. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  249. offset.type = t_uintptr;
  250. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  251. offset = lb_emit_conv(p, offset, t_i64);
  252. }
  253. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  254. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  255. offset = lb_emit_select(p,
  256. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  257. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  258. offset
  259. );
  260. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  261. lbValue len = lb_slice_len(p, value);
  262. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  263. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  264. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  265. return;
  266. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  267. lbValue ptr = addr.addr;
  268. lbValue index = addr.index_set.index;
  269. Ast *node = addr.index_set.node;
  270. ast_node(ce, CallExpr, node);
  271. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  272. proc_type = base_type(proc_type);
  273. GB_ASSERT(is_type_proc(proc_type));
  274. TypeProc *pt = &proc_type->Proc;
  275. isize arg_count = 3;
  276. isize param_count = 0;
  277. if (pt->params) {
  278. GB_ASSERT(pt->params->kind == Type_Tuple);
  279. param_count = pt->params->Tuple.variables.count;
  280. }
  281. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  282. args[0] = ptr;
  283. args[1] = index;
  284. args[2] = value;
  285. isize arg_index = arg_count;
  286. if (arg_count < param_count) {
  287. lbModule *m = p->module;
  288. String proc_name = {};
  289. if (p->entity != nullptr) {
  290. proc_name = p->entity->token.string;
  291. }
  292. TokenPos pos = ast_token(ce->proc).pos;
  293. TypeTuple *param_tuple = &pt->params->Tuple;
  294. isize end = cast(isize)param_count;
  295. while (arg_index < end) {
  296. Entity *e = param_tuple->variables[arg_index];
  297. GB_ASSERT(e->kind == Entity_Variable);
  298. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  299. }
  300. }
  301. Entity *e = entity_from_expr(ce->proc);
  302. GB_ASSERT(e != nullptr);
  303. GB_ASSERT(is_type_polymorphic(e->type));
  304. {
  305. lbValue *found = nullptr;
  306. if (p->module != e->code_gen_module) {
  307. gb_mutex_lock(&p->module->mutex);
  308. }
  309. GB_ASSERT(e->code_gen_module != nullptr);
  310. found = map_get(&e->code_gen_module->values, hash_entity(e));
  311. if (p->module != e->code_gen_module) {
  312. gb_mutex_unlock(&p->module->mutex);
  313. }
  314. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  315. lb_emit_call(p, *found, args);
  316. }
  317. return;
  318. } else if (addr.kind == lbAddr_Map) {
  319. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  320. return;
  321. } else if (addr.kind == lbAddr_Context) {
  322. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  323. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  324. lb_addr_store(p, next_addr, old);
  325. lb_push_context_onto_stack(p, next_addr);
  326. lbValue next = lb_addr_get_ptr(p, next_addr);
  327. if (addr.ctx.sel.index.count > 0) {
  328. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  329. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  330. lb_emit_store(p, lhs, rhs);
  331. } else {
  332. lbValue lhs = next;
  333. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  334. lb_emit_store(p, lhs, rhs);
  335. }
  336. return;
  337. } else if (addr.kind == lbAddr_SoaVariable) {
  338. Type *t = type_deref(addr.addr.type);
  339. t = base_type(t);
  340. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  341. Type *elem_type = t->Struct.soa_elem;
  342. value = lb_emit_conv(p, value, elem_type);
  343. elem_type = base_type(elem_type);
  344. lbValue index = addr.soa.index;
  345. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  346. Type *t = base_type(type_deref(addr.addr.type));
  347. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  348. lbValue len = lb_soa_struct_len(p, addr.addr);
  349. if (addr.soa.index_expr != nullptr) {
  350. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  351. }
  352. }
  353. isize field_count = 0;
  354. switch (elem_type->kind) {
  355. case Type_Struct:
  356. field_count = elem_type->Struct.fields.count;
  357. break;
  358. case Type_Array:
  359. field_count = elem_type->Array.count;
  360. break;
  361. }
  362. for (isize i = 0; i < field_count; i++) {
  363. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  364. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  365. if (t->Struct.soa_kind == StructSoa_Fixed) {
  366. dst = lb_emit_array_ep(p, dst, index);
  367. lb_emit_store(p, dst, src);
  368. } else {
  369. lbValue field = lb_emit_load(p, dst);
  370. dst = lb_emit_ptr_offset(p, field, index);
  371. lb_emit_store(p, dst, src);
  372. }
  373. }
  374. return;
  375. }
  376. GB_ASSERT(value.value != nullptr);
  377. value = lb_emit_conv(p, value, lb_addr_type(addr));
  378. // if (lb_is_const_or_global(value)) {
  379. // // NOTE(bill): Just bypass the actual storage and set the initializer
  380. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  381. // LLVMValueRef dst = addr.addr.value;
  382. // LLVMValueRef src = value.value;
  383. // LLVMSetInitializer(dst, src);
  384. // return;
  385. // }
  386. // }
  387. lb_emit_store(p, addr.addr, value);
  388. }
  389. void lb_const_store(lbValue ptr, lbValue value) {
  390. GB_ASSERT(lb_is_const(ptr));
  391. GB_ASSERT(lb_is_const(value));
  392. GB_ASSERT(is_type_pointer(ptr.type));
  393. LLVMSetInitializer(ptr.value, value.value);
  394. }
  395. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  396. GB_ASSERT(value.value != nullptr);
  397. Type *a = type_deref(ptr.type);
  398. if (is_type_boolean(a)) {
  399. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  400. value = lb_emit_conv(p, value, a);
  401. }
  402. Type *ca = core_type(a);
  403. if (ca->kind == Type_Basic) {
  404. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  405. }
  406. if (is_type_proc(a)) {
  407. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  408. // stored as regular pointer with no procedure information
  409. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  410. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  411. LLVMBuildStore(p->builder, v, ptr.value);
  412. } else {
  413. Type *ca = core_type(a);
  414. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  415. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  416. } else {
  417. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  418. }
  419. LLVMBuildStore(p->builder, value.value, ptr.value);
  420. }
  421. }
  422. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  423. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  424. }
  425. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  426. lbModule *m = p->module;
  427. GB_ASSERT(value.value != nullptr);
  428. GB_ASSERT(is_type_pointer(value.type));
  429. Type *t = type_deref(value.type);
  430. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  431. return lbValue{v, t};
  432. }
  433. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  434. GB_ASSERT(addr.addr.value != nullptr);
  435. if (addr.kind == lbAddr_RelativePointer) {
  436. Type *rel_ptr = base_type(lb_addr_type(addr));
  437. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  438. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  439. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  440. offset = lb_emit_load(p, offset);
  441. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  442. offset = lb_emit_conv(p, offset, t_i64);
  443. }
  444. offset = lb_emit_conv(p, offset, t_uintptr);
  445. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  446. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  447. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  448. // NOTE(bill): nil check
  449. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  450. lbValue final_ptr = {};
  451. final_ptr.type = absolute_ptr.type;
  452. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  453. return lb_emit_load(p, final_ptr);
  454. } else if (addr.kind == lbAddr_RelativeSlice) {
  455. Type *rel_ptr = base_type(lb_addr_type(addr));
  456. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  457. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  458. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  459. lbValue offset = lb_emit_load(p, offset_ptr);
  460. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  461. offset = lb_emit_conv(p, offset, t_i64);
  462. }
  463. offset = lb_emit_conv(p, offset, t_uintptr);
  464. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  465. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  466. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  467. Type *slice_elem = slice_type->Slice.elem;
  468. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  469. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  470. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  471. // NOTE(bill): nil check
  472. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  473. lbValue data = {};
  474. data.type = absolute_ptr.type;
  475. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  476. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  477. len = lb_emit_conv(p, len, t_int);
  478. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  479. lb_fill_slice(p, slice, data, len);
  480. return lb_addr_load(p, slice);
  481. } else if (addr.kind == lbAddr_Map) {
  482. Type *map_type = base_type(addr.map.type);
  483. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  484. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  485. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  486. auto args = array_make<lbValue>(permanent_allocator(), 2);
  487. args[0] = h;
  488. args[1] = key;
  489. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  490. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  491. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  492. lbBlock *then = lb_create_block(p, "map.get.then");
  493. lbBlock *done = lb_create_block(p, "map.get.done");
  494. lb_emit_if(p, ok, then, done);
  495. lb_start_block(p, then);
  496. {
  497. // TODO(bill): mem copy it instead?
  498. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  499. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  500. lb_emit_store(p, gep0, lb_emit_load(p, value));
  501. }
  502. lb_emit_jump(p, done);
  503. lb_start_block(p, done);
  504. if (is_type_tuple(addr.map.result)) {
  505. return lb_addr_load(p, v);
  506. } else {
  507. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  508. return lb_emit_load(p, single);
  509. }
  510. } else if (addr.kind == lbAddr_Context) {
  511. lbValue a = addr.addr;
  512. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  513. if (addr.ctx.sel.index.count > 0) {
  514. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  515. return lb_emit_load(p, b);
  516. } else {
  517. return lb_emit_load(p, a);
  518. }
  519. } else if (addr.kind == lbAddr_SoaVariable) {
  520. Type *t = type_deref(addr.addr.type);
  521. t = base_type(t);
  522. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  523. Type *elem = t->Struct.soa_elem;
  524. lbValue len = {};
  525. if (t->Struct.soa_kind == StructSoa_Fixed) {
  526. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  527. } else {
  528. lbValue v = lb_emit_load(p, addr.addr);
  529. len = lb_soa_struct_len(p, v);
  530. }
  531. lbAddr res = lb_add_local_generated(p, elem, true);
  532. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  533. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  534. }
  535. if (t->Struct.soa_kind == StructSoa_Fixed) {
  536. for_array(i, t->Struct.fields) {
  537. Entity *field = t->Struct.fields[i];
  538. Type *base_type = field->type;
  539. GB_ASSERT(base_type->kind == Type_Array);
  540. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  541. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  542. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  543. lbValue src = lb_emit_load(p, src_ptr);
  544. lb_emit_store(p, dst, src);
  545. }
  546. } else {
  547. isize field_count = t->Struct.fields.count;
  548. if (t->Struct.soa_kind == StructSoa_Slice) {
  549. field_count -= 1;
  550. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  551. field_count -= 3;
  552. }
  553. for (isize i = 0; i < field_count; i++) {
  554. Entity *field = t->Struct.fields[i];
  555. Type *base_type = field->type;
  556. GB_ASSERT(base_type->kind == Type_Pointer);
  557. Type *elem = base_type->Pointer.elem;
  558. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  559. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  560. lbValue src = lb_emit_load(p, src_ptr);
  561. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  562. src = lb_emit_load(p, src);
  563. lb_emit_store(p, dst, src);
  564. }
  565. }
  566. return lb_addr_load(p, res);
  567. }
  568. if (is_type_proc(addr.addr.type)) {
  569. return addr.addr;
  570. }
  571. return lb_emit_load(p, addr.addr);
  572. }
  573. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  574. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  575. }
  576. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  577. Type *t = u.type;
  578. GB_ASSERT_MSG(is_type_pointer(t) &&
  579. is_type_union(type_deref(t)), "%s", type_to_string(t));
  580. Type *ut = type_deref(t);
  581. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  582. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  583. GB_ASSERT(type_size_of(ut) > 0);
  584. Type *tag_type = union_tag_type(ut);
  585. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  586. unsigned element_count = LLVMCountStructElementTypes(uvt);
  587. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  588. lbValue tag_ptr = {};
  589. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  590. tag_ptr.type = alloc_type_pointer(tag_type);
  591. return tag_ptr;
  592. }
  593. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  594. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  595. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  596. return lb_emit_load(p, tag_ptr);
  597. }
  598. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  599. Type *t = type_deref(parent.type);
  600. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  601. // No tag needed!
  602. } else {
  603. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  604. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  605. }
  606. }
  607. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  608. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  609. lb_emit_store(p, underlying, variant);
  610. lb_emit_store_union_variant_tag(p, parent, variant_type);
  611. }
  612. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  613. unsigned field_count = LLVMCountStructElementTypes(src);
  614. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  615. LLVMGetStructElementTypes(src, fields);
  616. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  617. }
  618. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  619. switch (alignment) {
  620. case 1:
  621. return LLVMArrayType(lb_type(m, t_u8), 0);
  622. case 2:
  623. return LLVMArrayType(lb_type(m, t_u16), 0);
  624. case 4:
  625. return LLVMArrayType(lb_type(m, t_u32), 0);
  626. case 8:
  627. return LLVMArrayType(lb_type(m, t_u64), 0);
  628. case 16:
  629. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  630. default:
  631. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  632. break;
  633. }
  634. return nullptr;
  635. }
  636. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  637. if (!elem_type_can_be_constant(elem_type)) {
  638. return false;
  639. }
  640. if (elem->kind == Ast_FieldValue) {
  641. elem = elem->FieldValue.value;
  642. }
  643. TypeAndValue tav = type_and_value_of_expr(elem);
  644. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  645. return tav.value.kind != ExactValue_Invalid;
  646. }
  647. String lb_mangle_name(lbModule *m, Entity *e) {
  648. String name = e->token.string;
  649. AstPackage *pkg = e->pkg;
  650. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  651. String pkgn = pkg->name;
  652. GB_ASSERT(!rune_is_digit(pkgn[0]));
  653. if (pkgn == "llvm") {
  654. pkgn = str_lit("llvm$");
  655. }
  656. isize max_len = pkgn.len + 1 + name.len + 1;
  657. bool require_suffix_id = is_type_polymorphic(e->type, true);
  658. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  659. require_suffix_id = true;
  660. } else if (is_blank_ident(e->token)) {
  661. require_suffix_id = true;
  662. }if (e->flags & EntityFlag_NotExported) {
  663. require_suffix_id = true;
  664. }
  665. if (require_suffix_id) {
  666. max_len += 21;
  667. }
  668. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  669. isize new_name_len = gb_snprintf(
  670. new_name, max_len,
  671. "%.*s.%.*s", LIT(pkgn), LIT(name)
  672. );
  673. if (require_suffix_id) {
  674. char *str = new_name + new_name_len-1;
  675. isize len = max_len-new_name_len;
  676. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  677. new_name_len += extra-1;
  678. }
  679. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  680. return mangled_name;
  681. }
  682. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  683. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  684. // and as a result, the declaration does not have time to determine what it should be
  685. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  686. if (e->TypeName.ir_mangled_name.len != 0) {
  687. return e->TypeName.ir_mangled_name;
  688. }
  689. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  690. if (p == nullptr) {
  691. Entity *proc = nullptr;
  692. if (e->parent_proc_decl != nullptr) {
  693. proc = e->parent_proc_decl->entity;
  694. } else {
  695. Scope *scope = e->scope;
  696. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  697. scope = scope->parent;
  698. }
  699. GB_ASSERT(scope != nullptr);
  700. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  701. proc = scope->procedure_entity;
  702. }
  703. GB_ASSERT(proc->kind == Entity_Procedure);
  704. if (proc->code_gen_procedure != nullptr) {
  705. p = proc->code_gen_procedure;
  706. }
  707. }
  708. // NOTE(bill): Generate a new name
  709. // parent_proc.name-guid
  710. String ts_name = e->token.string;
  711. if (p != nullptr) {
  712. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  713. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  714. u32 guid = ++p->module->nested_type_name_guid;
  715. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  716. String name = make_string(cast(u8 *)name_text, name_len-1);
  717. e->TypeName.ir_mangled_name = name;
  718. return name;
  719. } else {
  720. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  721. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  722. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  723. static u32 guid = 0;
  724. guid += 1;
  725. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  726. String name = make_string(cast(u8 *)name_text, name_len-1);
  727. e->TypeName.ir_mangled_name = name;
  728. return name;
  729. }
  730. }
  731. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  732. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  733. return e->TypeName.ir_mangled_name;
  734. }
  735. GB_ASSERT(e != nullptr);
  736. if (e->pkg == nullptr) {
  737. return e->token.string;
  738. }
  739. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  740. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  741. }
  742. String name = {};
  743. bool no_name_mangle = false;
  744. if (e->kind == Entity_Variable) {
  745. bool is_foreign = e->Variable.is_foreign;
  746. bool is_export = e->Variable.is_export;
  747. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  748. if (e->Variable.link_name.len > 0) {
  749. return e->Variable.link_name;
  750. }
  751. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  752. return e->Procedure.link_name;
  753. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  754. no_name_mangle = true;
  755. }
  756. if (!no_name_mangle) {
  757. name = lb_mangle_name(m, e);
  758. }
  759. if (name.len == 0) {
  760. name = e->token.string;
  761. }
  762. if (e->kind == Entity_TypeName) {
  763. e->TypeName.ir_mangled_name = name;
  764. } else if (e->kind == Entity_Procedure) {
  765. e->Procedure.link_name = name;
  766. }
  767. return name;
  768. }
  769. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  770. Type *original_type = type;
  771. LLVMContextRef ctx = m->ctx;
  772. i64 size = type_size_of(type); // Check size
  773. GB_ASSERT(type != t_invalid);
  774. switch (type->kind) {
  775. case Type_Basic:
  776. switch (type->Basic.kind) {
  777. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  778. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  779. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  780. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  781. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  782. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  783. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  784. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  785. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  786. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  787. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  788. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  789. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  790. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  791. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  792. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  793. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  794. // Basic_f16,
  795. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  796. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  797. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  798. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  799. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  800. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  801. // Basic_complex32,
  802. case Basic_complex64:
  803. {
  804. char const *name = "..complex64";
  805. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  806. if (type != nullptr) {
  807. return type;
  808. }
  809. type = LLVMStructCreateNamed(ctx, name);
  810. LLVMTypeRef fields[2] = {
  811. lb_type(m, t_f32),
  812. lb_type(m, t_f32),
  813. };
  814. LLVMStructSetBody(type, fields, 2, false);
  815. return type;
  816. }
  817. case Basic_complex128:
  818. {
  819. char const *name = "..complex128";
  820. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  821. if (type != nullptr) {
  822. return type;
  823. }
  824. type = LLVMStructCreateNamed(ctx, name);
  825. LLVMTypeRef fields[2] = {
  826. lb_type(m, t_f64),
  827. lb_type(m, t_f64),
  828. };
  829. LLVMStructSetBody(type, fields, 2, false);
  830. return type;
  831. }
  832. case Basic_quaternion128:
  833. {
  834. char const *name = "..quaternion128";
  835. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  836. if (type != nullptr) {
  837. return type;
  838. }
  839. type = LLVMStructCreateNamed(ctx, name);
  840. LLVMTypeRef fields[4] = {
  841. lb_type(m, t_f32),
  842. lb_type(m, t_f32),
  843. lb_type(m, t_f32),
  844. lb_type(m, t_f32),
  845. };
  846. LLVMStructSetBody(type, fields, 4, false);
  847. return type;
  848. }
  849. case Basic_quaternion256:
  850. {
  851. char const *name = "..quaternion256";
  852. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  853. if (type != nullptr) {
  854. return type;
  855. }
  856. type = LLVMStructCreateNamed(ctx, name);
  857. LLVMTypeRef fields[4] = {
  858. lb_type(m, t_f64),
  859. lb_type(m, t_f64),
  860. lb_type(m, t_f64),
  861. lb_type(m, t_f64),
  862. };
  863. LLVMStructSetBody(type, fields, 4, false);
  864. return type;
  865. }
  866. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  867. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  868. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  869. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  870. case Basic_string:
  871. {
  872. char const *name = "..string";
  873. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  874. if (type != nullptr) {
  875. return type;
  876. }
  877. type = LLVMStructCreateNamed(ctx, name);
  878. LLVMTypeRef fields[2] = {
  879. LLVMPointerType(lb_type(m, t_u8), 0),
  880. lb_type(m, t_int),
  881. };
  882. LLVMStructSetBody(type, fields, 2, false);
  883. return type;
  884. }
  885. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  886. case Basic_any:
  887. {
  888. char const *name = "..any";
  889. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  890. if (type != nullptr) {
  891. return type;
  892. }
  893. type = LLVMStructCreateNamed(ctx, name);
  894. LLVMTypeRef fields[2] = {
  895. lb_type(m, t_rawptr),
  896. lb_type(m, t_typeid),
  897. };
  898. LLVMStructSetBody(type, fields, 2, false);
  899. return type;
  900. }
  901. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  902. // Endian Specific Types
  903. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  904. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  905. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  906. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  907. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  908. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  909. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  910. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  911. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  912. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  913. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  914. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  915. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  916. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  917. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  918. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  919. // Untyped types
  920. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  921. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  922. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  923. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  924. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  925. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  926. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  927. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  928. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  929. }
  930. break;
  931. case Type_Named:
  932. {
  933. Type *base = base_type(type->Named.base);
  934. switch (base->kind) {
  935. case Type_Basic:
  936. return lb_type_internal(m, base);
  937. case Type_Named:
  938. case Type_Generic:
  939. GB_PANIC("INVALID TYPE");
  940. break;
  941. case Type_Pointer:
  942. case Type_Array:
  943. case Type_EnumeratedArray:
  944. case Type_Slice:
  945. case Type_DynamicArray:
  946. case Type_Map:
  947. case Type_Enum:
  948. case Type_BitSet:
  949. case Type_SimdVector:
  950. return lb_type_internal(m, base);
  951. // TODO(bill): Deal with this correctly. Can this be named?
  952. case Type_Proc:
  953. return lb_type_internal(m, base);
  954. case Type_Tuple:
  955. return lb_type_internal(m, base);
  956. }
  957. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  958. if (found) {
  959. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  960. if (kind == LLVMStructTypeKind) {
  961. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  962. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  963. if (llvm_type != nullptr) {
  964. return llvm_type;
  965. }
  966. llvm_type = LLVMStructCreateNamed(ctx, name);
  967. map_set(&m->types, hash_type(type), llvm_type);
  968. lb_clone_struct_type(llvm_type, *found);
  969. return llvm_type;
  970. }
  971. }
  972. switch (base->kind) {
  973. case Type_Struct:
  974. case Type_Union:
  975. {
  976. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  977. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  978. if (llvm_type != nullptr) {
  979. return llvm_type;
  980. }
  981. llvm_type = LLVMStructCreateNamed(ctx, name);
  982. map_set(&m->types, hash_type(type), llvm_type);
  983. lb_clone_struct_type(llvm_type, lb_type(m, base));
  984. return llvm_type;
  985. }
  986. }
  987. return lb_type_internal(m, base);
  988. }
  989. case Type_Pointer:
  990. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  991. case Type_Array: {
  992. m->internal_type_level -= 1;
  993. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  994. m->internal_type_level += 1;
  995. return t;
  996. }
  997. case Type_EnumeratedArray: {
  998. m->internal_type_level -= 1;
  999. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1000. m->internal_type_level += 1;
  1001. return t;
  1002. }
  1003. case Type_Slice:
  1004. {
  1005. LLVMTypeRef fields[2] = {
  1006. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1007. lb_type(m, t_int), // len
  1008. };
  1009. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1010. }
  1011. break;
  1012. case Type_DynamicArray:
  1013. {
  1014. LLVMTypeRef fields[4] = {
  1015. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1016. lb_type(m, t_int), // len
  1017. lb_type(m, t_int), // cap
  1018. lb_type(m, t_allocator), // allocator
  1019. };
  1020. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1021. }
  1022. break;
  1023. case Type_Map:
  1024. return lb_type(m, type->Map.internal_type);
  1025. case Type_Struct:
  1026. {
  1027. if (type->Struct.is_raw_union) {
  1028. unsigned field_count = 2;
  1029. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1030. i64 alignment = type_align_of(type);
  1031. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1032. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1033. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1034. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1035. }
  1036. isize offset = 0;
  1037. if (type->Struct.custom_align > 0) {
  1038. offset = 1;
  1039. }
  1040. m->internal_type_level += 1;
  1041. defer (m->internal_type_level -= 1);
  1042. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1043. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1044. for_array(i, type->Struct.fields) {
  1045. Entity *field = type->Struct.fields[i];
  1046. fields[i+offset] = lb_type(m, field->type);
  1047. }
  1048. if (type->Struct.custom_align > 0) {
  1049. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1050. }
  1051. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1052. }
  1053. break;
  1054. case Type_Union:
  1055. if (type->Union.variants.count == 0) {
  1056. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1057. } else {
  1058. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1059. // LLVM takes the first element's alignment as the entire alignment (like C)
  1060. i64 align = type_align_of(type);
  1061. i64 size = type_size_of(type);
  1062. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1063. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1064. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1065. }
  1066. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1067. LLVMTypeRef fields[3] = {};
  1068. unsigned field_count = 1;
  1069. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1070. if (is_type_union_maybe_pointer(type)) {
  1071. field_count += 1;
  1072. fields[1] = lb_type(m, type->Union.variants[0]);
  1073. } else {
  1074. field_count += 2;
  1075. if (block_size == align) {
  1076. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1077. } else {
  1078. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1079. }
  1080. fields[2] = lb_type(m, union_tag_type(type));
  1081. }
  1082. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1083. }
  1084. break;
  1085. case Type_Enum:
  1086. return lb_type(m, base_enum_type(type));
  1087. case Type_Tuple:
  1088. if (type->Tuple.variables.count == 1) {
  1089. return lb_type(m, type->Tuple.variables[0]->type);
  1090. } else {
  1091. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1092. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1093. for_array(i, type->Tuple.variables) {
  1094. Entity *field = type->Tuple.variables[i];
  1095. LLVMTypeRef param_type = nullptr;
  1096. param_type = lb_type(m, field->type);
  1097. fields[i] = param_type;
  1098. }
  1099. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1100. }
  1101. case Type_Proc:
  1102. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1103. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1104. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1105. } else {
  1106. unsigned param_count = 0;
  1107. if (type->Proc.calling_convention == ProcCC_Odin) {
  1108. param_count += 1;
  1109. }
  1110. if (type->Proc.param_count != 0) {
  1111. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1112. for_array(i, type->Proc.params->Tuple.variables) {
  1113. Entity *e = type->Proc.params->Tuple.variables[i];
  1114. if (e->kind != Entity_Variable) {
  1115. continue;
  1116. }
  1117. param_count += 1;
  1118. }
  1119. }
  1120. m->internal_type_level += 1;
  1121. defer (m->internal_type_level -= 1);
  1122. LLVMTypeRef ret = nullptr;
  1123. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1124. if (type->Proc.result_count != 0) {
  1125. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1126. ret = lb_type(m, single_ret);
  1127. if (ret != nullptr) {
  1128. if (is_type_boolean(single_ret) &&
  1129. is_calling_convention_none(type->Proc.calling_convention) &&
  1130. type_size_of(single_ret) <= 1) {
  1131. ret = LLVMInt1TypeInContext(m->ctx);
  1132. }
  1133. }
  1134. }
  1135. isize param_index = 0;
  1136. if (type->Proc.param_count != 0) {
  1137. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1138. for_array(i, type->Proc.params->Tuple.variables) {
  1139. Entity *e = type->Proc.params->Tuple.variables[i];
  1140. if (e->kind != Entity_Variable) {
  1141. continue;
  1142. }
  1143. Type *e_type = reduce_tuple_to_single_type(e->type);
  1144. LLVMTypeRef param_type = nullptr;
  1145. if (is_type_boolean(e_type) &&
  1146. type_size_of(e_type) <= 1) {
  1147. param_type = LLVMInt1TypeInContext(m->ctx);
  1148. } else {
  1149. if (is_type_proc(e_type)) {
  1150. param_type = lb_type(m, t_rawptr);
  1151. } else {
  1152. param_type = lb_type(m, e_type);
  1153. }
  1154. }
  1155. params[param_index++] = param_type;
  1156. }
  1157. }
  1158. if (param_index < param_count) {
  1159. params[param_index++] = lb_type(m, t_rawptr);
  1160. // params[param_index++] = lb_type(m, t_context_ptr);
  1161. }
  1162. GB_ASSERT(param_index == param_count);
  1163. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1164. map_set(&m->function_type_map, hash_type(type), ft);
  1165. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1166. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1167. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1168. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1169. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1170. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1171. // GB_ASSERT_MSG(new_count == old_count, "%u %u, %s %s", new_count, old_count, LLVMPrintTypeToString(new_abi_fn_type), LLVMPrintTypeToString(old_abi_fn_type));
  1172. return new_abi_fn_ptr_type;
  1173. }
  1174. break;
  1175. case Type_BitSet:
  1176. {
  1177. Type *ut = bit_set_to_int(type);
  1178. return lb_type(m, ut);
  1179. }
  1180. case Type_SimdVector:
  1181. if (type->SimdVector.is_x86_mmx) {
  1182. return LLVMX86MMXTypeInContext(ctx);
  1183. }
  1184. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1185. case Type_RelativePointer:
  1186. return lb_type_internal(m, type->RelativePointer.base_integer);
  1187. case Type_RelativeSlice:
  1188. {
  1189. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1190. unsigned field_count = 2;
  1191. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1192. fields[0] = base_integer;
  1193. fields[1] = base_integer;
  1194. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1195. }
  1196. }
  1197. GB_PANIC("Invalid type %s", type_to_string(type));
  1198. return LLVMInt32TypeInContext(ctx);
  1199. }
  1200. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1201. type = default_type(type);
  1202. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1203. if (found) {
  1204. return *found;
  1205. }
  1206. LLVMTypeRef llvm_type = nullptr;
  1207. m->internal_type_level += 1;
  1208. llvm_type = lb_type_internal(m, type);
  1209. m->internal_type_level -= 1;
  1210. if (m->internal_type_level == 0) {
  1211. map_set(&m->types, hash_type(type), llvm_type);
  1212. if (is_type_named(type)) {
  1213. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1214. }
  1215. }
  1216. return llvm_type;
  1217. }
  1218. LLVMMetadataRef lb_get_llvm_metadata(lbModule *m, void *key) {
  1219. if (key == nullptr) {
  1220. return nullptr;
  1221. }
  1222. auto found = map_get(&m->debug_values, hash_pointer(key));
  1223. if (found) {
  1224. return *found;
  1225. }
  1226. return nullptr;
  1227. }
  1228. void lb_set_llvm_metadata(lbModule *m, void *key, LLVMMetadataRef value) {
  1229. if (key != nullptr) {
  1230. map_set(&m->debug_values, hash_pointer(key), value);
  1231. }
  1232. }
  1233. LLVMMetadataRef lb_get_llvm_file_metadata_from_node(lbModule *m, Ast *node) {
  1234. if (node == nullptr) {
  1235. return nullptr;
  1236. }
  1237. return lb_get_llvm_metadata(m, node->file);
  1238. }
  1239. LLVMMetadataRef lb_get_current_debug_scope(lbProcedure *p) {
  1240. GB_ASSERT_MSG(p->debug_info != nullptr, "missing debug information for %.*s", LIT(p->name));
  1241. for (isize i = p->scope_stack.count-1; i >= 0; i--) {
  1242. Scope *s = p->scope_stack[i];
  1243. LLVMMetadataRef md = lb_get_llvm_metadata(p->module, s);
  1244. if (md) {
  1245. return md;
  1246. }
  1247. }
  1248. return p->debug_info;
  1249. }
  1250. LLVMMetadataRef lb_debug_location_from_token_pos(lbProcedure *p, TokenPos pos) {
  1251. LLVMMetadataRef scope = lb_get_current_debug_scope(p);
  1252. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  1253. return LLVMDIBuilderCreateDebugLocation(p->module->ctx, cast(unsigned)pos.line, cast(unsigned)pos.column, scope, nullptr);
  1254. }
  1255. LLVMMetadataRef lb_debug_location_from_ast(lbProcedure *p, Ast *node) {
  1256. GB_ASSERT(node != nullptr);
  1257. return lb_debug_location_from_token_pos(p, ast_token(node).pos);
  1258. }
  1259. LLVMMetadataRef lb_debug_type_internal_proc(lbModule *m, Type *type) {
  1260. Type *original_type = type;
  1261. LLVMContextRef ctx = m->ctx;
  1262. i64 size = type_size_of(type); // Check size
  1263. GB_ASSERT(type != t_invalid);
  1264. unsigned const word_size = cast(unsigned)build_context.word_size;
  1265. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1266. GB_ASSERT(type->kind == Type_Proc);
  1267. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1268. unsigned parameter_count = 1;
  1269. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1270. Entity *e = type->Proc.params->Tuple.variables[i];
  1271. if (e->kind == Entity_Variable) {
  1272. parameter_count += 1;
  1273. }
  1274. }
  1275. LLVMMetadataRef *parameters = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, parameter_count);
  1276. unsigned param_index = 0;
  1277. if (type->Proc.result_count == 0) {
  1278. parameters[param_index++] = nullptr;
  1279. } else {
  1280. parameters[param_index++] = lb_debug_type(m, type->Proc.results);
  1281. }
  1282. LLVMMetadataRef parent_scope = nullptr;
  1283. LLVMMetadataRef scope = nullptr;
  1284. LLVMMetadataRef file = nullptr;
  1285. for (i32 i = 0; i < type->Proc.param_count; i++) {
  1286. Entity *e = type->Proc.params->Tuple.variables[i];
  1287. if (e->kind != Entity_Variable) {
  1288. continue;
  1289. }
  1290. parameters[param_index] = lb_debug_type(m, e->type);
  1291. param_index += 1;
  1292. }
  1293. LLVMDIFlags flags = LLVMDIFlagZero;
  1294. if (type->Proc.diverging) {
  1295. flags = LLVMDIFlagNoReturn;
  1296. }
  1297. return LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, parameters, parameter_count, flags);
  1298. }
  1299. LLVMMetadataRef lb_debug_struct_field(lbModule *m, String const &name, Type *type, u64 offset_in_bits) {
  1300. unsigned field_line = 1;
  1301. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1302. AstPackage *pkg = m->info->runtime_package;
  1303. GB_ASSERT(pkg->files.count != 0);
  1304. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1305. LLVMMetadataRef scope = file;
  1306. return LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1307. 8*cast(u64)type_size_of(type), 8*cast(u32)type_align_of(type), offset_in_bits,
  1308. field_flags, lb_debug_type(m, type)
  1309. );
  1310. }
  1311. LLVMMetadataRef lb_debug_basic_struct(lbModule *m, String const &name, u64 size_in_bits, u32 align_in_bits, LLVMMetadataRef *elements, unsigned element_count) {
  1312. AstPackage *pkg = m->info->runtime_package;
  1313. GB_ASSERT(pkg->files.count != 0);
  1314. LLVMMetadataRef file = lb_get_llvm_metadata(m, pkg->files[0]);
  1315. LLVMMetadataRef scope = file;
  1316. return LLVMDIBuilderCreateStructType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, 1, size_in_bits, align_in_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1317. }
  1318. LLVMMetadataRef lb_debug_type_basic_type(lbModule *m, String const &name, u64 size_in_bits, LLVMDWARFTypeEncoding encoding, LLVMDIFlags flags = LLVMDIFlagZero) {
  1319. LLVMMetadataRef basic_type = LLVMDIBuilderCreateBasicType(m->debug_builder, cast(char const *)name.text, name.len, size_in_bits, encoding, flags);
  1320. #if 1
  1321. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, basic_type, cast(char const *)name.text, name.len, nullptr, 0, nullptr, cast(u32)size_in_bits);
  1322. return final_decl;
  1323. #else
  1324. return basic_type;
  1325. #endif
  1326. }
  1327. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1328. Type *original_type = type;
  1329. LLVMContextRef ctx = m->ctx;
  1330. i64 size = type_size_of(type); // Check size
  1331. GB_ASSERT(type != t_invalid);
  1332. unsigned const word_size = cast(unsigned)build_context.word_size;
  1333. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1334. switch (type->kind) {
  1335. case Type_Basic:
  1336. switch (type->Basic.kind) {
  1337. case Basic_llvm_bool: return lb_debug_type_basic_type(m, str_lit("llvm bool"), 1, LLVMDWARFTypeEncoding_Boolean);
  1338. case Basic_bool: return lb_debug_type_basic_type(m, str_lit("bool"), 8, LLVMDWARFTypeEncoding_Boolean);
  1339. case Basic_b8: return lb_debug_type_basic_type(m, str_lit("b8"), 8, LLVMDWARFTypeEncoding_Boolean);
  1340. case Basic_b16: return lb_debug_type_basic_type(m, str_lit("b16"), 16, LLVMDWARFTypeEncoding_Boolean);
  1341. case Basic_b32: return lb_debug_type_basic_type(m, str_lit("b32"), 32, LLVMDWARFTypeEncoding_Boolean);
  1342. case Basic_b64: return lb_debug_type_basic_type(m, str_lit("b64"), 64, LLVMDWARFTypeEncoding_Boolean);
  1343. case Basic_i8: return lb_debug_type_basic_type(m, str_lit("i8"), 8, LLVMDWARFTypeEncoding_Signed);
  1344. case Basic_u8: return lb_debug_type_basic_type(m, str_lit("u8"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1345. case Basic_i16: return lb_debug_type_basic_type(m, str_lit("i16"), 16, LLVMDWARFTypeEncoding_Signed);
  1346. case Basic_u16: return lb_debug_type_basic_type(m, str_lit("u16"), 16, LLVMDWARFTypeEncoding_Unsigned);
  1347. case Basic_i32: return lb_debug_type_basic_type(m, str_lit("i32"), 32, LLVMDWARFTypeEncoding_Signed);
  1348. case Basic_u32: return lb_debug_type_basic_type(m, str_lit("u32"), 32, LLVMDWARFTypeEncoding_Unsigned);
  1349. case Basic_i64: return lb_debug_type_basic_type(m, str_lit("i64"), 64, LLVMDWARFTypeEncoding_Signed);
  1350. case Basic_u64: return lb_debug_type_basic_type(m, str_lit("u64"), 64, LLVMDWARFTypeEncoding_Unsigned);
  1351. case Basic_i128: return lb_debug_type_basic_type(m, str_lit("i128"), 128, LLVMDWARFTypeEncoding_Signed);
  1352. case Basic_u128: return lb_debug_type_basic_type(m, str_lit("u128"), 128, LLVMDWARFTypeEncoding_Unsigned);
  1353. case Basic_rune: return lb_debug_type_basic_type(m, str_lit("rune"), 32, LLVMDWARFTypeEncoding_Utf);
  1354. // Basic_f16,
  1355. case Basic_f32: return lb_debug_type_basic_type(m, str_lit("f32"), 32, LLVMDWARFTypeEncoding_Float);
  1356. case Basic_f64: return lb_debug_type_basic_type(m, str_lit("f64"), 64, LLVMDWARFTypeEncoding_Float);
  1357. case Basic_int: return lb_debug_type_basic_type(m, str_lit("int"), word_bits, LLVMDWARFTypeEncoding_Signed);
  1358. case Basic_uint: return lb_debug_type_basic_type(m, str_lit("uint"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1359. case Basic_uintptr: return lb_debug_type_basic_type(m, str_lit("uintptr"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1360. case Basic_typeid:
  1361. return lb_debug_type_basic_type(m, str_lit("typeid"), word_bits, LLVMDWARFTypeEncoding_Unsigned);
  1362. // Endian Specific Types
  1363. case Basic_i16le: return lb_debug_type_basic_type(m, str_lit("i16le"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1364. case Basic_u16le: return lb_debug_type_basic_type(m, str_lit("u16le"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1365. case Basic_i32le: return lb_debug_type_basic_type(m, str_lit("i32le"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1366. case Basic_u32le: return lb_debug_type_basic_type(m, str_lit("u32le"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1367. case Basic_i64le: return lb_debug_type_basic_type(m, str_lit("i64le"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1368. case Basic_u64le: return lb_debug_type_basic_type(m, str_lit("u64le"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1369. case Basic_i128le: return lb_debug_type_basic_type(m, str_lit("i128le"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagLittleEndian);
  1370. case Basic_u128le: return lb_debug_type_basic_type(m, str_lit("u128le"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagLittleEndian);
  1371. case Basic_f32le: return lb_debug_type_basic_type(m, str_lit("f32le"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1372. case Basic_f64le: return lb_debug_type_basic_type(m, str_lit("f64le"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1373. case Basic_i16be: return lb_debug_type_basic_type(m, str_lit("i16be"), 16, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1374. case Basic_u16be: return lb_debug_type_basic_type(m, str_lit("u16be"), 16, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1375. case Basic_i32be: return lb_debug_type_basic_type(m, str_lit("i32be"), 32, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1376. case Basic_u32be: return lb_debug_type_basic_type(m, str_lit("u32be"), 32, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1377. case Basic_i64be: return lb_debug_type_basic_type(m, str_lit("i64be"), 64, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1378. case Basic_u64be: return lb_debug_type_basic_type(m, str_lit("u64be"), 64, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1379. case Basic_i128be: return lb_debug_type_basic_type(m, str_lit("i128be"), 128, LLVMDWARFTypeEncoding_Signed, LLVMDIFlagBigEndian);
  1380. case Basic_u128be: return lb_debug_type_basic_type(m, str_lit("u128be"), 128, LLVMDWARFTypeEncoding_Unsigned, LLVMDIFlagBigEndian);
  1381. case Basic_f32be: return lb_debug_type_basic_type(m, str_lit("f32be"), 32, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1382. case Basic_f64be: return lb_debug_type_basic_type(m, str_lit("f64be"), 64, LLVMDWARFTypeEncoding_Float, LLVMDIFlagLittleEndian);
  1383. // Basic_complex32,
  1384. case Basic_complex64:
  1385. {
  1386. LLVMMetadataRef elements[2] = {};
  1387. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f32, 0);
  1388. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 4);
  1389. return lb_debug_basic_struct(m, str_lit("complex64"), 64, 32, elements, gb_count_of(elements));
  1390. }
  1391. case Basic_complex128:
  1392. {
  1393. LLVMMetadataRef elements[2] = {};
  1394. elements[0] = lb_debug_struct_field(m, str_lit("real"), t_f64, 0);
  1395. elements[1] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 8);
  1396. return lb_debug_basic_struct(m, str_lit("complex128"), 128, 64, elements, gb_count_of(elements));
  1397. }
  1398. case Basic_quaternion128:
  1399. {
  1400. LLVMMetadataRef elements[4] = {};
  1401. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f32, 0);
  1402. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f32, 4);
  1403. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f32, 8);
  1404. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f32, 12);
  1405. return lb_debug_basic_struct(m, str_lit("quaternion128"), 128, 32, elements, gb_count_of(elements));
  1406. }
  1407. case Basic_quaternion256:
  1408. {
  1409. LLVMMetadataRef elements[4] = {};
  1410. elements[0] = lb_debug_struct_field(m, str_lit("imag"), t_f64, 0);
  1411. elements[1] = lb_debug_struct_field(m, str_lit("jmag"), t_f64, 8);
  1412. elements[2] = lb_debug_struct_field(m, str_lit("kmag"), t_f64, 16);
  1413. elements[3] = lb_debug_struct_field(m, str_lit("real"), t_f64, 24);
  1414. return lb_debug_basic_struct(m, str_lit("quaternion256"), 256, 32, elements, gb_count_of(elements));
  1415. }
  1416. case Basic_rawptr:
  1417. {
  1418. LLVMMetadataRef void_type = lb_debug_type_basic_type(m, str_lit("void"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1419. return LLVMDIBuilderCreatePointerType(m->debug_builder, void_type, word_bits, word_bits, LLVMDWARFTypeEncoding_Address, "rawptr", 6);
  1420. }
  1421. case Basic_string:
  1422. {
  1423. LLVMMetadataRef elements[2] = {};
  1424. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_u8_ptr, 0);
  1425. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, word_bits);
  1426. return lb_debug_basic_struct(m, str_lit("string"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1427. }
  1428. case Basic_cstring:
  1429. {
  1430. LLVMMetadataRef char_type = lb_debug_type_basic_type(m, str_lit("char"), 8, LLVMDWARFTypeEncoding_Unsigned);
  1431. return LLVMDIBuilderCreatePointerType(m->debug_builder, char_type, word_bits, word_bits, 0, "cstring", 7);
  1432. }
  1433. case Basic_any:
  1434. {
  1435. LLVMMetadataRef elements[2] = {};
  1436. elements[0] = lb_debug_struct_field(m, str_lit("data"), t_rawptr, 0);
  1437. elements[1] = lb_debug_struct_field(m, str_lit("id"), t_typeid, word_bits);
  1438. return lb_debug_basic_struct(m, str_lit("any"), 2*word_bits, word_bits, elements, gb_count_of(elements));
  1439. }
  1440. // Untyped types
  1441. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1442. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1443. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1444. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1445. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1446. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1447. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1448. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1449. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1450. default: GB_PANIC("Basic Unhandled"); break;
  1451. }
  1452. break;
  1453. case Type_Named:
  1454. GB_PANIC("Type_Named should be handled in lb_debug_type separately");
  1455. case Type_Pointer:
  1456. return LLVMDIBuilderCreatePointerType(m->debug_builder, lb_debug_type(m, type->Pointer.elem), word_bits, word_bits, 0, nullptr, 0);
  1457. case Type_Array:
  1458. return LLVMDIBuilderCreateArrayType(m->debug_builder,
  1459. type->Array.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->Array.elem), nullptr, 0);
  1460. case Type_EnumeratedArray: {
  1461. LLVMMetadataRef array_type = LLVMDIBuilderCreateArrayType(m->debug_builder,
  1462. type->EnumeratedArray.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->EnumeratedArray.elem), nullptr, 0);
  1463. gbString name = type_to_string(type, temporary_allocator());
  1464. return LLVMDIBuilderCreateTypedef(m->debug_builder, array_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1465. }
  1466. case Type_Struct:
  1467. case Type_Union:
  1468. case Type_Slice:
  1469. case Type_DynamicArray:
  1470. case Type_Map:
  1471. case Type_BitSet:
  1472. {
  1473. unsigned tag = DW_TAG_structure_type;
  1474. if (is_type_raw_union(type) || is_type_union(type)) {
  1475. tag = DW_TAG_union_type;
  1476. }
  1477. u64 size_in_bits = cast(u64)(8*type_size_of(type));
  1478. u32 align_in_bits = cast(u32)(8*type_size_of(type));
  1479. LLVMDIFlags flags = LLVMDIFlagZero;
  1480. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1481. m->debug_builder, tag, "", 0, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1482. );
  1483. lbIncompleteDebugType idt = {};
  1484. idt.type = type;
  1485. idt.metadata = temp_forward_decl;
  1486. array_add(&m->debug_incomplete_types, idt);
  1487. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1488. return temp_forward_decl;
  1489. }
  1490. case Type_Enum:
  1491. {
  1492. LLVMMetadataRef scope = nullptr;
  1493. LLVMMetadataRef file = nullptr;
  1494. unsigned line = 0;
  1495. unsigned element_count = cast(unsigned)type->Enum.fields.count;
  1496. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1497. Type *bt = base_enum_type(type);
  1498. LLVMBool is_unsigned = is_type_unsigned(bt);
  1499. for (unsigned i = 0; i < element_count; i++) {
  1500. Entity *f = type->Enum.fields[i];
  1501. GB_ASSERT(f->kind == Entity_Constant);
  1502. String name = f->token.string;
  1503. i64 value = exact_value_to_i64(f->Constant.value);
  1504. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1505. }
  1506. LLVMMetadataRef class_type = lb_debug_type(m, bt);
  1507. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, "", 0, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1508. }
  1509. case Type_Tuple:
  1510. if (type->Tuple.variables.count == 1) {
  1511. return lb_debug_type(m, type->Tuple.variables[0]->type);
  1512. } else {
  1513. type_set_offsets(type);
  1514. LLVMMetadataRef parent_scope = nullptr;
  1515. LLVMMetadataRef scope = nullptr;
  1516. LLVMMetadataRef file = nullptr;
  1517. unsigned line = 0;
  1518. u64 size_in_bits = 8*cast(u64)type_size_of(type);
  1519. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1520. LLVMDIFlags flags = LLVMDIFlagZero;
  1521. unsigned element_count = cast(unsigned)type->Tuple.variables.count;
  1522. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1523. for (unsigned i = 0; i < element_count; i++) {
  1524. Entity *f = type->Tuple.variables[i];
  1525. GB_ASSERT(f->kind == Entity_Variable);
  1526. String name = f->token.string;
  1527. unsigned field_line = 0;
  1528. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1529. u64 offset_in_bits = 8*cast(u64)type->Tuple.offsets[i];
  1530. elements[i] = LLVMDIBuilderCreateMemberType(m->debug_builder, scope, cast(char const *)name.text, name.len, file, field_line,
  1531. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type), offset_in_bits,
  1532. field_flags, lb_debug_type(m, f->type)
  1533. );
  1534. }
  1535. return LLVMDIBuilderCreateStructType(m->debug_builder, parent_scope, "", 0, file, line,
  1536. size_in_bits, align_in_bits, flags,
  1537. nullptr, elements, element_count, 0, nullptr,
  1538. "", 0
  1539. );
  1540. }
  1541. case Type_Proc:
  1542. {
  1543. LLVMMetadataRef proc_underlying_type = lb_debug_type_internal_proc(m, type);
  1544. LLVMMetadataRef pointer_type = LLVMDIBuilderCreatePointerType(m->debug_builder, proc_underlying_type, word_bits, word_bits, 0, nullptr, 0);
  1545. gbString name = type_to_string(type, temporary_allocator());
  1546. return LLVMDIBuilderCreateTypedef(m->debug_builder, pointer_type, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1547. }
  1548. break;
  1549. case Type_SimdVector:
  1550. if (type->SimdVector.is_x86_mmx) {
  1551. return LLVMDIBuilderCreateVectorType(m->debug_builder, 2, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, t_f64), nullptr, 0);
  1552. }
  1553. return LLVMDIBuilderCreateVectorType(m->debug_builder, cast(unsigned)type->SimdVector.count, 8*cast(unsigned)type_align_of(type), lb_debug_type(m, type->SimdVector.elem), nullptr, 0);
  1554. case Type_RelativePointer: {
  1555. LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativePointer.base_integer);
  1556. gbString name = type_to_string(type, temporary_allocator());
  1557. return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type)));
  1558. }
  1559. case Type_RelativeSlice:
  1560. {
  1561. unsigned element_count = 0;
  1562. LLVMMetadataRef elements[2] = {};
  1563. Type *base_integer = type->RelativeSlice.base_integer;
  1564. elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0);
  1565. elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, 8*type_size_of(base_integer));
  1566. gbString name = type_to_string(type, temporary_allocator());
  1567. return LLVMDIBuilderCreateStructType(m->debug_builder, nullptr, name, gb_string_length(name), nullptr, 0, 2*word_bits, word_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0);
  1568. }
  1569. }
  1570. GB_PANIC("Invalid type %s", type_to_string(type));
  1571. return nullptr;
  1572. }
  1573. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1574. GB_ASSERT(type != nullptr);
  1575. LLVMMetadataRef found = lb_get_llvm_metadata(m, type);
  1576. if (found != nullptr) {
  1577. return found;
  1578. }
  1579. if (type->kind == Type_Named) {
  1580. LLVMMetadataRef file = nullptr;
  1581. unsigned line = 0;
  1582. LLVMMetadataRef scope = nullptr;
  1583. if (type->Named.type_name != nullptr) {
  1584. Entity *e = type->Named.type_name;
  1585. scope = lb_get_llvm_metadata(m, e->scope);
  1586. if (scope != nullptr) {
  1587. file = LLVMDIScopeGetFile(scope);
  1588. }
  1589. line = cast(unsigned)e->token.pos.line;
  1590. }
  1591. // TODO(bill): location data for Type_Named
  1592. u64 size_in_bits = 8*type_size_of(type);
  1593. u32 align_in_bits = 8*cast(u32)type_align_of(type);
  1594. String name = type->Named.name;
  1595. char const *name_text = cast(char const *)name.text;
  1596. size_t name_len = cast(size_t)name.len;
  1597. unsigned tag = DW_TAG_structure_type;
  1598. if (is_type_raw_union(type) || is_type_union(type)) {
  1599. tag = DW_TAG_union_type;
  1600. }
  1601. LLVMDIFlags flags = LLVMDIFlagZero;
  1602. Type *bt = base_type(type->Named.base);
  1603. lbIncompleteDebugType idt = {};
  1604. idt.type = type;
  1605. switch (bt->kind) {
  1606. case Type_Enum:
  1607. {
  1608. LLVMMetadataRef scope = nullptr;
  1609. LLVMMetadataRef file = nullptr;
  1610. unsigned line = 0;
  1611. unsigned element_count = cast(unsigned)bt->Enum.fields.count;
  1612. LLVMMetadataRef *elements = gb_alloc_array(permanent_allocator(), LLVMMetadataRef, element_count);
  1613. Type *ct = base_enum_type(type);
  1614. LLVMBool is_unsigned = is_type_unsigned(ct);
  1615. for (unsigned i = 0; i < element_count; i++) {
  1616. Entity *f = bt->Enum.fields[i];
  1617. GB_ASSERT(f->kind == Entity_Constant);
  1618. String name = f->token.string;
  1619. i64 value = exact_value_to_i64(f->Constant.value);
  1620. elements[i] = LLVMDIBuilderCreateEnumerator(m->debug_builder, cast(char const *)name.text, cast(size_t)name.len, value, is_unsigned);
  1621. }
  1622. LLVMMetadataRef class_type = lb_debug_type(m, ct);
  1623. return LLVMDIBuilderCreateEnumerationType(m->debug_builder, scope, name_text, name_len, file, line, 8*type_size_of(type), 8*cast(unsigned)type_align_of(type), elements, element_count, class_type);
  1624. }
  1625. case Type_Basic:
  1626. case Type_Pointer:
  1627. case Type_Array:
  1628. case Type_EnumeratedArray:
  1629. case Type_Tuple:
  1630. case Type_Proc:
  1631. case Type_SimdVector:
  1632. case Type_RelativePointer:
  1633. case Type_RelativeSlice:
  1634. {
  1635. LLVMMetadataRef debug_bt = lb_debug_type(m, bt);
  1636. LLVMMetadataRef final_decl = LLVMDIBuilderCreateTypedef(m->debug_builder, debug_bt, name_text, name_len, file, line, scope, align_in_bits);
  1637. lb_set_llvm_metadata(m, type, final_decl);
  1638. return final_decl;
  1639. }
  1640. case Type_Slice:
  1641. case Type_DynamicArray:
  1642. case Type_Map:
  1643. case Type_Struct:
  1644. case Type_Union:
  1645. case Type_BitSet:
  1646. LLVMMetadataRef temp_forward_decl = LLVMDIBuilderCreateReplaceableCompositeType(
  1647. m->debug_builder, tag, name_text, name_len, nullptr, nullptr, 0, 0, size_in_bits, align_in_bits, flags, "", 0
  1648. );
  1649. idt.metadata = temp_forward_decl;
  1650. array_add(&m->debug_incomplete_types, idt);
  1651. lb_set_llvm_metadata(m, type, temp_forward_decl);
  1652. return temp_forward_decl;
  1653. }
  1654. }
  1655. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1656. lb_set_llvm_metadata(m, type, dt);
  1657. return dt;
  1658. }
  1659. void lb_debug_complete_types(lbModule *m) {
  1660. unsigned const word_size = cast(unsigned)build_context.word_size;
  1661. unsigned const word_bits = cast(unsigned)(8*build_context.word_size);
  1662. for_array(debug_incomplete_type_index, m->debug_incomplete_types) {
  1663. auto const &idt = m->debug_incomplete_types[debug_incomplete_type_index];
  1664. GB_ASSERT(idt.type != nullptr);
  1665. GB_ASSERT(idt.metadata != nullptr);
  1666. Type *t = idt.type;
  1667. Type *bt = base_type(t);
  1668. LLVMMetadataRef parent_scope = nullptr;
  1669. LLVMMetadataRef file = nullptr;
  1670. unsigned line_number = 0;
  1671. u64 size_in_bits = 8*type_size_of(t);
  1672. u32 align_in_bits = cast(u32)(8*type_align_of(t));
  1673. LLVMDIFlags flags = LLVMDIFlagZero;
  1674. LLVMMetadataRef derived_from = nullptr;
  1675. LLVMMetadataRef *elements = nullptr;
  1676. unsigned element_count = 0;
  1677. unsigned runtime_lang = 0; // Objective-C runtime version
  1678. char const *unique_id = "";
  1679. LLVMMetadataRef vtable_holder = nullptr;
  1680. size_t unique_id_len = 0;
  1681. LLVMMetadataRef record_scope = nullptr;
  1682. switch (bt->kind) {
  1683. case Type_Slice:
  1684. case Type_DynamicArray:
  1685. case Type_Map:
  1686. case Type_Struct:
  1687. case Type_Union:
  1688. case Type_BitSet: {
  1689. bool is_union = is_type_raw_union(bt) || is_type_union(bt);
  1690. String name = str_lit("<anonymous-struct>");
  1691. if (t->kind == Type_Named) {
  1692. name = t->Named.name;
  1693. if (t->Named.type_name && t->Named.type_name->pkg && t->Named.type_name->pkg->name.len != 0) {
  1694. name = concatenate3_strings(temporary_allocator(), t->Named.type_name->pkg->name, str_lit("."), t->Named.name);
  1695. }
  1696. LLVMMetadataRef file = nullptr;
  1697. unsigned line = 0;
  1698. LLVMMetadataRef file_scope = nullptr;
  1699. if (t->Named.type_name != nullptr) {
  1700. Entity *e = t->Named.type_name;
  1701. file_scope = lb_get_llvm_metadata(m, e->scope);
  1702. if (file_scope != nullptr) {
  1703. file = LLVMDIScopeGetFile(file_scope);
  1704. }
  1705. line = cast(unsigned)e->token.pos.line;
  1706. }
  1707. // TODO(bill): location data for Type_Named
  1708. } else {
  1709. name = make_string_c(type_to_string(t, temporary_allocator()));
  1710. }
  1711. switch (bt->kind) {
  1712. case Type_Slice:
  1713. element_count = 2;
  1714. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1715. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->Slice.elem), 0*word_bits);
  1716. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1717. break;
  1718. case Type_DynamicArray:
  1719. element_count = 4;
  1720. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1721. elements[0] = lb_debug_struct_field(m, str_lit("data"), alloc_type_pointer(bt->DynamicArray.elem), 0*word_bits);
  1722. elements[1] = lb_debug_struct_field(m, str_lit("len"), t_int, 1*word_bits);
  1723. elements[2] = lb_debug_struct_field(m, str_lit("cap"), t_int, 2*word_bits);
  1724. elements[3] = lb_debug_struct_field(m, str_lit("allocator"), t_allocator, 3*word_bits);
  1725. break;
  1726. case Type_Map:
  1727. bt = bt->Map.internal_type;
  1728. /*fallthrough*/
  1729. case Type_Struct:
  1730. if (file == nullptr) {
  1731. if (bt->Struct.node) {
  1732. file = lb_get_llvm_metadata(m, bt->Struct.node->file);
  1733. line_number = cast(unsigned)ast_token(bt->Struct.node).pos.line;
  1734. }
  1735. }
  1736. type_set_offsets(bt);
  1737. {
  1738. isize element_offset = 0;
  1739. record_scope = lb_get_llvm_metadata(m, bt->Struct.scope);
  1740. switch (bt->Struct.soa_kind) {
  1741. case StructSoa_Slice: element_offset = 1; break;
  1742. case StructSoa_Dynamic: element_offset = 3; break;
  1743. }
  1744. element_count = cast(unsigned)(bt->Struct.fields.count + element_offset);
  1745. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1746. switch (bt->Struct.soa_kind) {
  1747. case StructSoa_Slice:
  1748. elements[0] = LLVMDIBuilderCreateMemberType(
  1749. m->debug_builder, record_scope,
  1750. ".len", 4,
  1751. file, 0,
  1752. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1753. 8*type_size_of(bt)-word_bits,
  1754. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1755. );
  1756. break;
  1757. case StructSoa_Dynamic:
  1758. elements[0] = LLVMDIBuilderCreateMemberType(
  1759. m->debug_builder, record_scope,
  1760. ".len", 4,
  1761. file, 0,
  1762. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1763. 8*type_size_of(bt)-word_bits + 0*word_bits,
  1764. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1765. );
  1766. elements[1] = LLVMDIBuilderCreateMemberType(
  1767. m->debug_builder, record_scope,
  1768. ".cap", 4,
  1769. file, 0,
  1770. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1771. 8*type_size_of(bt)-word_bits + 1*word_bits,
  1772. LLVMDIFlagZero, lb_debug_type(m, t_int)
  1773. );
  1774. elements[3] = LLVMDIBuilderCreateMemberType(
  1775. m->debug_builder, record_scope,
  1776. ".allocator", 12,
  1777. file, 0,
  1778. 8*cast(u64)type_size_of(t_int), 8*cast(u32)type_align_of(t_int),
  1779. 8*type_size_of(bt)-word_bits + 2*word_bits,
  1780. LLVMDIFlagZero, lb_debug_type(m, t_allocator)
  1781. );
  1782. break;
  1783. }
  1784. for_array(j, bt->Struct.fields) {
  1785. Entity *f = bt->Struct.fields[j];
  1786. String fname = f->token.string;
  1787. unsigned field_line = 0;
  1788. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1789. u64 offset_in_bits = 8*cast(u64)bt->Struct.offsets[j];
  1790. elements[element_offset+j] = LLVMDIBuilderCreateMemberType(
  1791. m->debug_builder, record_scope,
  1792. cast(char const *)fname.text, cast(size_t)fname.len,
  1793. file, field_line,
  1794. 8*cast(u64)type_size_of(f->type), 8*cast(u32)type_align_of(f->type),
  1795. offset_in_bits,
  1796. field_flags, lb_debug_type(m, f->type)
  1797. );
  1798. }
  1799. }
  1800. break;
  1801. case Type_Union:
  1802. {
  1803. if (file == nullptr) {
  1804. GB_ASSERT(bt->Union.node != nullptr);
  1805. file = lb_get_llvm_metadata(m, bt->Union.node->file);
  1806. line_number = cast(unsigned)ast_token(bt->Union.node).pos.line;
  1807. }
  1808. isize index_offset = 1;
  1809. if (is_type_union_maybe_pointer(bt)) {
  1810. index_offset = 0;
  1811. }
  1812. record_scope = lb_get_llvm_metadata(m, bt->Union.scope);
  1813. element_count = cast(unsigned)bt->Union.variants.count;
  1814. if (index_offset > 0) {
  1815. element_count += 1;
  1816. }
  1817. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1818. if (index_offset > 0) {
  1819. Type *tag_type = union_tag_type(bt);
  1820. unsigned field_line = 0;
  1821. u64 offset_in_bits = 8*cast(u64)bt->Union.variant_block_size;
  1822. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1823. elements[0] = LLVMDIBuilderCreateMemberType(
  1824. m->debug_builder, record_scope,
  1825. "tag", 3,
  1826. file, field_line,
  1827. 8*cast(u64)type_size_of(tag_type), 8*cast(u32)type_align_of(tag_type),
  1828. offset_in_bits,
  1829. field_flags, lb_debug_type(m, tag_type)
  1830. );
  1831. }
  1832. for_array(j, bt->Union.variants) {
  1833. Type *variant = bt->Union.variants[j];
  1834. unsigned field_index = cast(unsigned)(index_offset+j);
  1835. char name[16] = {};
  1836. gb_snprintf(name, gb_size_of(name), "v%u", field_index);
  1837. isize name_len = gb_strlen(name);
  1838. unsigned field_line = 0;
  1839. LLVMDIFlags field_flags = LLVMDIFlagZero;
  1840. u64 offset_in_bits = 0;
  1841. elements[field_index] = LLVMDIBuilderCreateMemberType(
  1842. m->debug_builder, record_scope,
  1843. name, name_len,
  1844. file, field_line,
  1845. 8*cast(u64)type_size_of(variant), 8*cast(u32)type_align_of(variant),
  1846. offset_in_bits,
  1847. field_flags, lb_debug_type(m, variant)
  1848. );
  1849. }
  1850. }
  1851. break;
  1852. case Type_BitSet:
  1853. {
  1854. if (file == nullptr) {
  1855. GB_ASSERT(bt->BitSet.node != nullptr);
  1856. file = lb_get_llvm_metadata(m, bt->BitSet.node->file);
  1857. line_number = cast(unsigned)ast_token(bt->BitSet.node).pos.line;
  1858. }
  1859. LLVMMetadataRef bit_set_field_type = lb_debug_type(m, t_bool);
  1860. LLVMMetadataRef scope = file;
  1861. Type *elem = base_type(bt->BitSet.elem);
  1862. if (elem->kind == Type_Enum) {
  1863. element_count = cast(unsigned)elem->Enum.fields.count;
  1864. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1865. for_array(i, elem->Enum.fields) {
  1866. Entity *f = elem->Enum.fields[i];
  1867. GB_ASSERT(f->kind == Entity_Constant);
  1868. i64 val = exact_value_to_i64(f->Constant.value);
  1869. String name = f->token.string;
  1870. u64 offset_in_bits = cast(u64)(val - bt->BitSet.lower);
  1871. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1872. m->debug_builder,
  1873. scope,
  1874. cast(char const *)name.text, name.len,
  1875. file, line_number,
  1876. 1,
  1877. offset_in_bits,
  1878. 0,
  1879. LLVMDIFlagZero,
  1880. bit_set_field_type
  1881. );
  1882. }
  1883. } else {
  1884. char name[32] = {};
  1885. GB_ASSERT(is_type_integer(elem));
  1886. i64 count = bt->BitSet.upper - bt->BitSet.lower + 1;
  1887. GB_ASSERT(0 <= count);
  1888. element_count = cast(unsigned)count;
  1889. elements = gb_alloc_array(temporary_allocator(), LLVMMetadataRef, element_count);
  1890. for (unsigned i = 0; i < element_count; i++) {
  1891. u64 offset_in_bits = i;
  1892. i64 val = bt->BitSet.lower + cast(i64)i;
  1893. gb_snprintf(name, gb_count_of(name), "%lld", val);
  1894. elements[i] = LLVMDIBuilderCreateBitFieldMemberType(
  1895. m->debug_builder,
  1896. scope,
  1897. name, gb_strlen(name),
  1898. file, line_number,
  1899. 1,
  1900. offset_in_bits,
  1901. 0,
  1902. LLVMDIFlagZero,
  1903. bit_set_field_type
  1904. );
  1905. }
  1906. }
  1907. }
  1908. }
  1909. LLVMMetadataRef final_metadata = nullptr;
  1910. if (is_union) {
  1911. final_metadata = LLVMDIBuilderCreateUnionType(
  1912. m->debug_builder,
  1913. parent_scope,
  1914. cast(char const *)name.text, cast(size_t)name.len,
  1915. file, line_number,
  1916. size_in_bits, align_in_bits,
  1917. flags,
  1918. elements, element_count,
  1919. runtime_lang,
  1920. unique_id, unique_id_len
  1921. );
  1922. } else {
  1923. final_metadata = LLVMDIBuilderCreateStructType(
  1924. m->debug_builder,
  1925. parent_scope,
  1926. cast(char const *)name.text, cast(size_t)name.len,
  1927. file, line_number,
  1928. size_in_bits, align_in_bits,
  1929. flags,
  1930. derived_from,
  1931. elements, element_count,
  1932. runtime_lang,
  1933. vtable_holder,
  1934. unique_id, unique_id_len
  1935. );
  1936. }
  1937. LLVMMetadataReplaceAllUsesWith(idt.metadata, final_metadata);
  1938. lb_set_llvm_metadata(m, idt.type, final_metadata);
  1939. } break;
  1940. default:
  1941. GB_PANIC("invalid incomplete debug type");
  1942. break;
  1943. }
  1944. }
  1945. array_clear(&m->debug_incomplete_types);
  1946. }
  1947. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1948. if (e != nullptr) {
  1949. map_set(&m->values, hash_entity(e), val);
  1950. }
  1951. }
  1952. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1953. if (name.len > 0) {
  1954. string_map_set(&m->members, name, val);
  1955. }
  1956. }
  1957. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1958. string_map_set(&m->members, key, val);
  1959. }
  1960. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1961. if (p->entity != nullptr) {
  1962. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1963. }
  1964. string_map_set(&m->procedures, p->name, p);
  1965. }
  1966. LLVMValueRef llvm_const_cast(LLVMValueRef val, LLVMTypeRef dst) {
  1967. LLVMTypeRef src = LLVMTypeOf(val);
  1968. if (src == dst) {
  1969. return val;
  1970. }
  1971. if (LLVMIsNull(val)) {
  1972. return LLVMConstNull(dst);
  1973. }
  1974. GB_ASSERT(LLVMSizeOf(dst) == LLVMSizeOf(src));
  1975. LLVMTypeKind kind = LLVMGetTypeKind(dst);
  1976. switch (kind) {
  1977. case LLVMPointerTypeKind:
  1978. return LLVMConstPointerCast(val, dst);
  1979. case LLVMStructTypeKind:
  1980. return LLVMConstBitCast(val, dst);
  1981. default:
  1982. GB_PANIC("Unhandled const cast %s to %s", LLVMPrintTypeToString(src), LLVMPrintTypeToString(dst));
  1983. }
  1984. return val;
  1985. }
  1986. LLVMValueRef llvm_const_named_struct(LLVMTypeRef t, LLVMValueRef *values, isize value_count_) {
  1987. unsigned value_count = cast(unsigned)value_count_;
  1988. unsigned elem_count = LLVMCountStructElementTypes(t);
  1989. GB_ASSERT(value_count == elem_count);
  1990. for (unsigned i = 0; i < elem_count; i++) {
  1991. LLVMTypeRef elem_type = LLVMStructGetTypeAtIndex(t, i);
  1992. values[i] = llvm_const_cast(values[i], elem_type);
  1993. }
  1994. return LLVMConstNamedStruct(t, values, value_count);
  1995. }
  1996. LLVMValueRef llvm_const_array(LLVMTypeRef elem_type, LLVMValueRef *values, isize value_count_) {
  1997. unsigned value_count = cast(unsigned)value_count_;
  1998. for (unsigned i = 0; i < value_count; i++) {
  1999. values[i] = llvm_const_cast(values[i], elem_type);
  2000. }
  2001. return LLVMConstArray(elem_type, values, value_count);
  2002. }
  2003. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  2004. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  2005. LLVMValueRef values[2] = {
  2006. str_elem.value,
  2007. str_len.value,
  2008. };
  2009. lbValue res = {};
  2010. res.type = t_string;
  2011. res.value = llvm_const_named_struct(lb_type(p->module, t_string), values, gb_count_of(values));
  2012. return res;
  2013. } else {
  2014. lbAddr res = lb_add_local_generated(p, t_string, false);
  2015. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  2016. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  2017. return lb_addr_load(p, res);
  2018. }
  2019. }
  2020. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  2021. String s = make_string_c(name);
  2022. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  2023. // and the current LLVM C API does not expose this functionality yet.
  2024. // It is better to ignore the attributes for the time being
  2025. if (s == "byval") {
  2026. return nullptr;
  2027. } else if (s == "byref") {
  2028. return nullptr;
  2029. } else if (s == "preallocated") {
  2030. return nullptr;
  2031. } else if (s == "sret") {
  2032. return nullptr;
  2033. }
  2034. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  2035. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  2036. return LLVMCreateEnumAttribute(ctx, kind, value);
  2037. }
  2038. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  2039. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  2040. GB_ASSERT(attr != nullptr);
  2041. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  2042. }
  2043. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  2044. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  2045. }
  2046. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  2047. if (p->abi_function_type != nullptr) {
  2048. return;
  2049. }
  2050. auto hash = hash_type(p->type);
  2051. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  2052. if (ft_found == nullptr) {
  2053. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  2054. ft_found = map_get(&m->function_type_map, hash);
  2055. }
  2056. GB_ASSERT(ft_found != nullptr);
  2057. p->abi_function_type = *ft_found;
  2058. GB_ASSERT(p->abi_function_type != nullptr);
  2059. }
  2060. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  2061. GB_ASSERT(entity != nullptr);
  2062. String link_name = lb_get_entity_name(m, entity);
  2063. {
  2064. StringHashKey key = string_hash_string(link_name);
  2065. lbValue *found = string_map_get(&m->members, key);
  2066. if (found) {
  2067. lb_add_entity(m, entity, *found);
  2068. lbProcedure **p_found = string_map_get(&m->procedures, key);
  2069. GB_ASSERT(p_found != nullptr);
  2070. return *p_found;
  2071. }
  2072. }
  2073. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2074. p->module = m;
  2075. entity->code_gen_module = m;
  2076. entity->code_gen_procedure = p;
  2077. p->entity = entity;
  2078. p->name = link_name;
  2079. DeclInfo *decl = entity->decl_info;
  2080. ast_node(pl, ProcLit, decl->proc_lit);
  2081. Type *pt = base_type(entity->type);
  2082. GB_ASSERT(pt->kind == Type_Proc);
  2083. set_procedure_abi_types(entity->type);
  2084. p->type = entity->type;
  2085. p->type_expr = decl->type_expr;
  2086. p->body = pl->body;
  2087. p->tags = pt->Proc.tags;
  2088. p->inlining = ProcInlining_none;
  2089. p->is_foreign = entity->Procedure.is_foreign;
  2090. p->is_export = entity->Procedure.is_export;
  2091. p->is_entry_point = false;
  2092. gbAllocator a = heap_allocator();
  2093. p->children.allocator = a;
  2094. p->params.allocator = a;
  2095. p->defer_stmts.allocator = a;
  2096. p->blocks.allocator = a;
  2097. p->branch_blocks.allocator = a;
  2098. p->context_stack.allocator = a;
  2099. p->scope_stack.allocator = a;
  2100. if (p->is_foreign) {
  2101. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  2102. }
  2103. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2104. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2105. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2106. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2107. lb_ensure_abi_function_type(m, p);
  2108. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  2109. if (false) {
  2110. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2111. // TODO(bill): Clean up this logic
  2112. if (build_context.metrics.os != TargetOs_js) {
  2113. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2114. }
  2115. LLVMSetFunctionCallConv(p->value, cc_kind);
  2116. }
  2117. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2118. // // TODO(bill): Clean up this logic
  2119. // if (build_context.metrics.os != TargetOs_js) {
  2120. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2121. // }
  2122. // LLVMSetFunctionCallConv(p->value, cc_kind);
  2123. lbValue proc_value = {p->value, p->type};
  2124. lb_add_entity(m, entity, proc_value);
  2125. lb_add_member(m, p->name, proc_value);
  2126. lb_add_procedure_value(m, p);
  2127. if (p->is_export) {
  2128. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  2129. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  2130. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  2131. if (build_context.metrics.os == TargetOs_js) {
  2132. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  2133. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  2134. }
  2135. }
  2136. if (p->is_foreign) {
  2137. if (build_context.metrics.os == TargetOs_js) {
  2138. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  2139. char const *module_name = "env";
  2140. if (entity->Procedure.foreign_library != nullptr) {
  2141. Entity *foreign_library = entity->Procedure.foreign_library;
  2142. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  2143. if (foreign_library->LibraryName.paths.count > 0) {
  2144. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  2145. }
  2146. }
  2147. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  2148. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  2149. }
  2150. }
  2151. // NOTE(bill): offset==0 is the return value
  2152. isize offset = 1;
  2153. if (pt->Proc.return_by_pointer) {
  2154. offset = 2;
  2155. }
  2156. isize parameter_index = 0;
  2157. if (pt->Proc.param_count) {
  2158. TypeTuple *params = &pt->Proc.params->Tuple;
  2159. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2160. Entity *e = params->variables[i];
  2161. Type *original_type = e->type;
  2162. Type *abi_type = pt->Proc.abi_compat_params[i];
  2163. if (e->kind != Entity_Variable) continue;
  2164. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2165. continue;
  2166. }
  2167. if (is_type_tuple(abi_type)) {
  2168. for_array(j, abi_type->Tuple.variables) {
  2169. Type *tft = abi_type->Tuple.variables[j]->type;
  2170. if (e->flags&EntityFlag_NoAlias) {
  2171. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  2172. }
  2173. }
  2174. parameter_index += abi_type->Tuple.variables.count;
  2175. } else {
  2176. if (e->flags&EntityFlag_NoAlias) {
  2177. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2178. }
  2179. parameter_index += 1;
  2180. }
  2181. }
  2182. }
  2183. if (m->debug_builder) { // Debug Information
  2184. Type *bt = base_type(p->type);
  2185. unsigned line = cast(unsigned)entity->token.pos.line;
  2186. LLVMMetadataRef scope = nullptr;
  2187. LLVMMetadataRef file = nullptr;
  2188. LLVMMetadataRef type = nullptr;
  2189. scope = p->module->debug_compile_unit;
  2190. type = lb_debug_type_internal_proc(m, bt);
  2191. if (entity->file != nullptr) {
  2192. file = lb_get_llvm_metadata(m, entity->file);
  2193. scope = file;
  2194. } else if (entity->identifier != nullptr && entity->identifier->file != nullptr) {
  2195. file = lb_get_llvm_metadata(m, entity->identifier->file);
  2196. scope = file;
  2197. } else if (entity->scope != nullptr) {
  2198. file = lb_get_llvm_metadata(m, entity->scope->file);
  2199. scope = file;
  2200. }
  2201. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  2202. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  2203. LLVMBool is_local_to_unit = false;
  2204. LLVMBool is_definition = p->body != nullptr;
  2205. unsigned scope_line = line;
  2206. u32 flags = LLVMDIFlagStaticMember;
  2207. LLVMBool is_optimized = false;
  2208. if (bt->Proc.diverging) {
  2209. flags |= LLVMDIFlagNoReturn;
  2210. }
  2211. if (p->body == nullptr) {
  2212. flags |= LLVMDIFlagPrototyped;
  2213. is_optimized = false;
  2214. }
  2215. if (p->body != nullptr) {
  2216. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  2217. cast(char const *)entity->token.string.text, entity->token.string.len,
  2218. cast(char const *)p->name.text, p->name.len,
  2219. file, line, type,
  2220. is_local_to_unit, is_definition,
  2221. scope_line, cast(LLVMDIFlags)flags, is_optimized
  2222. );
  2223. GB_ASSERT(p->debug_info != nullptr);
  2224. LLVMSetSubprogram(p->value, p->debug_info);
  2225. lb_set_llvm_metadata(m, p, p->debug_info);
  2226. }
  2227. }
  2228. return p;
  2229. }
  2230. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  2231. {
  2232. lbValue *found = string_map_get(&m->members, link_name);
  2233. GB_ASSERT(found == nullptr);
  2234. }
  2235. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  2236. p->module = m;
  2237. p->name = link_name;
  2238. p->type = type;
  2239. p->type_expr = nullptr;
  2240. p->body = nullptr;
  2241. p->tags = 0;
  2242. p->inlining = ProcInlining_none;
  2243. p->is_foreign = false;
  2244. p->is_export = false;
  2245. p->is_entry_point = false;
  2246. gbAllocator a = permanent_allocator();
  2247. p->children.allocator = a;
  2248. p->params.allocator = a;
  2249. p->defer_stmts.allocator = a;
  2250. p->blocks.allocator = a;
  2251. p->branch_blocks.allocator = a;
  2252. p->context_stack.allocator = a;
  2253. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  2254. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  2255. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  2256. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  2257. Type *pt = p->type;
  2258. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  2259. // TODO(bill): Clean up this logic
  2260. if (build_context.metrics.os != TargetOs_js) {
  2261. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  2262. }
  2263. LLVMSetFunctionCallConv(p->value, cc_kind);
  2264. lbValue proc_value = {p->value, p->type};
  2265. lb_add_member(m, p->name, proc_value);
  2266. lb_add_procedure_value(m, p);
  2267. // NOTE(bill): offset==0 is the return value
  2268. isize offset = 1;
  2269. if (pt->Proc.return_by_pointer) {
  2270. lb_add_proc_attribute_at_index(p, 1, "sret");
  2271. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2272. offset = 2;
  2273. }
  2274. isize parameter_index = 0;
  2275. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2276. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2277. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2278. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2279. }
  2280. return p;
  2281. }
  2282. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2283. lbParamPasskind kind = lbParamPass_Value;
  2284. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2285. if (is_type_pointer(abi_type)) {
  2286. GB_ASSERT(e->kind == Entity_Variable);
  2287. Type *av = core_type(type_deref(abi_type));
  2288. if (are_types_identical(av, core_type(e->type))) {
  2289. kind = lbParamPass_Pointer;
  2290. if (e->flags&EntityFlag_Value) {
  2291. kind = lbParamPass_ConstRef;
  2292. }
  2293. } else {
  2294. kind = lbParamPass_BitCast;
  2295. }
  2296. } else if (is_type_integer(abi_type)) {
  2297. kind = lbParamPass_Integer;
  2298. } else if (abi_type == t_llvm_bool) {
  2299. kind = lbParamPass_Value;
  2300. } else if (is_type_boolean(abi_type)) {
  2301. kind = lbParamPass_Integer;
  2302. } else if (is_type_simd_vector(abi_type)) {
  2303. kind = lbParamPass_BitCast;
  2304. } else if (is_type_float(abi_type)) {
  2305. kind = lbParamPass_BitCast;
  2306. } else if (is_type_tuple(abi_type)) {
  2307. kind = lbParamPass_Tuple;
  2308. } else if (is_type_proc(abi_type)) {
  2309. kind = lbParamPass_Value;
  2310. } else {
  2311. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2312. }
  2313. }
  2314. if (kind_) *kind_ = kind;
  2315. lbValue res = {};
  2316. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2317. res.type = abi_type;
  2318. return res;
  2319. }
  2320. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2321. lbParamPasskind kind = lbParamPass_Value;
  2322. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2323. array_add(&p->params, v);
  2324. lbValue res = {};
  2325. switch (kind) {
  2326. case lbParamPass_Value: {
  2327. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2328. lbValue x = v;
  2329. if (abi_type == t_llvm_bool) {
  2330. x = lb_emit_conv(p, x, t_bool);
  2331. }
  2332. lb_addr_store(p, l, x);
  2333. return x;
  2334. }
  2335. case lbParamPass_Pointer:
  2336. lb_add_entity(p->module, e, v);
  2337. return lb_emit_load(p, v);
  2338. case lbParamPass_Integer: {
  2339. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2340. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2341. lb_emit_store(p, iptr, v);
  2342. return lb_addr_load(p, l);
  2343. }
  2344. case lbParamPass_ConstRef:
  2345. lb_add_entity(p->module, e, v);
  2346. return lb_emit_load(p, v);
  2347. case lbParamPass_BitCast: {
  2348. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2349. lbValue x = lb_emit_transmute(p, v, e->type);
  2350. lb_addr_store(p, l, x);
  2351. return x;
  2352. }
  2353. case lbParamPass_Tuple: {
  2354. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2355. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2356. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2357. if (abi_type->Tuple.variables.count > 0) {
  2358. array_pop(&p->params);
  2359. }
  2360. for_array(i, abi_type->Tuple.variables) {
  2361. Type *t = abi_type->Tuple.variables[i]->type;
  2362. GB_ASSERT(!is_type_tuple(t));
  2363. lbParamPasskind elem_kind = lbParamPass_Value;
  2364. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2365. array_add(&p->params, elem);
  2366. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2367. lb_emit_store(p, dst, elem);
  2368. }
  2369. return lb_addr_load(p, l);
  2370. }
  2371. }
  2372. GB_PANIC("Unreachable");
  2373. return {};
  2374. }
  2375. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2376. GB_ASSERT(b != nullptr);
  2377. if (!b->appended) {
  2378. b->appended = true;
  2379. LLVMAppendExistingBasicBlock(p->value, b->block);
  2380. }
  2381. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2382. p->curr_block = b;
  2383. }
  2384. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2385. LLVMContextRef ctx = p->module->ctx;
  2386. LLVMTypeRef src_type = LLVMTypeOf(val);
  2387. if (src_type == dst_type) {
  2388. return val;
  2389. }
  2390. i64 src_size = lb_sizeof(src_type);
  2391. i64 dst_size = lb_sizeof(dst_type);
  2392. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2393. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2394. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2395. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2396. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2397. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2398. }
  2399. if (src_size != dst_size && (lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2400. // Okay
  2401. } else {
  2402. GB_ASSERT_MSG(src_size == dst_size, "%s == %s", LLVMPrintTypeToString(src_type), LLVMPrintTypeToString(dst_type));
  2403. }
  2404. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2405. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2406. if (src_kind == dst_kind) {
  2407. if (src_kind == LLVMPointerTypeKind) {
  2408. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2409. } else if (src_kind == LLVMArrayTypeKind) {
  2410. // ignore
  2411. } else if (src_kind != LLVMStructTypeKind) {
  2412. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2413. }
  2414. } else {
  2415. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2416. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2417. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2418. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2419. }
  2420. }
  2421. if (LLVMIsALoadInst(val)) {
  2422. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2423. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2424. return LLVMBuildLoad(p->builder, val_ptr, "");
  2425. } else {
  2426. GB_ASSERT(p->decl_block != p->curr_block);
  2427. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2428. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2429. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2430. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2431. max_align = gb_max(max_align, 4);
  2432. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2433. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2434. LLVMBuildStore(p->builder, val, nptr);
  2435. return LLVMBuildLoad(p->builder, ptr, "");
  2436. }
  2437. }
  2438. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token) {
  2439. if (p->debug_info == nullptr) {
  2440. return;
  2441. }
  2442. if (type == nullptr) {
  2443. return;
  2444. }
  2445. if (type == t_invalid) {
  2446. return;
  2447. }
  2448. if (p->body == nullptr) {
  2449. return;
  2450. }
  2451. lbModule *m = p->module;
  2452. String const &name = token.string;
  2453. if (name == "" || name == "_") {
  2454. return;
  2455. }
  2456. if (lb_get_llvm_metadata(m, ptr) != nullptr) {
  2457. // Already been set
  2458. return;
  2459. }
  2460. AstFile *file = p->body->file;
  2461. LLVMMetadataRef llvm_scope = lb_get_current_debug_scope(p);
  2462. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, file);
  2463. GB_ASSERT(llvm_scope != nullptr);
  2464. if (llvm_file == nullptr) {
  2465. llvm_file = LLVMDIScopeGetFile(llvm_scope);
  2466. }
  2467. if (llvm_file == nullptr) {
  2468. return;
  2469. }
  2470. unsigned alignment_in_bits = cast(unsigned)(8*type_align_of(type));
  2471. LLVMDIFlags flags = LLVMDIFlagZero;
  2472. LLVMBool always_preserve = build_context.optimization_level == 0;
  2473. LLVMMetadataRef debug_type = lb_debug_type(m, type);
  2474. LLVMMetadataRef var_info = LLVMDIBuilderCreateAutoVariable(
  2475. m->debug_builder, llvm_scope,
  2476. cast(char const *)name.text, cast(size_t)name.len,
  2477. llvm_file, token.pos.line,
  2478. debug_type,
  2479. always_preserve, flags, alignment_in_bits
  2480. );
  2481. LLVMValueRef storage = ptr;
  2482. LLVMValueRef instr = ptr;
  2483. LLVMMetadataRef llvm_debug_loc = lb_debug_location_from_token_pos(p, token.pos);
  2484. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2485. lb_set_llvm_metadata(m, ptr, llvm_expr);
  2486. LLVMDIBuilderInsertDeclareBefore(m->debug_builder, storage, var_info, llvm_expr, llvm_debug_loc, instr);
  2487. }
  2488. void lb_add_debug_context_variable(lbProcedure *p, lbAddr const &ctx) {
  2489. if (!p->debug_info || !p->body) {
  2490. return;
  2491. }
  2492. LLVMMetadataRef loc = LLVMGetCurrentDebugLocation2(p->builder);
  2493. if (!loc) {
  2494. return;
  2495. }
  2496. TokenPos pos = {};
  2497. pos.file_id = p->body->file ? p->body->file->id : 0;
  2498. pos.line = LLVMDILocationGetLine(loc);
  2499. pos.column = LLVMDILocationGetColumn(loc);
  2500. Token token = {};
  2501. token.kind = Token_context;
  2502. token.string = str_lit("context");
  2503. token.pos = pos;
  2504. lb_add_debug_local_variable(p, ctx.addr.value, t_context, token);
  2505. }
  2506. void lb_begin_procedure_body(lbProcedure *p) {
  2507. DeclInfo *decl = decl_info_of_entity(p->entity);
  2508. if (decl != nullptr) {
  2509. for_array(i, decl->labels) {
  2510. BlockLabel bl = decl->labels[i];
  2511. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2512. array_add(&p->branch_blocks, bb);
  2513. }
  2514. }
  2515. if (p->tags != 0) {
  2516. u64 in = p->tags;
  2517. u64 out = p->module->state_flags;
  2518. if (in & ProcTag_bounds_check) {
  2519. out |= StateFlag_bounds_check;
  2520. out &= ~StateFlag_no_bounds_check;
  2521. } else if (in & ProcTag_no_bounds_check) {
  2522. out |= StateFlag_no_bounds_check;
  2523. out &= ~StateFlag_bounds_check;
  2524. }
  2525. p->module->state_flags = out;
  2526. }
  2527. p->builder = LLVMCreateBuilder();
  2528. p->decl_block = lb_create_block(p, "decls", true);
  2529. p->entry_block = lb_create_block(p, "entry", true);
  2530. lb_start_block(p, p->entry_block);
  2531. GB_ASSERT(p->type != nullptr);
  2532. lb_ensure_abi_function_type(p->module, p);
  2533. {
  2534. lbFunctionType *ft = p->abi_function_type;
  2535. unsigned param_offset = 0;
  2536. lbValue return_ptr_value = {};
  2537. if (ft->ret.kind == lbArg_Indirect) {
  2538. // NOTE(bill): this must be parameter 0
  2539. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2540. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2541. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2542. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2543. return_ptr_value.type = ptr_type;
  2544. p->return_ptr = lb_addr(return_ptr_value);
  2545. lb_add_entity(p->module, e, return_ptr_value);
  2546. param_offset += 1;
  2547. }
  2548. if (p->type->Proc.params != nullptr) {
  2549. TypeTuple *params = &p->type->Proc.params->Tuple;
  2550. unsigned param_index = 0;
  2551. for_array(i, params->variables) {
  2552. Entity *e = params->variables[i];
  2553. if (e->kind != Entity_Variable) {
  2554. continue;
  2555. }
  2556. lbArgType *arg_type = &ft->args[param_index];
  2557. if (arg_type->kind == lbArg_Ignore) {
  2558. continue;
  2559. } else if (arg_type->kind == lbArg_Direct) {
  2560. lbParamPasskind kind = lbParamPass_Value;
  2561. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2562. if (param_type != arg_type->type) {
  2563. kind = lbParamPass_BitCast;
  2564. }
  2565. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2566. value = OdinLLVMBuildTransmute(p, value, param_type);
  2567. lbValue param = {};
  2568. param.value = value;
  2569. param.type = e->type;
  2570. array_add(&p->params, param);
  2571. if (e->token.string.len != 0) {
  2572. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2573. lb_addr_store(p, l, param);
  2574. }
  2575. param_index += 1;
  2576. } else if (arg_type->kind == lbArg_Indirect) {
  2577. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2578. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2579. lbValue param = {};
  2580. param.value = value;
  2581. param.type = e->type;
  2582. array_add(&p->params, param);
  2583. lbValue ptr = {};
  2584. ptr.value = value_ptr;
  2585. ptr.type = alloc_type_pointer(e->type);
  2586. lb_add_entity(p->module, e, ptr);
  2587. param_index += 1;
  2588. }
  2589. }
  2590. }
  2591. if (p->type->Proc.has_named_results) {
  2592. GB_ASSERT(p->type->Proc.result_count > 0);
  2593. TypeTuple *results = &p->type->Proc.results->Tuple;
  2594. for_array(i, results->variables) {
  2595. Entity *e = results->variables[i];
  2596. GB_ASSERT(e->kind == Entity_Variable);
  2597. if (e->token.string != "") {
  2598. GB_ASSERT(!is_blank_ident(e->token));
  2599. lbAddr res = {};
  2600. if (return_ptr_value.value) {
  2601. lbValue ptr = return_ptr_value;
  2602. if (results->variables.count != 1) {
  2603. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2604. }
  2605. res = lb_addr(ptr);
  2606. lb_add_entity(p->module, e, ptr);
  2607. } else {
  2608. res = lb_add_local(p, e->type, e);
  2609. }
  2610. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2611. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2612. lb_addr_store(p, res, c);
  2613. }
  2614. }
  2615. }
  2616. }
  2617. }
  2618. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2619. lb_push_context_onto_stack_from_implicit_parameter(p);
  2620. }
  2621. lb_start_block(p, p->entry_block);
  2622. if (p->debug_info != nullptr) {
  2623. TokenPos pos = {};
  2624. if (p->body != nullptr) {
  2625. pos = ast_token(p->body).pos;
  2626. } else if (p->type_expr != nullptr) {
  2627. pos = ast_token(p->type_expr).pos;
  2628. } else if (p->entity != nullptr) {
  2629. pos = p->entity->token.pos;
  2630. }
  2631. if (pos.file_id != 0) {
  2632. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  2633. }
  2634. if (p->context_stack.count != 0) {
  2635. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  2636. }
  2637. }
  2638. }
  2639. void lb_end_procedure_body(lbProcedure *p) {
  2640. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2641. LLVMBuildBr(p->builder, p->entry_block->block);
  2642. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2643. // Make sure there is a "ret void" at the end of a procedure with no return type
  2644. if (p->type->Proc.result_count == 0) {
  2645. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2646. if (!lb_is_instr_terminating(instr)) {
  2647. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2648. LLVMBuildRetVoid(p->builder);
  2649. }
  2650. }
  2651. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  2652. LLVMBasicBlockRef block = nullptr;
  2653. // Make sure every block terminates, and if not, make it unreachable
  2654. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  2655. LLVMValueRef instr = LLVMGetLastInstruction(block);
  2656. if (instr == nullptr) {
  2657. LLVMPositionBuilderAtEnd(p->builder, block);
  2658. LLVMBuildUnreachable(p->builder);
  2659. }
  2660. }
  2661. p->curr_block = nullptr;
  2662. p->module->state_flags = 0;
  2663. }
  2664. void lb_end_procedure(lbProcedure *p) {
  2665. LLVMDisposeBuilder(p->builder);
  2666. }
  2667. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2668. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2669. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2670. array_add(&from->succs, to);
  2671. array_add(&to->preds, from);
  2672. }
  2673. }
  2674. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2675. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2676. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2677. b->appended = false;
  2678. if (append) {
  2679. b->appended = true;
  2680. LLVMAppendExistingBasicBlock(p->value, b->block);
  2681. }
  2682. b->scope = p->curr_scope;
  2683. b->scope_index = p->scope_index;
  2684. b->preds.allocator = heap_allocator();
  2685. b->succs.allocator = heap_allocator();
  2686. array_add(&p->blocks, b);
  2687. return b;
  2688. }
  2689. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2690. if (p->curr_block == nullptr) {
  2691. return;
  2692. }
  2693. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2694. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2695. return;
  2696. }
  2697. lb_add_edge(p->curr_block, target_block);
  2698. LLVMBuildBr(p->builder, target_block->block);
  2699. p->curr_block = nullptr;
  2700. }
  2701. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2702. lbBlock *b = p->curr_block;
  2703. if (b == nullptr) {
  2704. return;
  2705. }
  2706. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2707. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2708. return;
  2709. }
  2710. lb_add_edge(b, true_block);
  2711. lb_add_edge(b, false_block);
  2712. LLVMValueRef cv = cond.value;
  2713. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2714. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2715. }
  2716. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2717. GB_ASSERT(cond != nullptr);
  2718. GB_ASSERT(true_block != nullptr);
  2719. GB_ASSERT(false_block != nullptr);
  2720. switch (cond->kind) {
  2721. case_ast_node(pe, ParenExpr, cond);
  2722. return lb_build_cond(p, pe->expr, true_block, false_block);
  2723. case_end;
  2724. case_ast_node(ue, UnaryExpr, cond);
  2725. if (ue->op.kind == Token_Not) {
  2726. return lb_build_cond(p, ue->expr, false_block, true_block);
  2727. }
  2728. case_end;
  2729. case_ast_node(be, BinaryExpr, cond);
  2730. if (be->op.kind == Token_CmpAnd) {
  2731. lbBlock *block = lb_create_block(p, "cmp.and");
  2732. lb_build_cond(p, be->left, block, false_block);
  2733. lb_start_block(p, block);
  2734. return lb_build_cond(p, be->right, true_block, false_block);
  2735. } else if (be->op.kind == Token_CmpOr) {
  2736. lbBlock *block = lb_create_block(p, "cmp.or");
  2737. lb_build_cond(p, be->left, true_block, block);
  2738. lb_start_block(p, block);
  2739. return lb_build_cond(p, be->right, true_block, false_block);
  2740. }
  2741. case_end;
  2742. }
  2743. lbValue v = lb_build_expr(p, cond);
  2744. // v = lb_emit_conv(p, v, t_bool);
  2745. v = lb_emit_conv(p, v, t_llvm_bool);
  2746. lb_emit_if(p, v, true_block, false_block);
  2747. return v;
  2748. }
  2749. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2750. GB_ASSERT(p->decl_block != p->curr_block);
  2751. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2752. char const *name = "";
  2753. if (e != nullptr) {
  2754. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2755. }
  2756. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2757. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2758. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2759. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2760. LLVMSetAlignment(ptr, alignment);
  2761. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2762. if (zero_init) {
  2763. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2764. switch (kind) {
  2765. case LLVMStructTypeKind:
  2766. case LLVMArrayTypeKind:
  2767. {
  2768. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2769. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2770. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2771. i32 sz = cast(i32)type_size_of(type);
  2772. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2773. }
  2774. break;
  2775. default:
  2776. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2777. break;
  2778. }
  2779. }
  2780. lbValue val = {};
  2781. val.value = ptr;
  2782. val.type = alloc_type_pointer(type);
  2783. if (e != nullptr) {
  2784. lb_add_entity(p->module, e, val);
  2785. lb_add_debug_local_variable(p, ptr, type, e->token);
  2786. }
  2787. return lb_addr(val);
  2788. }
  2789. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2790. return lb_add_local(p, type, nullptr, zero_init);
  2791. }
  2792. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2793. GB_ASSERT(pd->body != nullptr);
  2794. lbModule *m = p->module;
  2795. auto *min_dep_set = &m->info->minimum_dependency_set;
  2796. if (ptr_set_exists(min_dep_set, e) == false) {
  2797. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2798. return;
  2799. }
  2800. // NOTE(bill): Generate a new name
  2801. // parent.name-guid
  2802. String original_name = e->token.string;
  2803. String pd_name = original_name;
  2804. if (e->Procedure.link_name.len > 0) {
  2805. pd_name = e->Procedure.link_name;
  2806. }
  2807. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2808. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2809. i32 guid = cast(i32)p->children.count;
  2810. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2811. String name = make_string(cast(u8 *)name_text, name_len-1);
  2812. set_procedure_abi_types(e->type);
  2813. e->Procedure.link_name = name;
  2814. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2815. e->code_gen_procedure = nested_proc;
  2816. lbValue value = {};
  2817. value.value = nested_proc->value;
  2818. value.type = nested_proc->type;
  2819. lb_add_entity(m, e, value);
  2820. array_add(&p->children, nested_proc);
  2821. array_add(&m->procedures_to_generate, nested_proc);
  2822. }
  2823. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2824. if (e == nullptr) {
  2825. return;
  2826. }
  2827. GB_ASSERT(e->kind == Entity_LibraryName);
  2828. GB_ASSERT(e->flags & EntityFlag_Used);
  2829. for_array(i, e->LibraryName.paths) {
  2830. String library_path = e->LibraryName.paths[i];
  2831. if (library_path.len == 0) {
  2832. continue;
  2833. }
  2834. bool ok = true;
  2835. for_array(path_index, m->foreign_library_paths) {
  2836. String path = m->foreign_library_paths[path_index];
  2837. #if defined(GB_SYSTEM_WINDOWS)
  2838. if (str_eq_ignore_case(path, library_path)) {
  2839. #else
  2840. if (str_eq(path, library_path)) {
  2841. #endif
  2842. ok = false;
  2843. break;
  2844. }
  2845. }
  2846. if (ok) {
  2847. array_add(&m->foreign_library_paths, library_path);
  2848. }
  2849. }
  2850. }
  2851. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2852. if (vd == nullptr || vd->is_mutable) {
  2853. return;
  2854. }
  2855. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2856. static i32 global_guid = 0;
  2857. for_array(i, vd->names) {
  2858. Ast *ident = vd->names[i];
  2859. GB_ASSERT(ident->kind == Ast_Ident);
  2860. Entity *e = entity_of_node(ident);
  2861. GB_ASSERT(e != nullptr);
  2862. if (e->kind != Entity_TypeName) {
  2863. continue;
  2864. }
  2865. bool polymorphic_struct = false;
  2866. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2867. Type *bt = base_type(e->type);
  2868. if (bt->kind == Type_Struct) {
  2869. polymorphic_struct = bt->Struct.is_polymorphic;
  2870. }
  2871. }
  2872. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2873. continue;
  2874. }
  2875. if (e->TypeName.ir_mangled_name.len != 0) {
  2876. // NOTE(bill): Already set
  2877. continue;
  2878. }
  2879. lb_set_nested_type_name_ir_mangled_name(e, p);
  2880. }
  2881. for_array(i, vd->names) {
  2882. Ast *ident = vd->names[i];
  2883. GB_ASSERT(ident->kind == Ast_Ident);
  2884. Entity *e = entity_of_node(ident);
  2885. GB_ASSERT(e != nullptr);
  2886. if (e->kind != Entity_Procedure) {
  2887. continue;
  2888. }
  2889. CheckerInfo *info = p->module->info;
  2890. DeclInfo *decl = decl_info_of_entity(e);
  2891. ast_node(pl, ProcLit, decl->proc_lit);
  2892. if (pl->body != nullptr) {
  2893. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2894. if (found) {
  2895. auto procs = *found;
  2896. for_array(i, procs) {
  2897. Entity *e = procs[i];
  2898. if (!ptr_set_exists(min_dep_set, e)) {
  2899. continue;
  2900. }
  2901. DeclInfo *d = decl_info_of_entity(e);
  2902. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2903. }
  2904. } else {
  2905. lb_build_nested_proc(p, pl, e);
  2906. }
  2907. } else {
  2908. // FFI - Foreign function interace
  2909. String original_name = e->token.string;
  2910. String name = original_name;
  2911. if (e->Procedure.is_foreign) {
  2912. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2913. }
  2914. if (e->Procedure.link_name.len > 0) {
  2915. name = e->Procedure.link_name;
  2916. }
  2917. lbValue *prev_value = string_map_get(&p->module->members, name);
  2918. if (prev_value != nullptr) {
  2919. // NOTE(bill): Don't do mutliple declarations in the IR
  2920. return;
  2921. }
  2922. set_procedure_abi_types(e->type);
  2923. e->Procedure.link_name = name;
  2924. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2925. lbValue value = {};
  2926. value.value = nested_proc->value;
  2927. value.type = nested_proc->type;
  2928. array_add(&p->module->procedures_to_generate, nested_proc);
  2929. if (p != nullptr) {
  2930. array_add(&p->children, nested_proc);
  2931. } else {
  2932. string_map_set(&p->module->members, name, value);
  2933. }
  2934. }
  2935. }
  2936. }
  2937. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  2938. for_array(i, stmts) {
  2939. Ast *stmt = stmts[i];
  2940. switch (stmt->kind) {
  2941. case_ast_node(vd, ValueDecl, stmt);
  2942. lb_build_constant_value_decl(p, vd);
  2943. case_end;
  2944. case_ast_node(fb, ForeignBlockDecl, stmt);
  2945. ast_node(block, BlockStmt, fb->body);
  2946. lb_build_stmt_list(p, block->stmts);
  2947. case_end;
  2948. }
  2949. }
  2950. for_array(i, stmts) {
  2951. lb_build_stmt(p, stmts[i]);
  2952. }
  2953. }
  2954. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2955. GB_ASSERT(ident->kind == Ast_Ident);
  2956. Entity *e = entity_of_node(ident);
  2957. GB_ASSERT(e->kind == Entity_Label);
  2958. for_array(i, p->branch_blocks) {
  2959. lbBranchBlocks *b = &p->branch_blocks[i];
  2960. if (b->label == e->Label.node) {
  2961. return *b;
  2962. }
  2963. }
  2964. GB_PANIC("Unreachable");
  2965. lbBranchBlocks empty = {};
  2966. return empty;
  2967. }
  2968. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2969. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  2970. tl->prev = p->target_list;
  2971. tl->break_ = break_;
  2972. tl->continue_ = continue_;
  2973. tl->fallthrough_ = fallthrough_;
  2974. p->target_list = tl;
  2975. if (label != nullptr) { // Set label blocks
  2976. GB_ASSERT(label->kind == Ast_Label);
  2977. for_array(i, p->branch_blocks) {
  2978. lbBranchBlocks *b = &p->branch_blocks[i];
  2979. GB_ASSERT(b->label != nullptr && label != nullptr);
  2980. GB_ASSERT(b->label->kind == Ast_Label);
  2981. if (b->label == label) {
  2982. b->break_ = break_;
  2983. b->continue_ = continue_;
  2984. return tl;
  2985. }
  2986. }
  2987. GB_PANIC("Unreachable");
  2988. }
  2989. return tl;
  2990. }
  2991. void lb_pop_target_list(lbProcedure *p) {
  2992. p->target_list = p->target_list->prev;
  2993. }
  2994. void lb_open_scope(lbProcedure *p, Scope *s) {
  2995. lbModule *m = p->module;
  2996. if (m->debug_builder) {
  2997. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  2998. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  2999. Token token = ast_token(s->node);
  3000. unsigned line = cast(unsigned)token.pos.line;
  3001. unsigned column = cast(unsigned)token.pos.column;
  3002. LLVMMetadataRef file = nullptr;
  3003. if (s->node->file != nullptr) {
  3004. file = lb_get_llvm_metadata(m, s->node->file);
  3005. }
  3006. LLVMMetadataRef scope = nullptr;
  3007. if (p->scope_stack.count > 0) {
  3008. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  3009. }
  3010. if (scope == nullptr) {
  3011. scope = lb_get_llvm_metadata(m, p);
  3012. }
  3013. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  3014. if (m->debug_builder) {
  3015. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  3016. file, line, column
  3017. );
  3018. lb_set_llvm_metadata(m, s, res);
  3019. }
  3020. }
  3021. }
  3022. p->scope_index += 1;
  3023. array_add(&p->scope_stack, s);
  3024. }
  3025. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  3026. lb_emit_defer_stmts(p, kind, block);
  3027. GB_ASSERT(p->scope_index > 0);
  3028. // NOTE(bill): Remove `context`s made in that scope
  3029. while (p->context_stack.count > 0) {
  3030. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  3031. if (ctx->scope_index >= p->scope_index) {
  3032. array_pop(&p->context_stack);
  3033. } else {
  3034. break;
  3035. }
  3036. }
  3037. p->scope_index -= 1;
  3038. array_pop(&p->scope_stack);
  3039. }
  3040. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  3041. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  3042. GB_ASSERT(is_type_boolean(tv.type));
  3043. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  3044. if (tv.value.value_bool) {
  3045. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  3046. } else if (ws->else_stmt) {
  3047. switch (ws->else_stmt->kind) {
  3048. case Ast_BlockStmt:
  3049. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  3050. break;
  3051. case Ast_WhenStmt:
  3052. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  3053. break;
  3054. default:
  3055. GB_PANIC("Invalid 'else' statement in 'when' statement");
  3056. break;
  3057. }
  3058. }
  3059. }
  3060. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  3061. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3062. lbModule *m = p->module;
  3063. lbValue count = {};
  3064. Type *expr_type = base_type(type_deref(expr.type));
  3065. switch (expr_type->kind) {
  3066. case Type_Array:
  3067. count = lb_const_int(m, t_int, expr_type->Array.count);
  3068. break;
  3069. }
  3070. lbValue val = {};
  3071. lbValue idx = {};
  3072. lbBlock *loop = nullptr;
  3073. lbBlock *done = nullptr;
  3074. lbBlock *body = nullptr;
  3075. lbAddr index = lb_add_local_generated(p, t_int, false);
  3076. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  3077. loop = lb_create_block(p, "for.index.loop");
  3078. lb_emit_jump(p, loop);
  3079. lb_start_block(p, loop);
  3080. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  3081. lb_addr_store(p, index, incr);
  3082. body = lb_create_block(p, "for.index.body");
  3083. done = lb_create_block(p, "for.index.done");
  3084. if (count.value == nullptr) {
  3085. GB_ASSERT(count_ptr.value != nullptr);
  3086. count = lb_emit_load(p, count_ptr);
  3087. }
  3088. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3089. lb_emit_if(p, cond, body, done);
  3090. lb_start_block(p, body);
  3091. idx = lb_addr_load(p, index);
  3092. switch (expr_type->kind) {
  3093. case Type_Array: {
  3094. if (val_type != nullptr) {
  3095. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3096. }
  3097. break;
  3098. }
  3099. case Type_EnumeratedArray: {
  3100. if (val_type != nullptr) {
  3101. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  3102. // NOTE(bill): Override the idx value for the enumeration
  3103. Type *index_type = expr_type->EnumeratedArray.index;
  3104. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  3105. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  3106. }
  3107. }
  3108. break;
  3109. }
  3110. case Type_Slice: {
  3111. if (val_type != nullptr) {
  3112. lbValue elem = lb_slice_elem(p, expr);
  3113. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3114. }
  3115. break;
  3116. }
  3117. case Type_DynamicArray: {
  3118. if (val_type != nullptr) {
  3119. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  3120. elem = lb_emit_load(p, elem);
  3121. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  3122. }
  3123. break;
  3124. }
  3125. case Type_Map: {
  3126. lbValue entries = lb_map_entries_ptr(p, expr);
  3127. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  3128. elem = lb_emit_load(p, elem);
  3129. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  3130. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  3131. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  3132. break;
  3133. }
  3134. case Type_Struct: {
  3135. GB_ASSERT(is_type_soa_struct(expr_type));
  3136. break;
  3137. }
  3138. default:
  3139. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  3140. break;
  3141. }
  3142. if (val_) *val_ = val;
  3143. if (idx_) *idx_ = idx;
  3144. if (loop_) *loop_ = loop;
  3145. if (done_) *done_ = done;
  3146. }
  3147. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  3148. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3149. lbModule *m = p->module;
  3150. lbValue count = lb_const_int(m, t_int, 0);
  3151. Type *expr_type = base_type(expr.type);
  3152. switch (expr_type->kind) {
  3153. case Type_Basic:
  3154. count = lb_string_len(p, expr);
  3155. break;
  3156. default:
  3157. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  3158. break;
  3159. }
  3160. lbValue val = {};
  3161. lbValue idx = {};
  3162. lbBlock *loop = nullptr;
  3163. lbBlock *done = nullptr;
  3164. lbBlock *body = nullptr;
  3165. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3166. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3167. loop = lb_create_block(p, "for.string.loop");
  3168. lb_emit_jump(p, loop);
  3169. lb_start_block(p, loop);
  3170. body = lb_create_block(p, "for.string.body");
  3171. done = lb_create_block(p, "for.string.done");
  3172. lbValue offset = lb_addr_load(p, offset_);
  3173. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  3174. lb_emit_if(p, cond, body, done);
  3175. lb_start_block(p, body);
  3176. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  3177. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  3178. auto args = array_make<lbValue>(permanent_allocator(), 1);
  3179. args[0] = lb_emit_string(p, str_elem, str_len);
  3180. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  3181. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  3182. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  3183. idx = offset;
  3184. if (val_type != nullptr) {
  3185. val = lb_emit_struct_ev(p, rune_and_len, 0);
  3186. }
  3187. if (val_) *val_ = val;
  3188. if (idx_) *idx_ = idx;
  3189. if (loop_) *loop_ = loop;
  3190. if (done_) *done_ = done;
  3191. }
  3192. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  3193. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3194. lbModule *m = p->module;
  3195. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  3196. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  3197. lbValue lower = lb_build_expr(p, node->left);
  3198. lbValue upper = {};
  3199. lbValue val = {};
  3200. lbValue idx = {};
  3201. lbBlock *loop = nullptr;
  3202. lbBlock *done = nullptr;
  3203. lbBlock *body = nullptr;
  3204. if (val_type == nullptr) {
  3205. val_type = lower.type;
  3206. }
  3207. lbAddr value = lb_add_local_generated(p, val_type, false);
  3208. lb_addr_store(p, value, lower);
  3209. lbAddr index = lb_add_local_generated(p, t_int, false);
  3210. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  3211. loop = lb_create_block(p, "for.interval.loop");
  3212. lb_emit_jump(p, loop);
  3213. lb_start_block(p, loop);
  3214. body = lb_create_block(p, "for.interval.body");
  3215. done = lb_create_block(p, "for.interval.done");
  3216. TokenKind op = Token_Lt;
  3217. switch (node->op.kind) {
  3218. case Token_Ellipsis: op = Token_LtEq; break;
  3219. case Token_RangeHalf: op = Token_Lt; break;
  3220. default: GB_PANIC("Invalid interval operator"); break;
  3221. }
  3222. upper = lb_build_expr(p, node->right);
  3223. lbValue curr_value = lb_addr_load(p, value);
  3224. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  3225. lb_emit_if(p, cond, body, done);
  3226. lb_start_block(p, body);
  3227. val = lb_addr_load(p, value);
  3228. idx = lb_addr_load(p, index);
  3229. lb_emit_increment(p, value.addr);
  3230. lb_emit_increment(p, index.addr);
  3231. if (val_) *val_ = val;
  3232. if (idx_) *idx_ = idx;
  3233. if (loop_) *loop_ = loop;
  3234. if (done_) *done_ = done;
  3235. }
  3236. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  3237. lbModule *m = p->module;
  3238. Type *t = enum_type;
  3239. GB_ASSERT(is_type_enum(t));
  3240. Type *enum_ptr = alloc_type_pointer(t);
  3241. t = base_type(t);
  3242. Type *core_elem = core_type(t);
  3243. GB_ASSERT(t->kind == Type_Enum);
  3244. i64 enum_count = t->Enum.fields.count;
  3245. lbValue max_count = lb_const_int(m, t_int, enum_count);
  3246. lbValue ti = lb_type_info(m, t);
  3247. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  3248. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  3249. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  3250. lbValue values_data = lb_slice_elem(p, values);
  3251. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  3252. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  3253. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  3254. lb_emit_jump(p, loop);
  3255. lb_start_block(p, loop);
  3256. lbBlock *body = lb_create_block(p, "for.enum.body");
  3257. lbBlock *done = lb_create_block(p, "for.enum.done");
  3258. lbValue offset = lb_addr_load(p, offset_);
  3259. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  3260. lb_emit_if(p, cond, body, done);
  3261. lb_start_block(p, body);
  3262. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  3263. lb_emit_increment(p, offset_.addr);
  3264. lbValue val = {};
  3265. if (val_type != nullptr) {
  3266. GB_ASSERT(are_types_identical(enum_type, val_type));
  3267. if (is_type_integer(core_elem)) {
  3268. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  3269. val = lb_emit_conv(p, i, t);
  3270. } else {
  3271. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  3272. }
  3273. }
  3274. if (val_) *val_ = val;
  3275. if (idx_) *idx_ = offset;
  3276. if (loop_) *loop_ = loop;
  3277. if (done_) *done_ = done;
  3278. }
  3279. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  3280. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  3281. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  3282. lb_emit_jump(p, loop);
  3283. lb_start_block(p, loop);
  3284. lbBlock *body = lb_create_block(p, "for.tuple.body");
  3285. lbBlock *done = lb_create_block(p, "for.tuple.done");
  3286. lbValue tuple_value = lb_build_expr(p, expr);
  3287. Type *tuple = tuple_value.type;
  3288. GB_ASSERT(tuple->kind == Type_Tuple);
  3289. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  3290. i32 cond_index = tuple_count-1;
  3291. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  3292. lb_emit_if(p, cond, body, done);
  3293. lb_start_block(p, body);
  3294. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  3295. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  3296. if (loop_) *loop_ = loop;
  3297. if (done_) *done_ = done;
  3298. }
  3299. void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3300. Ast *expr = unparen_expr(rs->expr);
  3301. TypeAndValue tav = type_and_value_of_expr(expr);
  3302. lbBlock *loop = nullptr;
  3303. lbBlock *body = nullptr;
  3304. lbBlock *done = nullptr;
  3305. lb_open_scope(p, scope);
  3306. Type *val_types[2] = {};
  3307. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3308. val_types[0] = type_of_expr(rs->vals[0]);
  3309. }
  3310. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3311. val_types[1] = type_of_expr(rs->vals[1]);
  3312. }
  3313. lbAddr array = lb_build_addr(p, expr);
  3314. if (is_type_pointer(type_deref(lb_addr_type(array)))) {
  3315. array = lb_addr(lb_addr_load(p, array));
  3316. }
  3317. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  3318. lbAddr index = lb_add_local_generated(p, t_int, false);
  3319. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  3320. loop = lb_create_block(p, "for.soa.loop");
  3321. lb_emit_jump(p, loop);
  3322. lb_start_block(p, loop);
  3323. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  3324. lb_addr_store(p, index, incr);
  3325. body = lb_create_block(p, "for.soa.body");
  3326. done = lb_create_block(p, "for.soa.done");
  3327. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  3328. lb_emit_if(p, cond, body, done);
  3329. lb_start_block(p, body);
  3330. if (val_types[0]) {
  3331. Entity *e = entity_of_node(rs->vals[0]);
  3332. if (e != nullptr) {
  3333. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  3334. map_set(&p->module->soa_values, hash_entity(e), soa_val);
  3335. }
  3336. }
  3337. if (val_types[1]) {
  3338. lb_store_range_stmt_val(p, rs->vals[1], lb_addr_load(p, index));
  3339. }
  3340. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3341. lb_build_stmt(p, rs->body);
  3342. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3343. lb_pop_target_list(p);
  3344. lb_emit_jump(p, loop);
  3345. lb_start_block(p, done);
  3346. }
  3347. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  3348. Ast *expr = unparen_expr(rs->expr);
  3349. Type *expr_type = type_of_expr(expr);
  3350. if (expr_type != nullptr) {
  3351. Type *et = base_type(type_deref(expr_type));
  3352. if (is_type_soa_struct(et)) {
  3353. lb_build_range_stmt_struct_soa(p, rs, scope);
  3354. return;
  3355. }
  3356. }
  3357. lb_open_scope(p, scope);
  3358. Type *val0_type = nullptr;
  3359. Type *val1_type = nullptr;
  3360. if (rs->vals.count > 0 && rs->vals[0] != nullptr && !is_blank_ident(rs->vals[0])) {
  3361. val0_type = type_of_expr(rs->vals[0]);
  3362. }
  3363. if (rs->vals.count > 1 && rs->vals[1] != nullptr && !is_blank_ident(rs->vals[1])) {
  3364. val1_type = type_of_expr(rs->vals[1]);
  3365. }
  3366. if (val0_type != nullptr) {
  3367. Entity *e = entity_of_node(rs->vals[0]);
  3368. lb_add_local(p, e->type, e, true);
  3369. }
  3370. if (val1_type != nullptr) {
  3371. Entity *e = entity_of_node(rs->vals[1]);
  3372. lb_add_local(p, e->type, e, true);
  3373. }
  3374. lbValue val = {};
  3375. lbValue key = {};
  3376. lbBlock *loop = nullptr;
  3377. lbBlock *done = nullptr;
  3378. bool is_map = false;
  3379. TypeAndValue tav = type_and_value_of_expr(expr);
  3380. if (is_ast_range(expr)) {
  3381. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  3382. } else if (tav.mode == Addressing_Type) {
  3383. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3384. } else {
  3385. Type *expr_type = type_of_expr(expr);
  3386. Type *et = base_type(type_deref(expr_type));
  3387. switch (et->kind) {
  3388. case Type_Map: {
  3389. is_map = true;
  3390. lbValue map = lb_build_addr_ptr(p, expr);
  3391. if (is_type_pointer(type_deref(map.type))) {
  3392. map = lb_emit_load(p, map);
  3393. }
  3394. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3395. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3396. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3397. break;
  3398. }
  3399. case Type_Array: {
  3400. lbValue array = lb_build_addr_ptr(p, expr);
  3401. if (is_type_pointer(type_deref(array.type))) {
  3402. array = lb_emit_load(p, array);
  3403. }
  3404. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3405. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3406. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3407. break;
  3408. }
  3409. case Type_EnumeratedArray: {
  3410. lbValue array = lb_build_addr_ptr(p, expr);
  3411. if (is_type_pointer(type_deref(array.type))) {
  3412. array = lb_emit_load(p, array);
  3413. }
  3414. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3415. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3416. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3417. break;
  3418. }
  3419. case Type_DynamicArray: {
  3420. lbValue count_ptr = {};
  3421. lbValue array = lb_build_addr_ptr(p, expr);
  3422. if (is_type_pointer(type_deref(array.type))) {
  3423. array = lb_emit_load(p, array);
  3424. }
  3425. count_ptr = lb_emit_struct_ep(p, array, 1);
  3426. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3427. break;
  3428. }
  3429. case Type_Slice: {
  3430. lbValue count_ptr = {};
  3431. lbValue slice = lb_build_expr(p, expr);
  3432. if (is_type_pointer(slice.type)) {
  3433. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3434. slice = lb_emit_load(p, slice);
  3435. } else {
  3436. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3437. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3438. }
  3439. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3440. break;
  3441. }
  3442. case Type_Basic: {
  3443. lbValue string = lb_build_expr(p, expr);
  3444. if (is_type_pointer(string.type)) {
  3445. string = lb_emit_load(p, string);
  3446. }
  3447. if (is_type_untyped(expr_type)) {
  3448. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3449. lb_addr_store(p, s, string);
  3450. string = lb_addr_load(p, s);
  3451. }
  3452. Type *t = base_type(string.type);
  3453. GB_ASSERT(!is_type_cstring(t));
  3454. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3455. break;
  3456. }
  3457. case Type_Tuple:
  3458. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3459. break;
  3460. default:
  3461. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3462. break;
  3463. }
  3464. }
  3465. if (is_map) {
  3466. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], key);
  3467. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], val);
  3468. } else {
  3469. if (val0_type) lb_store_range_stmt_val(p, rs->vals[0], val);
  3470. if (val1_type) lb_store_range_stmt_val(p, rs->vals[1], key);
  3471. }
  3472. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3473. lb_build_stmt(p, rs->body);
  3474. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3475. lb_pop_target_list(p);
  3476. lb_emit_jump(p, loop);
  3477. lb_start_block(p, done);
  3478. }
  3479. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs, Scope *scope) {
  3480. lbModule *m = p->module;
  3481. lb_open_scope(p, scope); // Open scope here
  3482. Type *val0_type = nullptr;
  3483. Type *val1_type = nullptr;
  3484. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3485. val0_type = type_of_expr(rs->val0);
  3486. }
  3487. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3488. val1_type = type_of_expr(rs->val1);
  3489. }
  3490. if (val0_type != nullptr) {
  3491. Entity *e = entity_of_node(rs->val0);
  3492. lb_add_local(p, e->type, e, true);
  3493. }
  3494. if (val1_type != nullptr) {
  3495. Entity *e = entity_of_node(rs->val1);
  3496. lb_add_local(p, e->type, e, true);
  3497. }
  3498. lbValue val = {};
  3499. lbValue key = {};
  3500. lbBlock *loop = nullptr;
  3501. lbBlock *done = nullptr;
  3502. Ast *expr = unparen_expr(rs->expr);
  3503. TypeAndValue tav = type_and_value_of_expr(expr);
  3504. if (is_ast_range(expr)) {
  3505. lbAddr val0_addr = {};
  3506. lbAddr val1_addr = {};
  3507. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3508. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3509. TokenKind op = expr->BinaryExpr.op.kind;
  3510. Ast *start_expr = expr->BinaryExpr.left;
  3511. Ast *end_expr = expr->BinaryExpr.right;
  3512. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3513. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3514. ExactValue start = start_expr->tav.value;
  3515. ExactValue end = end_expr->tav.value;
  3516. if (op == Token_Ellipsis) { // .. [start, end]
  3517. ExactValue index = exact_value_i64(0);
  3518. for (ExactValue val = start;
  3519. compare_exact_values(Token_LtEq, val, end);
  3520. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3521. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3522. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3523. lb_build_stmt(p, rs->body);
  3524. }
  3525. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3526. ExactValue index = exact_value_i64(0);
  3527. for (ExactValue val = start;
  3528. compare_exact_values(Token_Lt, val, end);
  3529. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3530. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3531. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3532. lb_build_stmt(p, rs->body);
  3533. }
  3534. }
  3535. } else if (tav.mode == Addressing_Type) {
  3536. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3537. Type *et = type_deref(tav.type);
  3538. Type *bet = base_type(et);
  3539. lbAddr val0_addr = {};
  3540. lbAddr val1_addr = {};
  3541. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3542. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3543. for_array(i, bet->Enum.fields) {
  3544. Entity *field = bet->Enum.fields[i];
  3545. GB_ASSERT(field->kind == Entity_Constant);
  3546. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3547. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3548. lb_build_stmt(p, rs->body);
  3549. }
  3550. } else {
  3551. lbAddr val0_addr = {};
  3552. lbAddr val1_addr = {};
  3553. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3554. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3555. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3556. Type *t = base_type(expr->tav.type);
  3557. switch (t->kind) {
  3558. case Type_Basic:
  3559. GB_ASSERT(is_type_string(t));
  3560. {
  3561. ExactValue value = expr->tav.value;
  3562. GB_ASSERT(value.kind == ExactValue_String);
  3563. String str = value.value_string;
  3564. Rune codepoint = 0;
  3565. isize offset = 0;
  3566. do {
  3567. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3568. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3569. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3570. lb_build_stmt(p, rs->body);
  3571. offset += width;
  3572. } while (offset < str.len);
  3573. }
  3574. break;
  3575. case Type_Array:
  3576. if (t->Array.count > 0) {
  3577. lbValue val = lb_build_expr(p, expr);
  3578. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3579. for (i64 i = 0; i < t->Array.count; i++) {
  3580. if (val0_type) {
  3581. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3582. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3583. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3584. }
  3585. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3586. lb_build_stmt(p, rs->body);
  3587. }
  3588. }
  3589. break;
  3590. case Type_EnumeratedArray:
  3591. if (t->EnumeratedArray.count > 0) {
  3592. lbValue val = lb_build_expr(p, expr);
  3593. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3594. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3595. if (val0_type) {
  3596. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3597. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3598. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3599. }
  3600. if (val1_type) {
  3601. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3602. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3603. }
  3604. lb_build_stmt(p, rs->body);
  3605. }
  3606. }
  3607. break;
  3608. default:
  3609. GB_PANIC("Invalid '#unroll for' type");
  3610. break;
  3611. }
  3612. }
  3613. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3614. }
  3615. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  3616. lb_open_scope(p, scope);
  3617. if (ss->init != nullptr) {
  3618. lb_build_stmt(p, ss->init);
  3619. }
  3620. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3621. if (ss->tag != nullptr) {
  3622. tag = lb_build_expr(p, ss->tag);
  3623. }
  3624. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3625. ast_node(body, BlockStmt, ss->body);
  3626. Slice<Ast *> default_stmts = {};
  3627. lbBlock *default_fall = nullptr;
  3628. lbBlock *default_block = nullptr;
  3629. lbBlock *fall = nullptr;
  3630. isize case_count = body->stmts.count;
  3631. for_array(i, body->stmts) {
  3632. Ast *clause = body->stmts[i];
  3633. ast_node(cc, CaseClause, clause);
  3634. lbBlock *body = fall;
  3635. if (body == nullptr) {
  3636. body = lb_create_block(p, "switch.case.body");
  3637. }
  3638. fall = done;
  3639. if (i+1 < case_count) {
  3640. fall = lb_create_block(p, "switch.fall.body");
  3641. }
  3642. if (cc->list.count == 0) {
  3643. // default case
  3644. default_stmts = cc->stmts;
  3645. default_fall = fall;
  3646. default_block = body;
  3647. continue;
  3648. }
  3649. lbBlock *next_cond = nullptr;
  3650. for_array(j, cc->list) {
  3651. Ast *expr = unparen_expr(cc->list[j]);
  3652. next_cond = lb_create_block(p, "switch.case.next");
  3653. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3654. if (is_ast_range(expr)) {
  3655. ast_node(ie, BinaryExpr, expr);
  3656. TokenKind op = Token_Invalid;
  3657. switch (ie->op.kind) {
  3658. case Token_Ellipsis: op = Token_LtEq; break;
  3659. case Token_RangeHalf: op = Token_Lt; break;
  3660. default: GB_PANIC("Invalid interval operator"); break;
  3661. }
  3662. lbValue lhs = lb_build_expr(p, ie->left);
  3663. lbValue rhs = lb_build_expr(p, ie->right);
  3664. // TODO(bill): do short circuit here
  3665. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3666. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3667. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3668. } else {
  3669. if (expr->tav.mode == Addressing_Type) {
  3670. GB_ASSERT(is_type_typeid(tag.type));
  3671. lbValue e = lb_typeid(p->module, expr->tav.type);
  3672. e = lb_emit_conv(p, e, tag.type);
  3673. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3674. } else {
  3675. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3676. }
  3677. }
  3678. lb_emit_if(p, cond, body, next_cond);
  3679. lb_start_block(p, next_cond);
  3680. }
  3681. lb_start_block(p, body);
  3682. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3683. lb_open_scope(p, body->scope);
  3684. lb_build_stmt_list(p, cc->stmts);
  3685. lb_close_scope(p, lbDeferExit_Default, body);
  3686. lb_pop_target_list(p);
  3687. lb_emit_jump(p, done);
  3688. lb_start_block(p, next_cond);
  3689. }
  3690. if (default_block != nullptr) {
  3691. lb_emit_jump(p, default_block);
  3692. lb_start_block(p, default_block);
  3693. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3694. lb_open_scope(p, default_block->scope);
  3695. lb_build_stmt_list(p, default_stmts);
  3696. lb_close_scope(p, lbDeferExit_Default, default_block);
  3697. lb_pop_target_list(p);
  3698. }
  3699. lb_emit_jump(p, done);
  3700. lb_close_scope(p, lbDeferExit_Default, done);
  3701. lb_start_block(p, done);
  3702. }
  3703. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3704. Entity *e = implicit_entity_of_node(clause);
  3705. GB_ASSERT(e != nullptr);
  3706. if (e->flags & EntityFlag_Value) {
  3707. // by value
  3708. GB_ASSERT(are_types_identical(e->type, value.type));
  3709. lbAddr x = lb_add_local(p, e->type, e, false);
  3710. lb_addr_store(p, x, value);
  3711. } else {
  3712. // by reference
  3713. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3714. lb_add_entity(p->module, e, value);
  3715. }
  3716. }
  3717. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3718. Entity *e = entity_of_node(stmt_val);
  3719. if (e == nullptr) {
  3720. return {};
  3721. }
  3722. if ((e->flags & EntityFlag_Value) == 0) {
  3723. if (LLVMIsALoadInst(value.value)) {
  3724. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3725. lb_add_entity(p->module, e, ptr);
  3726. return lb_addr(ptr);
  3727. }
  3728. }
  3729. // by value
  3730. lbAddr addr = lb_add_local(p, e->type, e, false);
  3731. lb_addr_store(p, addr, value);
  3732. return addr;
  3733. }
  3734. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3735. ast_node(cc, CaseClause, clause);
  3736. lb_push_target_list(p, label, done, nullptr, nullptr);
  3737. lb_open_scope(p, body->scope);
  3738. lb_build_stmt_list(p, cc->stmts);
  3739. lb_close_scope(p, lbDeferExit_Default, body);
  3740. lb_pop_target_list(p);
  3741. lb_emit_jump(p, done);
  3742. }
  3743. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3744. lbModule *m = p->module;
  3745. ast_node(as, AssignStmt, ss->tag);
  3746. GB_ASSERT(as->lhs.count == 1);
  3747. GB_ASSERT(as->rhs.count == 1);
  3748. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3749. bool is_parent_ptr = is_type_pointer(parent.type);
  3750. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3751. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3752. lbValue parent_value = parent;
  3753. lbValue parent_ptr = parent;
  3754. if (!is_parent_ptr) {
  3755. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3756. }
  3757. lbValue tag_index = {};
  3758. lbValue union_data = {};
  3759. if (switch_kind == TypeSwitch_Union) {
  3760. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3761. tag_index = lb_emit_load(p, tag_ptr);
  3762. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3763. }
  3764. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3765. lb_emit_jump(p, start_block);
  3766. lb_start_block(p, start_block);
  3767. // NOTE(bill): Append this later
  3768. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3769. Ast *default_ = nullptr;
  3770. ast_node(body, BlockStmt, ss->body);
  3771. gb_local_persist i32 weird_count = 0;
  3772. for_array(i, body->stmts) {
  3773. Ast *clause = body->stmts[i];
  3774. ast_node(cc, CaseClause, clause);
  3775. if (cc->list.count == 0) {
  3776. default_ = clause;
  3777. continue;
  3778. }
  3779. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3780. lbBlock *next = nullptr;
  3781. Type *case_type = nullptr;
  3782. for_array(type_index, cc->list) {
  3783. next = lb_create_block(p, "typeswitch.next");
  3784. case_type = type_of_expr(cc->list[type_index]);
  3785. lbValue cond = {};
  3786. if (switch_kind == TypeSwitch_Union) {
  3787. Type *ut = base_type(type_deref(parent.type));
  3788. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3789. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3790. } else if (switch_kind == TypeSwitch_Any) {
  3791. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3792. lbValue case_typeid = lb_typeid(m, case_type);
  3793. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3794. }
  3795. GB_ASSERT(cond.value != nullptr);
  3796. lb_emit_if(p, cond, body, next);
  3797. lb_start_block(p, next);
  3798. }
  3799. Entity *case_entity = implicit_entity_of_node(clause);
  3800. lbValue value = parent_value;
  3801. lb_start_block(p, body);
  3802. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3803. if (cc->list.count == 1) {
  3804. lbValue data = {};
  3805. if (switch_kind == TypeSwitch_Union) {
  3806. data = union_data;
  3807. } else if (switch_kind == TypeSwitch_Any) {
  3808. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3809. data = any_data;
  3810. }
  3811. Type *ct = case_entity->type;
  3812. Type *ct_ptr = alloc_type_pointer(ct);
  3813. value = lb_emit_conv(p, data, ct_ptr);
  3814. if (!by_reference) {
  3815. value = lb_emit_load(p, value);
  3816. }
  3817. }
  3818. lb_store_type_case_implicit(p, clause, value);
  3819. lb_type_case_body(p, ss->label, clause, body, done);
  3820. lb_start_block(p, next);
  3821. }
  3822. if (default_ != nullptr) {
  3823. lb_store_type_case_implicit(p, default_, parent_value);
  3824. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3825. } else {
  3826. lb_emit_jump(p, done);
  3827. }
  3828. lb_start_block(p, done);
  3829. }
  3830. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3831. lbModule *m = p->module;
  3832. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3833. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3834. type = default_type(type);
  3835. lbValue short_circuit = {};
  3836. if (op == Token_CmpAnd) {
  3837. lb_build_cond(p, left, rhs, done);
  3838. short_circuit = lb_const_bool(m, type, false);
  3839. } else if (op == Token_CmpOr) {
  3840. lb_build_cond(p, left, done, rhs);
  3841. short_circuit = lb_const_bool(m, type, true);
  3842. }
  3843. if (rhs->preds.count == 0) {
  3844. lb_start_block(p, done);
  3845. return short_circuit;
  3846. }
  3847. if (done->preds.count == 0) {
  3848. lb_start_block(p, rhs);
  3849. return lb_build_expr(p, right);
  3850. }
  3851. Array<LLVMValueRef> incoming_values = {};
  3852. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3853. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3854. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3855. for_array(i, done->preds) {
  3856. incoming_values[i] = short_circuit.value;
  3857. incoming_blocks[i] = done->preds[i]->block;
  3858. }
  3859. lb_start_block(p, rhs);
  3860. lbValue edge = lb_build_expr(p, right);
  3861. incoming_values[done->preds.count] = edge.value;
  3862. incoming_blocks[done->preds.count] = p->curr_block->block;
  3863. lb_emit_jump(p, done);
  3864. lb_start_block(p, done);
  3865. lbValue res = {};
  3866. res.type = type;
  3867. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3868. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3869. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3870. return res;
  3871. }
  3872. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3873. Ast *prev_stmt = p->curr_stmt;
  3874. defer (p->curr_stmt = prev_stmt);
  3875. p->curr_stmt = node;
  3876. if (p->curr_block != nullptr) {
  3877. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3878. if (lb_is_instr_terminating(last_instr)) {
  3879. return;
  3880. }
  3881. }
  3882. LLVMMetadataRef prev_debug_location = nullptr;
  3883. if (p->debug_info != nullptr) {
  3884. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  3885. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  3886. }
  3887. defer (if (prev_debug_location != nullptr) {
  3888. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  3889. });
  3890. u64 prev_state_flags = p->module->state_flags;
  3891. defer (p->module->state_flags = prev_state_flags);
  3892. if (node->state_flags != 0) {
  3893. u64 in = node->state_flags;
  3894. u64 out = p->module->state_flags;
  3895. if (in & StateFlag_bounds_check) {
  3896. out |= StateFlag_bounds_check;
  3897. out &= ~StateFlag_no_bounds_check;
  3898. } else if (in & StateFlag_no_bounds_check) {
  3899. out |= StateFlag_no_bounds_check;
  3900. out &= ~StateFlag_bounds_check;
  3901. }
  3902. p->module->state_flags = out;
  3903. }
  3904. switch (node->kind) {
  3905. case_ast_node(bs, EmptyStmt, node);
  3906. case_end;
  3907. case_ast_node(us, UsingStmt, node);
  3908. case_end;
  3909. case_ast_node(ws, WhenStmt, node);
  3910. lb_build_when_stmt(p, ws);
  3911. case_end;
  3912. case_ast_node(bs, BlockStmt, node);
  3913. lbBlock *done = nullptr;
  3914. if (bs->label != nullptr) {
  3915. done = lb_create_block(p, "block.done");
  3916. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3917. tl->is_block = true;
  3918. }
  3919. lb_open_scope(p, node->scope);
  3920. lb_build_stmt_list(p, bs->stmts);
  3921. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3922. if (done != nullptr) {
  3923. lb_emit_jump(p, done);
  3924. lb_start_block(p, done);
  3925. }
  3926. case_end;
  3927. case_ast_node(vd, ValueDecl, node);
  3928. if (!vd->is_mutable) {
  3929. return;
  3930. }
  3931. bool is_static = false;
  3932. if (vd->names.count > 0) {
  3933. Entity *e = entity_of_node(vd->names[0]);
  3934. if (e->flags & EntityFlag_Static) {
  3935. // NOTE(bill): If one of the entities is static, they all are
  3936. is_static = true;
  3937. }
  3938. }
  3939. if (is_static) {
  3940. for_array(i, vd->names) {
  3941. lbValue value = {};
  3942. if (vd->values.count > 0) {
  3943. GB_ASSERT(vd->names.count == vd->values.count);
  3944. Ast *ast_value = vd->values[i];
  3945. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3946. ast_value->tav.mode == Addressing_Invalid);
  3947. bool allow_local = false;
  3948. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3949. }
  3950. Ast *ident = vd->names[i];
  3951. GB_ASSERT(!is_blank_ident(ident));
  3952. Entity *e = entity_of_node(ident);
  3953. GB_ASSERT(e->flags & EntityFlag_Static);
  3954. String name = e->token.string;
  3955. String mangled_name = {};
  3956. {
  3957. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  3958. str = gb_string_appendc(str, "-");
  3959. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3960. mangled_name.text = cast(u8 *)str;
  3961. mangled_name.len = gb_string_length(str);
  3962. }
  3963. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  3964. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3965. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3966. if (value.value != nullptr) {
  3967. LLVMSetInitializer(global, value.value);
  3968. } else {
  3969. }
  3970. if (e->Variable.thread_local_model != "") {
  3971. LLVMSetThreadLocal(global, true);
  3972. String m = e->Variable.thread_local_model;
  3973. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3974. if (m == "default") {
  3975. mode = LLVMGeneralDynamicTLSModel;
  3976. } else if (m == "localdynamic") {
  3977. mode = LLVMLocalDynamicTLSModel;
  3978. } else if (m == "initialexec") {
  3979. mode = LLVMInitialExecTLSModel;
  3980. } else if (m == "localexec") {
  3981. mode = LLVMLocalExecTLSModel;
  3982. } else {
  3983. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3984. }
  3985. LLVMSetThreadLocalMode(global, mode);
  3986. } else {
  3987. LLVMSetLinkage(global, LLVMInternalLinkage);
  3988. }
  3989. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3990. lb_add_entity(p->module, e, global_val);
  3991. lb_add_member(p->module, mangled_name, global_val);
  3992. }
  3993. return;
  3994. }
  3995. if (vd->values.count == 0) { // declared and zero-initialized
  3996. for_array(i, vd->names) {
  3997. Ast *name = vd->names[i];
  3998. if (!is_blank_ident(name)) {
  3999. Entity *e = entity_of_node(name);
  4000. lb_add_local(p, e->type, e, true);
  4001. }
  4002. }
  4003. } else { // Tuple(s)
  4004. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  4005. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  4006. for_array(i, vd->names) {
  4007. Ast *name = vd->names[i];
  4008. lbAddr lval = {};
  4009. if (!is_blank_ident(name)) {
  4010. Entity *e = entity_of_node(name);
  4011. lval = lb_add_local(p, e->type, e, false);
  4012. }
  4013. array_add(&lvals, lval);
  4014. }
  4015. for_array(i, vd->values) {
  4016. lbValue init = lb_build_expr(p, vd->values[i]);
  4017. Type *t = init.type;
  4018. if (t->kind == Type_Tuple) {
  4019. for_array(i, t->Tuple.variables) {
  4020. Entity *e = t->Tuple.variables[i];
  4021. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4022. array_add(&inits, v);
  4023. }
  4024. } else {
  4025. array_add(&inits, init);
  4026. }
  4027. }
  4028. for_array(i, inits) {
  4029. lbAddr lval = lvals[i];
  4030. lbValue init = inits[i];
  4031. lb_addr_store(p, lval, init);
  4032. }
  4033. }
  4034. case_end;
  4035. case_ast_node(as, AssignStmt, node);
  4036. if (as->op.kind == Token_Eq) {
  4037. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  4038. for_array(i, as->lhs) {
  4039. Ast *lhs = as->lhs[i];
  4040. lbAddr lval = {};
  4041. if (!is_blank_ident(lhs)) {
  4042. lval = lb_build_addr(p, lhs);
  4043. }
  4044. array_add(&lvals, lval);
  4045. }
  4046. if (as->lhs.count == as->rhs.count) {
  4047. if (as->lhs.count == 1) {
  4048. lbAddr lval = lvals[0];
  4049. Ast *rhs = as->rhs[0];
  4050. lbValue init = lb_build_expr(p, rhs);
  4051. lb_addr_store(p, lvals[0], init);
  4052. } else {
  4053. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4054. for_array(i, as->rhs) {
  4055. lbValue init = lb_build_expr(p, as->rhs[i]);
  4056. array_add(&inits, init);
  4057. }
  4058. for_array(i, inits) {
  4059. lbAddr lval = lvals[i];
  4060. lbValue init = inits[i];
  4061. lb_addr_store(p, lval, init);
  4062. }
  4063. }
  4064. } else {
  4065. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  4066. for_array(i, as->rhs) {
  4067. lbValue init = lb_build_expr(p, as->rhs[i]);
  4068. Type *t = init.type;
  4069. // TODO(bill): refactor for code reuse as this is repeated a bit
  4070. if (t->kind == Type_Tuple) {
  4071. for_array(i, t->Tuple.variables) {
  4072. Entity *e = t->Tuple.variables[i];
  4073. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  4074. array_add(&inits, v);
  4075. }
  4076. } else {
  4077. array_add(&inits, init);
  4078. }
  4079. }
  4080. for_array(i, inits) {
  4081. lbAddr lval = lvals[i];
  4082. lbValue init = inits[i];
  4083. lb_addr_store(p, lval, init);
  4084. }
  4085. }
  4086. } else {
  4087. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  4088. // +=, -=, etc
  4089. i32 op = cast(i32)as->op.kind;
  4090. op += Token_Add - Token_AddEq; // Convert += to +
  4091. if (op == Token_CmpAnd || op == Token_CmpOr) {
  4092. Type *type = as->lhs[0]->tav.type;
  4093. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  4094. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4095. lb_addr_store(p, lhs, new_value);
  4096. } else {
  4097. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  4098. lbValue value = lb_build_expr(p, as->rhs[0]);
  4099. lbValue old_value = lb_addr_load(p, lhs);
  4100. Type *type = old_value.type;
  4101. lbValue change = lb_emit_conv(p, value, type);
  4102. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  4103. lb_addr_store(p, lhs, new_value);
  4104. }
  4105. return;
  4106. }
  4107. case_end;
  4108. case_ast_node(es, ExprStmt, node);
  4109. lb_build_expr(p, es->expr);
  4110. case_end;
  4111. case_ast_node(ds, DeferStmt, node);
  4112. isize scope_index = p->scope_index;
  4113. lb_add_defer_node(p, scope_index, ds->stmt);
  4114. case_end;
  4115. case_ast_node(rs, ReturnStmt, node);
  4116. lbValue res = {};
  4117. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  4118. isize return_count = p->type->Proc.result_count;
  4119. isize res_count = rs->results.count;
  4120. if (return_count == 0) {
  4121. // No return values
  4122. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4123. LLVMBuildRetVoid(p->builder);
  4124. return;
  4125. } else if (return_count == 1) {
  4126. Entity *e = tuple->variables[0];
  4127. if (res_count == 0) {
  4128. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4129. GB_ASSERT(found);
  4130. res = lb_emit_load(p, *found);
  4131. } else {
  4132. res = lb_build_expr(p, rs->results[0]);
  4133. res = lb_emit_conv(p, res, e->type);
  4134. }
  4135. if (p->type->Proc.has_named_results) {
  4136. // NOTE(bill): store the named values before returning
  4137. if (e->token.string != "") {
  4138. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4139. GB_ASSERT(found != nullptr);
  4140. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  4141. }
  4142. }
  4143. } else {
  4144. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  4145. if (res_count != 0) {
  4146. for (isize res_index = 0; res_index < res_count; res_index++) {
  4147. lbValue res = lb_build_expr(p, rs->results[res_index]);
  4148. Type *t = res.type;
  4149. if (t->kind == Type_Tuple) {
  4150. for_array(i, t->Tuple.variables) {
  4151. Entity *e = t->Tuple.variables[i];
  4152. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  4153. array_add(&results, v);
  4154. }
  4155. } else {
  4156. array_add(&results, res);
  4157. }
  4158. }
  4159. } else {
  4160. for (isize res_index = 0; res_index < return_count; res_index++) {
  4161. Entity *e = tuple->variables[res_index];
  4162. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4163. GB_ASSERT(found);
  4164. lbValue res = lb_emit_load(p, *found);
  4165. array_add(&results, res);
  4166. }
  4167. }
  4168. GB_ASSERT(results.count == return_count);
  4169. if (p->type->Proc.has_named_results) {
  4170. // NOTE(bill): store the named values before returning
  4171. for_array(i, p->type->Proc.results->Tuple.variables) {
  4172. Entity *e = p->type->Proc.results->Tuple.variables[i];
  4173. if (e->kind != Entity_Variable) {
  4174. continue;
  4175. }
  4176. if (e->token.string == "") {
  4177. continue;
  4178. }
  4179. lbValue *found = map_get(&p->module->values, hash_entity(e));
  4180. GB_ASSERT(found != nullptr);
  4181. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  4182. }
  4183. }
  4184. Type *ret_type = p->type->Proc.results;
  4185. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4186. res = lb_add_local_generated(p, ret_type, false).addr;
  4187. for_array(i, results) {
  4188. Entity *e = tuple->variables[i];
  4189. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  4190. lbValue val = lb_emit_conv(p, results[i], e->type);
  4191. lb_emit_store(p, field, val);
  4192. }
  4193. res = lb_emit_load(p, res);
  4194. }
  4195. lb_ensure_abi_function_type(p->module, p);
  4196. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  4197. if (res.value != nullptr) {
  4198. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  4199. } else {
  4200. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  4201. }
  4202. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4203. LLVMBuildRetVoid(p->builder);
  4204. } else {
  4205. LLVMValueRef ret_val = res.value;
  4206. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  4207. if (p->abi_function_type->ret.cast_type != nullptr) {
  4208. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  4209. }
  4210. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  4211. LLVMBuildRet(p->builder, ret_val);
  4212. }
  4213. case_end;
  4214. case_ast_node(is, IfStmt, node);
  4215. lb_open_scope(p, node->scope); // Scope #1
  4216. if (is->init != nullptr) {
  4217. // TODO(bill): Should this have a separate block to begin with?
  4218. #if 1
  4219. lbBlock *init = lb_create_block(p, "if.init");
  4220. lb_emit_jump(p, init);
  4221. lb_start_block(p, init);
  4222. #endif
  4223. lb_build_stmt(p, is->init);
  4224. }
  4225. lbBlock *then = lb_create_block(p, "if.then");
  4226. lbBlock *done = lb_create_block(p, "if.done");
  4227. lbBlock *else_ = done;
  4228. if (is->else_stmt != nullptr) {
  4229. else_ = lb_create_block(p, "if.else");
  4230. }
  4231. lb_build_cond(p, is->cond, then, else_);
  4232. lb_start_block(p, then);
  4233. if (is->label != nullptr) {
  4234. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  4235. tl->is_block = true;
  4236. }
  4237. lb_build_stmt(p, is->body);
  4238. lb_emit_jump(p, done);
  4239. if (is->else_stmt != nullptr) {
  4240. lb_start_block(p, else_);
  4241. lb_open_scope(p, is->else_stmt->scope);
  4242. lb_build_stmt(p, is->else_stmt);
  4243. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4244. lb_emit_jump(p, done);
  4245. }
  4246. lb_start_block(p, done);
  4247. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4248. case_end;
  4249. case_ast_node(fs, ForStmt, node);
  4250. lb_open_scope(p, node->scope); // Open Scope here
  4251. if (fs->init != nullptr) {
  4252. #if 1
  4253. lbBlock *init = lb_create_block(p, "for.init");
  4254. lb_emit_jump(p, init);
  4255. lb_start_block(p, init);
  4256. #endif
  4257. lb_build_stmt(p, fs->init);
  4258. }
  4259. lbBlock *body = lb_create_block(p, "for.body");
  4260. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  4261. lbBlock *loop = body;
  4262. if (fs->cond != nullptr) {
  4263. loop = lb_create_block(p, "for.loop");
  4264. }
  4265. lbBlock *post = loop;
  4266. if (fs->post != nullptr) {
  4267. post = lb_create_block(p, "for.post");
  4268. }
  4269. lb_emit_jump(p, loop);
  4270. lb_start_block(p, loop);
  4271. if (loop != body) {
  4272. lb_build_cond(p, fs->cond, body, done);
  4273. lb_start_block(p, body);
  4274. }
  4275. lb_push_target_list(p, fs->label, done, post, nullptr);
  4276. lb_build_stmt(p, fs->body);
  4277. lb_close_scope(p, lbDeferExit_Default, nullptr);
  4278. lb_pop_target_list(p);
  4279. lb_emit_jump(p, post);
  4280. if (fs->post != nullptr) {
  4281. lb_start_block(p, post);
  4282. lb_build_stmt(p, fs->post);
  4283. lb_emit_jump(p, loop);
  4284. }
  4285. lb_start_block(p, done);
  4286. case_end;
  4287. case_ast_node(rs, RangeStmt, node);
  4288. lb_build_range_stmt(p, rs, node->scope);
  4289. case_end;
  4290. case_ast_node(rs, InlineRangeStmt, node);
  4291. lb_build_inline_range_stmt(p, rs, node->scope);
  4292. case_end;
  4293. case_ast_node(ss, SwitchStmt, node);
  4294. lb_build_switch_stmt(p, ss, node->scope);
  4295. case_end;
  4296. case_ast_node(ss, TypeSwitchStmt, node);
  4297. lb_build_type_switch_stmt(p, ss);
  4298. case_end;
  4299. case_ast_node(bs, BranchStmt, node);
  4300. lbBlock *block = nullptr;
  4301. if (bs->label != nullptr) {
  4302. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  4303. switch (bs->token.kind) {
  4304. case Token_break: block = bb.break_; break;
  4305. case Token_continue: block = bb.continue_; break;
  4306. case Token_fallthrough:
  4307. GB_PANIC("fallthrough cannot have a label");
  4308. break;
  4309. }
  4310. } else {
  4311. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  4312. if (t->is_block) {
  4313. continue;
  4314. }
  4315. switch (bs->token.kind) {
  4316. case Token_break: block = t->break_; break;
  4317. case Token_continue: block = t->continue_; break;
  4318. case Token_fallthrough: block = t->fallthrough_; break;
  4319. }
  4320. }
  4321. }
  4322. if (block != nullptr) {
  4323. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  4324. }
  4325. lb_emit_jump(p, block);
  4326. case_end;
  4327. }
  4328. }
  4329. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  4330. cond = lb_emit_conv(p, cond, t_llvm_bool);
  4331. lbValue res = {};
  4332. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  4333. res.type = x.type;
  4334. return res;
  4335. }
  4336. lbValue lb_const_nil(lbModule *m, Type *type) {
  4337. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  4338. return lbValue{v, type};
  4339. }
  4340. lbValue lb_const_undef(lbModule *m, Type *type) {
  4341. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  4342. return lbValue{v, type};
  4343. }
  4344. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  4345. lbValue res = {};
  4346. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  4347. res.type = type;
  4348. return res;
  4349. }
  4350. lbValue lb_const_string(lbModule *m, String const &value) {
  4351. return lb_const_value(m, t_string, exact_value_string(value));
  4352. }
  4353. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  4354. lbValue res = {};
  4355. res.value = LLVMConstInt(lb_type(m, type), value, false);
  4356. res.type = type;
  4357. return res;
  4358. }
  4359. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4360. GB_ASSERT(type_size_of(type) == 4);
  4361. u32 u = bit_cast<u32>(f);
  4362. if (is_type_different_to_arch_endianness(type)) {
  4363. u = gb_endian_swap32(u);
  4364. }
  4365. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4366. return LLVMConstBitCast(i, lb_type(m, type));
  4367. }
  4368. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4369. x = lb_emit_conv(p, x, t);
  4370. y = lb_emit_conv(p, y, t);
  4371. if (is_type_float(t)) {
  4372. i64 sz = 8*type_size_of(t);
  4373. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4374. args[0] = x;
  4375. args[1] = y;
  4376. switch (sz) {
  4377. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4378. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4379. }
  4380. GB_PANIC("Unknown float type");
  4381. }
  4382. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4383. }
  4384. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4385. x = lb_emit_conv(p, x, t);
  4386. y = lb_emit_conv(p, y, t);
  4387. if (is_type_float(t)) {
  4388. i64 sz = 8*type_size_of(t);
  4389. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4390. args[0] = x;
  4391. args[1] = y;
  4392. switch (sz) {
  4393. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4394. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4395. }
  4396. GB_PANIC("Unknown float type");
  4397. }
  4398. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4399. }
  4400. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4401. lbValue z = {};
  4402. z = lb_emit_max(p, t, x, min);
  4403. z = lb_emit_min(p, t, z, max);
  4404. return z;
  4405. }
  4406. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4407. StringHashKey key = string_hash_string(str);
  4408. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4409. if (found != nullptr) {
  4410. return *found;
  4411. } else {
  4412. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4413. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4414. cast(char const *)str.text,
  4415. cast(unsigned)str.len,
  4416. false);
  4417. isize max_len = 7+8+1;
  4418. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4419. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4420. len -= 1;
  4421. m->global_array_index++;
  4422. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4423. LLVMSetInitializer(global_data, data);
  4424. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4425. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4426. string_map_set(&m->const_strings, key, ptr);
  4427. return ptr;
  4428. }
  4429. }
  4430. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4431. LLVMValueRef ptr = nullptr;
  4432. if (str.len != 0) {
  4433. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4434. } else {
  4435. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4436. }
  4437. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4438. LLVMValueRef values[2] = {ptr, str_len};
  4439. lbValue res = {};
  4440. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  4441. res.type = t_string;
  4442. return res;
  4443. }
  4444. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4445. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4446. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4447. cast(char const *)str.text,
  4448. cast(unsigned)str.len,
  4449. false);
  4450. char *name = nullptr;
  4451. {
  4452. isize max_len = 7+8+1;
  4453. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4454. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4455. len -= 1;
  4456. m->global_array_index++;
  4457. }
  4458. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4459. LLVMSetInitializer(global_data, data);
  4460. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4461. LLVMValueRef ptr = nullptr;
  4462. if (str.len != 0) {
  4463. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4464. } else {
  4465. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4466. }
  4467. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4468. LLVMValueRef values[2] = {ptr, len};
  4469. lbValue res = {};
  4470. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  4471. res.type = t_u8_slice;
  4472. return res;
  4473. }
  4474. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4475. isize index = type_info_index(info, type, false);
  4476. if (index >= 0) {
  4477. auto *set = &info->minimum_dependency_type_info_set;
  4478. for_array(i, set->entries) {
  4479. if (set->entries[i].ptr == index) {
  4480. return i+1;
  4481. }
  4482. }
  4483. }
  4484. if (err_on_not_found) {
  4485. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4486. }
  4487. return -1;
  4488. }
  4489. lbValue lb_typeid(lbModule *m, Type *type) {
  4490. type = default_type(type);
  4491. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4492. GB_ASSERT(id >= 0);
  4493. u64 kind = Typeid_Invalid;
  4494. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4495. u64 special = 0;
  4496. u64 reserved = 0;
  4497. Type *bt = base_type(type);
  4498. TypeKind tk = bt->kind;
  4499. switch (tk) {
  4500. case Type_Basic: {
  4501. u32 flags = bt->Basic.flags;
  4502. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4503. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4504. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4505. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4506. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4507. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4508. if (flags & BasicFlag_String) kind = Typeid_String;
  4509. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4510. } break;
  4511. case Type_Pointer: kind = Typeid_Pointer; break;
  4512. case Type_Array: kind = Typeid_Array; break;
  4513. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4514. case Type_Slice: kind = Typeid_Slice; break;
  4515. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4516. case Type_Map: kind = Typeid_Map; break;
  4517. case Type_Struct: kind = Typeid_Struct; break;
  4518. case Type_Enum: kind = Typeid_Enum; break;
  4519. case Type_Union: kind = Typeid_Union; break;
  4520. case Type_Tuple: kind = Typeid_Tuple; break;
  4521. case Type_Proc: kind = Typeid_Procedure; break;
  4522. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4523. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4524. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4525. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4526. }
  4527. if (is_type_cstring(type)) {
  4528. special = 1;
  4529. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4530. special = 1;
  4531. }
  4532. u64 data = 0;
  4533. if (build_context.word_size == 4) {
  4534. GB_ASSERT(id <= (1u<<24u));
  4535. data |= (id &~ (1u<<24)) << 0u; // index
  4536. data |= (kind &~ (1u<<5)) << 24u; // kind
  4537. data |= (named &~ (1u<<1)) << 29u; // kind
  4538. data |= (special &~ (1u<<1)) << 30u; // kind
  4539. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4540. } else {
  4541. GB_ASSERT(build_context.word_size == 8);
  4542. GB_ASSERT(id <= (1ull<<56u));
  4543. data |= (id &~ (1ull<<56)) << 0ul; // index
  4544. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4545. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4546. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4547. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4548. }
  4549. lbValue res = {};
  4550. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4551. res.type = t_typeid;
  4552. return res;
  4553. }
  4554. lbValue lb_type_info(lbModule *m, Type *type) {
  4555. type = default_type(type);
  4556. isize index = lb_type_info_index(m->info, type);
  4557. GB_ASSERT(index >= 0);
  4558. LLVMTypeRef it = lb_type(m, t_int);
  4559. LLVMValueRef indices[2] = {
  4560. LLVMConstInt(it, 0, false),
  4561. LLVMConstInt(it, index, true),
  4562. };
  4563. lbValue value = {};
  4564. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4565. value.type = t_type_info_ptr;
  4566. return value;
  4567. }
  4568. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  4569. bool is_local = allow_local && m->curr_procedure != nullptr;
  4570. bool is_const = true;
  4571. if (is_local) {
  4572. for (isize i = 0; i < count; i++) {
  4573. GB_ASSERT(values[i] != nullptr);
  4574. if (!LLVMIsConstant(values[i])) {
  4575. is_const = false;
  4576. break;
  4577. }
  4578. }
  4579. }
  4580. if (!is_const) {
  4581. lbProcedure *p = m->curr_procedure;
  4582. GB_ASSERT(p != nullptr);
  4583. lbAddr v = lb_add_local_generated(p, type, false);
  4584. lbValue ptr = lb_addr_get_ptr(p, v);
  4585. for (isize i = 0; i < count; i++) {
  4586. lbValue elem = lb_emit_array_epi(p, ptr, i);
  4587. LLVMBuildStore(p->builder, values[i], elem.value);
  4588. }
  4589. return lb_addr_load(p, v).value;
  4590. }
  4591. return llvm_const_array(lb_type(m, elem_type), values, cast(unsigned int)count);
  4592. }
  4593. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4594. LLVMContextRef ctx = m->ctx;
  4595. type = default_type(type);
  4596. Type *original_type = type;
  4597. lbValue res = {};
  4598. res.type = original_type;
  4599. type = core_type(type);
  4600. value = convert_exact_value_for_type(value, type);
  4601. if (value.kind == ExactValue_Typeid) {
  4602. return lb_typeid(m, value.value_typeid);
  4603. }
  4604. if (value.kind == ExactValue_Invalid) {
  4605. return lb_const_nil(m, type);
  4606. }
  4607. if (value.kind == ExactValue_Procedure) {
  4608. Ast *expr = unparen_expr(value.value_procedure);
  4609. if (expr->kind == Ast_ProcLit) {
  4610. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4611. }
  4612. Entity *e = entity_from_expr(expr);
  4613. e = strip_entity_wrapping(e);
  4614. GB_ASSERT(e != nullptr);
  4615. auto *found = map_get(&m->values, hash_entity(e));
  4616. if (found) {
  4617. return *found;
  4618. }
  4619. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  4620. }
  4621. bool is_local = allow_local && m->curr_procedure != nullptr;
  4622. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4623. if (is_type_slice(type)) {
  4624. if (value.kind == ExactValue_String) {
  4625. GB_ASSERT(is_type_u8_slice(type));
  4626. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4627. return res;
  4628. } else {
  4629. ast_node(cl, CompoundLit, value.value_compound);
  4630. isize count = cl->elems.count;
  4631. if (count == 0) {
  4632. return lb_const_nil(m, type);
  4633. }
  4634. count = gb_max(cl->max_count, count);
  4635. Type *elem = base_type(type)->Slice.elem;
  4636. Type *t = alloc_type_array(elem, count);
  4637. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4638. LLVMValueRef array_data = nullptr;
  4639. if (is_local) {
  4640. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4641. // its backing data on the stack
  4642. lbProcedure *p = m->curr_procedure;
  4643. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4644. LLVMTypeRef llvm_type = lb_type(m, t);
  4645. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4646. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4647. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4648. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4649. {
  4650. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4651. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4652. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4653. lbAddr slice = lb_add_local_generated(p, type, false);
  4654. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4655. return lb_addr_load(p, slice);
  4656. }
  4657. } else {
  4658. isize max_len = 7+8+1;
  4659. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4660. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4661. m->global_array_index++;
  4662. String name = make_string(cast(u8 *)str, len-1);
  4663. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4664. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4665. LLVMSetInitializer(array_data, backing_array.value);
  4666. lbValue g = {};
  4667. g.value = array_data;
  4668. g.type = t;
  4669. lb_add_entity(m, e, g);
  4670. lb_add_member(m, name, g);
  4671. {
  4672. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4673. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4674. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4675. LLVMValueRef values[2] = {ptr, len};
  4676. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4677. return res;
  4678. }
  4679. }
  4680. }
  4681. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4682. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4683. i64 count = type->Array.count;
  4684. Type *elem = type->Array.elem;
  4685. LLVMTypeRef et = lb_type(m, elem);
  4686. Rune rune;
  4687. isize offset = 0;
  4688. isize width = 1;
  4689. String s = value.value_string;
  4690. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4691. for (i64 i = 0; i < count && offset < s.len; i++) {
  4692. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4693. offset += width;
  4694. elems[i] = LLVMConstInt(et, rune, true);
  4695. }
  4696. GB_ASSERT(offset == s.len);
  4697. res.value = llvm_const_array(et, elems, cast(unsigned)count);
  4698. return res;
  4699. }
  4700. GB_PANIC("HERE!\n");
  4701. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4702. cast(char const *)value.value_string.text,
  4703. cast(unsigned)value.value_string.len,
  4704. false /*DontNullTerminate*/);
  4705. res.value = data;
  4706. return res;
  4707. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4708. GB_ASSERT(type->Array.count == value.value_string.len);
  4709. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4710. cast(char const *)value.value_string.text,
  4711. cast(unsigned)value.value_string.len,
  4712. true /*DontNullTerminate*/);
  4713. res.value = data;
  4714. return res;
  4715. } else if (is_type_array(type) &&
  4716. value.kind != ExactValue_Invalid &&
  4717. value.kind != ExactValue_String &&
  4718. value.kind != ExactValue_Compound) {
  4719. i64 count = type->Array.count;
  4720. Type *elem = type->Array.elem;
  4721. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4722. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4723. for (i64 i = 0; i < count; i++) {
  4724. elems[i] = single_elem.value;
  4725. }
  4726. res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count);
  4727. return res;
  4728. }
  4729. switch (value.kind) {
  4730. case ExactValue_Invalid:
  4731. res.value = LLVMConstNull(lb_type(m, original_type));
  4732. return res;
  4733. case ExactValue_Bool:
  4734. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4735. return res;
  4736. case ExactValue_String:
  4737. {
  4738. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4739. lbValue res = {};
  4740. res.type = default_type(original_type);
  4741. if (is_type_cstring(res.type)) {
  4742. res.value = ptr;
  4743. } else {
  4744. if (value.value_string.len == 0) {
  4745. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4746. }
  4747. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4748. LLVMValueRef values[2] = {ptr, str_len};
  4749. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4750. }
  4751. return res;
  4752. }
  4753. case ExactValue_Integer:
  4754. if (is_type_pointer(type)) {
  4755. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4756. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4757. } else {
  4758. unsigned len = cast(unsigned)value.value_integer.len;
  4759. if (len == 0) {
  4760. u64 word = 0;
  4761. res.value = LLVMConstNull(lb_type(m, original_type));
  4762. } else {
  4763. u64 *words = big_int_ptr(&value.value_integer);
  4764. if (is_type_different_to_arch_endianness(type)) {
  4765. // NOTE(bill): Swap byte order for different endianness
  4766. i64 sz = type_size_of(type);
  4767. isize byte_len = gb_size_of(u64)*len;
  4768. u8 *old_bytes = cast(u8 *)words;
  4769. // TODO(bill): Use a different allocator here for a temporary allocation
  4770. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4771. for (i64 i = 0; i < sz; i++) {
  4772. new_bytes[i] = old_bytes[sz-1-i];
  4773. }
  4774. words = cast(u64 *)new_bytes;
  4775. }
  4776. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4777. if (value.value_integer.neg) {
  4778. res.value = LLVMConstNeg(res.value);
  4779. }
  4780. }
  4781. }
  4782. return res;
  4783. case ExactValue_Float:
  4784. if (type_size_of(type) == 4) {
  4785. f32 f = cast(f32)value.value_float;
  4786. res.value = lb_const_f32(m, f, type);
  4787. return res;
  4788. }
  4789. if (is_type_different_to_arch_endianness(type)) {
  4790. u64 u = bit_cast<u64>(value.value_float);
  4791. u = gb_endian_swap64(u);
  4792. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4793. } else {
  4794. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4795. }
  4796. return res;
  4797. case ExactValue_Complex:
  4798. {
  4799. LLVMValueRef values[2] = {};
  4800. switch (8*type_size_of(type)) {
  4801. case 64:
  4802. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  4803. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  4804. break;
  4805. case 128:
  4806. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  4807. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  4808. break;
  4809. }
  4810. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 2);
  4811. return res;
  4812. }
  4813. break;
  4814. case ExactValue_Quaternion:
  4815. {
  4816. LLVMValueRef values[4] = {};
  4817. switch (8*type_size_of(type)) {
  4818. case 128:
  4819. // @QuaternionLayout
  4820. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  4821. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  4822. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  4823. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  4824. break;
  4825. case 256:
  4826. // @QuaternionLayout
  4827. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  4828. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  4829. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  4830. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  4831. break;
  4832. }
  4833. res.value = llvm_const_named_struct(lb_type(m, original_type), values, 4);
  4834. return res;
  4835. }
  4836. break;
  4837. case ExactValue_Pointer:
  4838. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4839. return res;
  4840. case ExactValue_Compound:
  4841. if (is_type_slice(type)) {
  4842. return lb_const_value(m, type, value, allow_local);
  4843. } else if (is_type_array(type)) {
  4844. ast_node(cl, CompoundLit, value.value_compound);
  4845. Type *elem_type = type->Array.elem;
  4846. isize elem_count = cl->elems.count;
  4847. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4848. return lb_const_nil(m, original_type);
  4849. }
  4850. if (cl->elems[0]->kind == Ast_FieldValue) {
  4851. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4852. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4853. isize value_index = 0;
  4854. for (i64 i = 0; i < type->Array.count; i++) {
  4855. bool found = false;
  4856. for (isize j = 0; j < elem_count; j++) {
  4857. Ast *elem = cl->elems[j];
  4858. ast_node(fv, FieldValue, elem);
  4859. if (is_ast_range(fv->field)) {
  4860. ast_node(ie, BinaryExpr, fv->field);
  4861. TypeAndValue lo_tav = ie->left->tav;
  4862. TypeAndValue hi_tav = ie->right->tav;
  4863. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4864. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4865. TokenKind op = ie->op.kind;
  4866. i64 lo = exact_value_to_i64(lo_tav.value);
  4867. i64 hi = exact_value_to_i64(hi_tav.value);
  4868. if (op == Token_Ellipsis) {
  4869. hi += 1;
  4870. }
  4871. if (lo == i) {
  4872. TypeAndValue tav = fv->value->tav;
  4873. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4874. for (i64 k = lo; k < hi; k++) {
  4875. values[value_index++] = val;
  4876. }
  4877. found = true;
  4878. i += (hi-lo-1);
  4879. break;
  4880. }
  4881. } else {
  4882. TypeAndValue index_tav = fv->field->tav;
  4883. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4884. i64 index = exact_value_to_i64(index_tav.value);
  4885. if (index == i) {
  4886. TypeAndValue tav = fv->value->tav;
  4887. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4888. values[value_index++] = val;
  4889. found = true;
  4890. break;
  4891. }
  4892. }
  4893. }
  4894. if (!found) {
  4895. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4896. }
  4897. }
  4898. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4899. return res;
  4900. } else {
  4901. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4902. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4903. for (isize i = 0; i < elem_count; i++) {
  4904. TypeAndValue tav = cl->elems[i]->tav;
  4905. GB_ASSERT(tav.mode != Addressing_Invalid);
  4906. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4907. }
  4908. for (isize i = elem_count; i < type->Array.count; i++) {
  4909. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4910. }
  4911. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4912. return res;
  4913. }
  4914. } else if (is_type_enumerated_array(type)) {
  4915. ast_node(cl, CompoundLit, value.value_compound);
  4916. Type *elem_type = type->EnumeratedArray.elem;
  4917. isize elem_count = cl->elems.count;
  4918. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4919. return lb_const_nil(m, original_type);
  4920. }
  4921. if (cl->elems[0]->kind == Ast_FieldValue) {
  4922. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4923. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4924. isize value_index = 0;
  4925. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4926. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4927. for (i64 i = total_lo; i <= total_hi; i++) {
  4928. bool found = false;
  4929. for (isize j = 0; j < elem_count; j++) {
  4930. Ast *elem = cl->elems[j];
  4931. ast_node(fv, FieldValue, elem);
  4932. if (is_ast_range(fv->field)) {
  4933. ast_node(ie, BinaryExpr, fv->field);
  4934. TypeAndValue lo_tav = ie->left->tav;
  4935. TypeAndValue hi_tav = ie->right->tav;
  4936. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4937. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4938. TokenKind op = ie->op.kind;
  4939. i64 lo = exact_value_to_i64(lo_tav.value);
  4940. i64 hi = exact_value_to_i64(hi_tav.value);
  4941. if (op == Token_Ellipsis) {
  4942. hi += 1;
  4943. }
  4944. if (lo == i) {
  4945. TypeAndValue tav = fv->value->tav;
  4946. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4947. for (i64 k = lo; k < hi; k++) {
  4948. values[value_index++] = val;
  4949. }
  4950. found = true;
  4951. i += (hi-lo-1);
  4952. break;
  4953. }
  4954. } else {
  4955. TypeAndValue index_tav = fv->field->tav;
  4956. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4957. i64 index = exact_value_to_i64(index_tav.value);
  4958. if (index == i) {
  4959. TypeAndValue tav = fv->value->tav;
  4960. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4961. values[value_index++] = val;
  4962. found = true;
  4963. break;
  4964. }
  4965. }
  4966. }
  4967. if (!found) {
  4968. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4969. }
  4970. }
  4971. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4972. return res;
  4973. } else {
  4974. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4975. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4976. for (isize i = 0; i < elem_count; i++) {
  4977. TypeAndValue tav = cl->elems[i]->tav;
  4978. GB_ASSERT(tav.mode != Addressing_Invalid);
  4979. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4980. }
  4981. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4982. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4983. }
  4984. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4985. return res;
  4986. }
  4987. } else if (is_type_simd_vector(type)) {
  4988. ast_node(cl, CompoundLit, value.value_compound);
  4989. Type *elem_type = type->SimdVector.elem;
  4990. isize elem_count = cl->elems.count;
  4991. if (elem_count == 0) {
  4992. return lb_const_nil(m, original_type);
  4993. }
  4994. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4995. isize total_elem_count = type->SimdVector.count;
  4996. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  4997. for (isize i = 0; i < elem_count; i++) {
  4998. TypeAndValue tav = cl->elems[i]->tav;
  4999. GB_ASSERT(tav.mode != Addressing_Invalid);
  5000. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  5001. }
  5002. LLVMTypeRef et = lb_type(m, elem_type);
  5003. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  5004. values[i] = LLVMConstNull(et);
  5005. }
  5006. for (isize i = 0; i< total_elem_count; i++) {
  5007. values[i] = llvm_const_cast(values[i], et);
  5008. }
  5009. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  5010. return res;
  5011. } else if (is_type_struct(type)) {
  5012. ast_node(cl, CompoundLit, value.value_compound);
  5013. if (cl->elems.count == 0) {
  5014. return lb_const_nil(m, original_type);
  5015. }
  5016. isize offset = 0;
  5017. if (type->Struct.custom_align > 0) {
  5018. offset = 1;
  5019. }
  5020. isize value_count = type->Struct.fields.count + offset;
  5021. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  5022. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  5023. if (cl->elems.count > 0) {
  5024. if (cl->elems[0]->kind == Ast_FieldValue) {
  5025. isize elem_count = cl->elems.count;
  5026. for (isize i = 0; i < elem_count; i++) {
  5027. ast_node(fv, FieldValue, cl->elems[i]);
  5028. String name = fv->field->Ident.token.string;
  5029. TypeAndValue tav = fv->value->tav;
  5030. GB_ASSERT(tav.mode != Addressing_Invalid);
  5031. Selection sel = lookup_field(type, name, false);
  5032. Entity *f = type->Struct.fields[sel.index[0]];
  5033. if (elem_type_can_be_constant(f->type)) {
  5034. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  5035. visited[offset+f->Variable.field_index] = true;
  5036. }
  5037. }
  5038. } else {
  5039. for_array(i, cl->elems) {
  5040. Entity *f = type->Struct.fields[i];
  5041. TypeAndValue tav = cl->elems[i]->tav;
  5042. ExactValue val = {};
  5043. if (tav.mode != Addressing_Invalid) {
  5044. val = tav.value;
  5045. }
  5046. if (elem_type_can_be_constant(f->type)) {
  5047. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  5048. visited[offset+f->Variable.field_index] = true;
  5049. }
  5050. }
  5051. }
  5052. }
  5053. for (isize i = 0; i < type->Struct.fields.count; i++) {
  5054. if (!visited[offset+i]) {
  5055. GB_ASSERT(values[offset+i] == nullptr);
  5056. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  5057. }
  5058. }
  5059. if (type->Struct.custom_align > 0) {
  5060. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  5061. }
  5062. for (isize i = 0; i < value_count; i++) {
  5063. GB_ASSERT(LLVMIsConstant(values[i]));
  5064. }
  5065. res.value = llvm_const_named_struct(lb_type(m, original_type), values, cast(unsigned)value_count);
  5066. return res;
  5067. } else if (is_type_bit_set(type)) {
  5068. ast_node(cl, CompoundLit, value.value_compound);
  5069. if (cl->elems.count == 0) {
  5070. return lb_const_nil(m, original_type);
  5071. }
  5072. i64 sz = type_size_of(type);
  5073. if (sz == 0) {
  5074. return lb_const_nil(m, original_type);
  5075. }
  5076. u64 bits = 0;
  5077. for_array(i, cl->elems) {
  5078. Ast *e = cl->elems[i];
  5079. GB_ASSERT(e->kind != Ast_FieldValue);
  5080. TypeAndValue tav = e->tav;
  5081. if (tav.mode != Addressing_Constant) {
  5082. continue;
  5083. }
  5084. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  5085. i64 v = big_int_to_i64(&tav.value.value_integer);
  5086. i64 lower = type->BitSet.lower;
  5087. bits |= 1ull<<cast(u64)(v-lower);
  5088. }
  5089. if (is_type_different_to_arch_endianness(type)) {
  5090. i64 size = type_size_of(type);
  5091. switch (size) {
  5092. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  5093. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  5094. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  5095. }
  5096. }
  5097. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  5098. return res;
  5099. } else {
  5100. return lb_const_nil(m, original_type);
  5101. }
  5102. break;
  5103. case ExactValue_Procedure:
  5104. {
  5105. Ast *expr = value.value_procedure;
  5106. GB_ASSERT(expr != nullptr);
  5107. if (expr->kind == Ast_ProcLit) {
  5108. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  5109. }
  5110. }
  5111. break;
  5112. case ExactValue_Typeid:
  5113. return lb_typeid(m, value.value_typeid);
  5114. }
  5115. return lb_const_nil(m, original_type);
  5116. }
  5117. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  5118. lbModule *m = p->module;
  5119. LLVMValueRef fields[4] = {};
  5120. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)).value;
  5121. fields[1]/*line*/ = lb_const_int(m, t_i32, pos.line).value;
  5122. fields[2]/*column*/ = lb_const_int(m, t_i32, pos.column).value;
  5123. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  5124. lbValue res = {};
  5125. res.value = llvm_const_named_struct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  5126. res.type = t_source_code_location;
  5127. return res;
  5128. }
  5129. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  5130. String proc_name = {};
  5131. if (p->entity) {
  5132. proc_name = p->entity->token.string;
  5133. }
  5134. TokenPos pos = {};
  5135. if (node) {
  5136. pos = ast_token(node).pos;
  5137. }
  5138. return lb_emit_source_code_location(p, proc_name, pos);
  5139. }
  5140. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  5141. switch (op) {
  5142. case Token_Add:
  5143. return x;
  5144. case Token_Not: // Boolean not
  5145. case Token_Xor: // Bitwise not
  5146. case Token_Sub: // Number negation
  5147. break;
  5148. case Token_Pointer:
  5149. GB_PANIC("This should be handled elsewhere");
  5150. break;
  5151. }
  5152. if (is_type_array(x.type)) {
  5153. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  5154. Type *tl = base_type(x.type);
  5155. lbValue val = lb_address_from_load_or_generate_local(p, x);
  5156. GB_ASSERT(is_type_array(type));
  5157. Type *elem_type = base_array_type(type);
  5158. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5159. lbAddr res_addr = lb_add_local_generated(p, type, false);
  5160. lbValue res = lb_addr_get_ptr(p, res_addr);
  5161. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5162. i32 count = cast(i32)tl->Array.count;
  5163. if (inline_array_arith) {
  5164. // inline
  5165. for (i32 i = 0; i < count; i++) {
  5166. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  5167. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5168. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  5169. }
  5170. } else {
  5171. auto loop_data = lb_loop_start(p, count, t_i32);
  5172. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  5173. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  5174. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  5175. lb_loop_end(p, loop_data);
  5176. }
  5177. return lb_emit_load(p, res);
  5178. }
  5179. if (op == Token_Xor) {
  5180. lbValue cmp = {};
  5181. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  5182. cmp.type = x.type;
  5183. return lb_emit_conv(p, cmp, type);
  5184. }
  5185. if (op == Token_Not) {
  5186. lbValue cmp = {};
  5187. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  5188. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  5189. cmp.type = t_llvm_bool;
  5190. return lb_emit_conv(p, cmp, type);
  5191. }
  5192. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5193. Type *platform_type = integer_endian_type_to_platform_type(type);
  5194. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5195. lbValue res = {};
  5196. res.value = LLVMBuildNeg(p->builder, v.value, "");
  5197. res.type = platform_type;
  5198. return lb_emit_byte_swap(p, res, type);
  5199. }
  5200. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5201. Type *platform_type = integer_endian_type_to_platform_type(type);
  5202. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  5203. lbValue res = {};
  5204. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  5205. res.type = platform_type;
  5206. return lb_emit_byte_swap(p, res, type);
  5207. }
  5208. lbValue res = {};
  5209. switch (op) {
  5210. case Token_Not: // Boolean not
  5211. case Token_Xor: // Bitwise not
  5212. res.value = LLVMBuildNot(p->builder, x.value, "");
  5213. res.type = x.type;
  5214. return res;
  5215. case Token_Sub: // Number negation
  5216. if (is_type_integer(x.type)) {
  5217. res.value = LLVMBuildNeg(p->builder, x.value, "");
  5218. } else if (is_type_float(x.type)) {
  5219. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  5220. } else if (is_type_complex(x.type)) {
  5221. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5222. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5223. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5224. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5225. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5226. return lb_addr_load(p, addr);
  5227. } else if (is_type_quaternion(x.type)) {
  5228. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  5229. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  5230. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  5231. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  5232. lbAddr addr = lb_add_local_generated(p, x.type, false);
  5233. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  5234. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  5235. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  5236. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  5237. return lb_addr_load(p, addr);
  5238. } else {
  5239. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  5240. }
  5241. res.type = x.type;
  5242. return res;
  5243. }
  5244. return res;
  5245. }
  5246. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  5247. lbModule *m = p->module;
  5248. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  5249. lhs = lb_emit_conv(p, lhs, type);
  5250. rhs = lb_emit_conv(p, rhs, type);
  5251. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  5252. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  5253. GB_ASSERT(is_type_array(type));
  5254. Type *elem_type = base_array_type(type);
  5255. lbAddr res = lb_add_local_generated(p, type, false);
  5256. i64 count = base_type(type)->Array.count;
  5257. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  5258. if (inline_array_arith) {
  5259. for (i64 i = 0; i < count; i++) {
  5260. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  5261. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  5262. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  5263. lbValue a = lb_emit_load(p, a_ptr);
  5264. lbValue b = lb_emit_load(p, b_ptr);
  5265. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5266. lb_emit_store(p, dst_ptr, c);
  5267. }
  5268. } else {
  5269. auto loop_data = lb_loop_start(p, count, t_i32);
  5270. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  5271. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  5272. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  5273. lbValue a = lb_emit_load(p, a_ptr);
  5274. lbValue b = lb_emit_load(p, b_ptr);
  5275. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  5276. lb_emit_store(p, dst_ptr, c);
  5277. lb_loop_end(p, loop_data);
  5278. }
  5279. return lb_addr_load(p, res);
  5280. } else if (is_type_complex(type)) {
  5281. lhs = lb_emit_conv(p, lhs, type);
  5282. rhs = lb_emit_conv(p, rhs, type);
  5283. Type *ft = base_complex_elem_type(type);
  5284. if (op == Token_Quo) {
  5285. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5286. args[0] = lhs;
  5287. args[1] = rhs;
  5288. switch (type_size_of(ft)) {
  5289. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  5290. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  5291. default: GB_PANIC("Unknown float type"); break;
  5292. }
  5293. }
  5294. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5295. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  5296. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  5297. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  5298. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  5299. lbValue real = {};
  5300. lbValue imag = {};
  5301. switch (op) {
  5302. case Token_Add:
  5303. real = lb_emit_arith(p, Token_Add, a, c, ft);
  5304. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  5305. break;
  5306. case Token_Sub:
  5307. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  5308. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  5309. break;
  5310. case Token_Mul: {
  5311. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  5312. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  5313. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  5314. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  5315. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  5316. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  5317. break;
  5318. }
  5319. }
  5320. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  5321. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  5322. return lb_addr_load(p, res);
  5323. } else if (is_type_quaternion(type)) {
  5324. lhs = lb_emit_conv(p, lhs, type);
  5325. rhs = lb_emit_conv(p, rhs, type);
  5326. Type *ft = base_complex_elem_type(type);
  5327. if (op == Token_Add || op == Token_Sub) {
  5328. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  5329. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  5330. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  5331. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  5332. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  5333. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  5334. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  5335. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  5336. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  5337. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  5338. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  5339. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  5340. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  5341. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  5342. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  5343. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  5344. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  5345. return lb_addr_load(p, res);
  5346. } else if (op == Token_Mul) {
  5347. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5348. args[0] = lhs;
  5349. args[1] = rhs;
  5350. switch (8*type_size_of(ft)) {
  5351. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  5352. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  5353. default: GB_PANIC("Unknown float type"); break;
  5354. }
  5355. } else if (op == Token_Quo) {
  5356. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5357. args[0] = lhs;
  5358. args[1] = rhs;
  5359. switch (8*type_size_of(ft)) {
  5360. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  5361. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  5362. default: GB_PANIC("Unknown float type"); break;
  5363. }
  5364. }
  5365. }
  5366. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  5367. switch (op) {
  5368. case Token_AndNot:
  5369. case Token_And:
  5370. case Token_Or:
  5371. case Token_Xor:
  5372. goto handle_op;
  5373. }
  5374. Type *platform_type = integer_endian_type_to_platform_type(type);
  5375. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5376. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5377. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5378. return lb_emit_byte_swap(p, res, type);
  5379. }
  5380. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5381. Type *platform_type = integer_endian_type_to_platform_type(type);
  5382. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5383. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5384. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5385. return lb_emit_byte_swap(p, res, type);
  5386. }
  5387. handle_op:
  5388. lhs = lb_emit_conv(p, lhs, type);
  5389. rhs = lb_emit_conv(p, rhs, type);
  5390. lbValue res = {};
  5391. res.type = type;
  5392. // NOTE(bill): Bit Set Aliases for + and -
  5393. if (is_type_bit_set(type)) {
  5394. switch (op) {
  5395. case Token_Add: op = Token_Or; break;
  5396. case Token_Sub: op = Token_AndNot; break;
  5397. }
  5398. }
  5399. switch (op) {
  5400. case Token_Add:
  5401. if (is_type_float(type)) {
  5402. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5403. return res;
  5404. }
  5405. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5406. return res;
  5407. case Token_Sub:
  5408. if (is_type_float(type)) {
  5409. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5410. return res;
  5411. }
  5412. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5413. return res;
  5414. case Token_Mul:
  5415. if (is_type_float(type)) {
  5416. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5417. return res;
  5418. }
  5419. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5420. return res;
  5421. case Token_Quo:
  5422. if (is_type_float(type)) {
  5423. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5424. return res;
  5425. } else if (is_type_unsigned(type)) {
  5426. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5427. return res;
  5428. }
  5429. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5430. return res;
  5431. case Token_Mod:
  5432. if (is_type_float(type)) {
  5433. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5434. return res;
  5435. } else if (is_type_unsigned(type)) {
  5436. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5437. return res;
  5438. }
  5439. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5440. return res;
  5441. case Token_ModMod:
  5442. if (is_type_unsigned(type)) {
  5443. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5444. return res;
  5445. } else {
  5446. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5447. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5448. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5449. res.value = c;
  5450. return res;
  5451. }
  5452. case Token_And:
  5453. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5454. return res;
  5455. case Token_Or:
  5456. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5457. return res;
  5458. case Token_Xor:
  5459. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5460. return res;
  5461. case Token_Shl:
  5462. {
  5463. rhs = lb_emit_conv(p, rhs, lhs.type);
  5464. LLVMValueRef lhsval = lhs.value;
  5465. LLVMValueRef bits = rhs.value;
  5466. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5467. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULT, bits, max, "");
  5468. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5469. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5470. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  5471. return res;
  5472. }
  5473. case Token_Shr:
  5474. {
  5475. rhs = lb_emit_conv(p, rhs, lhs.type);
  5476. LLVMValueRef lhsval = lhs.value;
  5477. LLVMValueRef bits = rhs.value;
  5478. bool is_unsigned = is_type_unsigned(type);
  5479. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  5480. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULT, bits, max, "");
  5481. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  5482. if (is_unsigned) {
  5483. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  5484. } else {
  5485. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5486. }
  5487. return res;
  5488. }
  5489. case Token_AndNot:
  5490. {
  5491. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5492. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5493. return res;
  5494. }
  5495. break;
  5496. }
  5497. GB_PANIC("unhandled operator of lb_emit_arith");
  5498. return {};
  5499. }
  5500. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5501. ast_node(be, BinaryExpr, expr);
  5502. TypeAndValue tv = type_and_value_of_expr(expr);
  5503. switch (be->op.kind) {
  5504. case Token_Add:
  5505. case Token_Sub:
  5506. case Token_Mul:
  5507. case Token_Quo:
  5508. case Token_Mod:
  5509. case Token_ModMod:
  5510. case Token_And:
  5511. case Token_Or:
  5512. case Token_Xor:
  5513. case Token_AndNot:
  5514. case Token_Shl:
  5515. case Token_Shr: {
  5516. Type *type = default_type(tv.type);
  5517. lbValue left = lb_build_expr(p, be->left);
  5518. lbValue right = lb_build_expr(p, be->right);
  5519. return lb_emit_arith(p, be->op.kind, left, right, type);
  5520. }
  5521. case Token_CmpEq:
  5522. case Token_NotEq:
  5523. case Token_Lt:
  5524. case Token_LtEq:
  5525. case Token_Gt:
  5526. case Token_GtEq:
  5527. {
  5528. lbValue left = {};
  5529. lbValue right = {};
  5530. if (be->left->tav.mode == Addressing_Type) {
  5531. left = lb_typeid(p->module, be->left->tav.type);
  5532. }
  5533. if (be->right->tav.mode == Addressing_Type) {
  5534. right = lb_typeid(p->module, be->right->tav.type);
  5535. }
  5536. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5537. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5538. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5539. Type *type = default_type(tv.type);
  5540. return lb_emit_conv(p, cmp, type);
  5541. }
  5542. case Token_CmpAnd:
  5543. case Token_CmpOr:
  5544. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5545. case Token_in:
  5546. case Token_not_in:
  5547. {
  5548. lbValue left = lb_build_expr(p, be->left);
  5549. Type *type = default_type(tv.type);
  5550. lbValue right = lb_build_expr(p, be->right);
  5551. Type *rt = base_type(right.type);
  5552. switch (rt->kind) {
  5553. case Type_Map:
  5554. {
  5555. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5556. lbValue h = lb_gen_map_header(p, addr, rt);
  5557. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  5558. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5559. args[0] = h;
  5560. args[1] = key;
  5561. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5562. if (be->op.kind == Token_in) {
  5563. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5564. } else {
  5565. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5566. }
  5567. }
  5568. break;
  5569. case Type_BitSet:
  5570. {
  5571. Type *key_type = rt->BitSet.elem;
  5572. GB_ASSERT(are_types_identical(left.type, key_type));
  5573. Type *it = bit_set_to_int(rt);
  5574. left = lb_emit_conv(p, left, it);
  5575. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5576. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5577. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5578. bit = lb_emit_conv(p, bit, it);
  5579. lbValue old_value = lb_emit_transmute(p, right, it);
  5580. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5581. if (be->op.kind == Token_in) {
  5582. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5583. } else {
  5584. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5585. }
  5586. }
  5587. break;
  5588. default:
  5589. GB_PANIC("Invalid 'in' type");
  5590. }
  5591. break;
  5592. }
  5593. break;
  5594. default:
  5595. GB_PANIC("Invalid binary expression");
  5596. break;
  5597. }
  5598. return {};
  5599. }
  5600. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5601. Type *prev_src = src;
  5602. // Type *prev_dst = dst;
  5603. src = base_type(type_deref(src));
  5604. // dst = base_type(type_deref(dst));
  5605. bool src_is_ptr = src != prev_src;
  5606. // bool dst_is_ptr = dst != prev_dst;
  5607. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5608. for_array(i, src->Struct.fields) {
  5609. Entity *f = src->Struct.fields[i];
  5610. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5611. if (are_types_identical(dst, f->type)) {
  5612. return f->token.string;
  5613. }
  5614. if (src_is_ptr && is_type_pointer(dst)) {
  5615. if (are_types_identical(type_deref(dst), f->type)) {
  5616. return f->token.string;
  5617. }
  5618. }
  5619. if (is_type_struct(f->type)) {
  5620. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5621. if (name.len > 0) {
  5622. return name;
  5623. }
  5624. }
  5625. }
  5626. }
  5627. return str_lit("");
  5628. }
  5629. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5630. GB_ASSERT(is_type_pointer(value.type));
  5631. GB_ASSERT(is_type_pointer(t));
  5632. GB_ASSERT(lb_is_const(value));
  5633. lbValue res = {};
  5634. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5635. res.type = t;
  5636. return res;
  5637. }
  5638. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5639. lbModule *m = p->module;
  5640. t = reduce_tuple_to_single_type(t);
  5641. Type *src_type = value.type;
  5642. if (are_types_identical(t, src_type)) {
  5643. return value;
  5644. }
  5645. Type *src = core_type(src_type);
  5646. Type *dst = core_type(t);
  5647. GB_ASSERT(src != nullptr);
  5648. GB_ASSERT(dst != nullptr);
  5649. if (is_type_untyped_nil(src)) {
  5650. return lb_const_nil(m, t);
  5651. }
  5652. if (is_type_untyped_undef(src)) {
  5653. return lb_const_undef(m, t);
  5654. }
  5655. if (LLVMIsConstant(value.value)) {
  5656. if (is_type_any(dst)) {
  5657. Type *st = default_type(src_type);
  5658. lbAddr default_value = lb_add_local_generated(p, st, false);
  5659. lb_addr_store(p, default_value, value);
  5660. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5661. lbValue id = lb_typeid(m, st);
  5662. lbAddr res = lb_add_local_generated(p, t, false);
  5663. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5664. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5665. lb_emit_store(p, a0, data);
  5666. lb_emit_store(p, a1, id);
  5667. return lb_addr_load(p, res);
  5668. } else if (dst->kind == Type_Basic) {
  5669. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5670. String str = lb_get_const_string(m, value);
  5671. lbValue res = {};
  5672. res.type = t;
  5673. res.value = llvm_cstring(m, str);
  5674. return res;
  5675. }
  5676. // if (is_type_float(dst)) {
  5677. // return value;
  5678. // } else if (is_type_integer(dst)) {
  5679. // return value;
  5680. // }
  5681. // ExactValue ev = value->Constant.value;
  5682. // if (is_type_float(dst)) {
  5683. // ev = exact_value_to_float(ev);
  5684. // } else if (is_type_complex(dst)) {
  5685. // ev = exact_value_to_complex(ev);
  5686. // } else if (is_type_quaternion(dst)) {
  5687. // ev = exact_value_to_quaternion(ev);
  5688. // } else if (is_type_string(dst)) {
  5689. // // Handled elsewhere
  5690. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5691. // } else if (is_type_integer(dst)) {
  5692. // ev = exact_value_to_integer(ev);
  5693. // } else if (is_type_pointer(dst)) {
  5694. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5695. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5696. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5697. // }
  5698. // return lb_const_value(p->module, t, ev);
  5699. }
  5700. }
  5701. if (are_types_identical(src, dst)) {
  5702. if (!are_types_identical(src_type, t)) {
  5703. return lb_emit_transmute(p, value, t);
  5704. }
  5705. return value;
  5706. }
  5707. // bool <-> llvm bool
  5708. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5709. lbValue res = {};
  5710. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5711. res.type = dst;
  5712. return res;
  5713. }
  5714. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5715. lbValue res = {};
  5716. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5717. res.type = dst;
  5718. return res;
  5719. }
  5720. // integer -> integer
  5721. if (is_type_integer(src) && is_type_integer(dst)) {
  5722. GB_ASSERT(src->kind == Type_Basic &&
  5723. dst->kind == Type_Basic);
  5724. i64 sz = type_size_of(default_type(src));
  5725. i64 dz = type_size_of(default_type(dst));
  5726. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5727. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5728. value = lb_emit_byte_swap(p, value, platform_src_type);
  5729. }
  5730. LLVMOpcode op = LLVMTrunc;
  5731. if (dz < sz) {
  5732. op = LLVMTrunc;
  5733. } else if (dz == sz) {
  5734. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5735. // NOTE(bill): Copy the value just for type correctness
  5736. op = LLVMBitCast;
  5737. } else if (dz > sz) {
  5738. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5739. }
  5740. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5741. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5742. lbValue res = {};
  5743. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5744. res.type = t;
  5745. return lb_emit_byte_swap(p, res, t);
  5746. } else {
  5747. lbValue res = {};
  5748. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5749. res.type = t;
  5750. return res;
  5751. }
  5752. }
  5753. // boolean -> boolean/integer
  5754. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5755. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5756. lbValue res = {};
  5757. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5758. res.type = t;
  5759. return res;
  5760. }
  5761. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5762. return lb_emit_transmute(p, value, dst);
  5763. }
  5764. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5765. return lb_emit_transmute(p, value, dst);
  5766. }
  5767. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5768. return lb_emit_transmute(p, value, dst);
  5769. }
  5770. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5771. return lb_emit_transmute(p, value, dst);
  5772. }
  5773. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5774. lbValue c = lb_emit_conv(p, value, t_cstring);
  5775. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5776. args[0] = c;
  5777. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5778. return lb_emit_conv(p, s, dst);
  5779. }
  5780. // integer -> boolean
  5781. if (is_type_integer(src) && is_type_boolean(dst)) {
  5782. lbValue res = {};
  5783. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5784. res.type = t_llvm_bool;
  5785. return lb_emit_conv(p, res, t);
  5786. }
  5787. // float -> float
  5788. if (is_type_float(src) && is_type_float(dst)) {
  5789. i64 sz = type_size_of(src);
  5790. i64 dz = type_size_of(dst);
  5791. if (dz == sz) {
  5792. if (types_have_same_internal_endian(src, dst)) {
  5793. lbValue res = {};
  5794. res.type = t;
  5795. res.value = value.value;
  5796. return res;
  5797. } else {
  5798. return lb_emit_byte_swap(p, value, t);
  5799. }
  5800. }
  5801. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5802. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5803. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5804. lbValue res = {};
  5805. res = lb_emit_conv(p, value, platform_src_type);
  5806. res = lb_emit_conv(p, res, platform_dst_type);
  5807. if (is_type_different_to_arch_endianness(dst)) {
  5808. res = lb_emit_byte_swap(p, res, t);
  5809. }
  5810. return lb_emit_conv(p, res, t);
  5811. }
  5812. lbValue res = {};
  5813. res.type = t;
  5814. if (dz >= sz) {
  5815. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5816. } else {
  5817. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5818. }
  5819. return res;
  5820. }
  5821. if (is_type_complex(src) && is_type_complex(dst)) {
  5822. Type *ft = base_complex_elem_type(dst);
  5823. lbAddr gen = lb_add_local_generated(p, dst, false);
  5824. lbValue gp = lb_addr_get_ptr(p, gen);
  5825. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5826. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5827. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5828. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5829. return lb_addr_load(p, gen);
  5830. }
  5831. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5832. // @QuaternionLayout
  5833. Type *ft = base_complex_elem_type(dst);
  5834. lbAddr gen = lb_add_local_generated(p, dst, false);
  5835. lbValue gp = lb_addr_get_ptr(p, gen);
  5836. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5837. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5838. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5839. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5840. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5841. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5842. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5843. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5844. return lb_addr_load(p, gen);
  5845. }
  5846. if (is_type_float(src) && is_type_complex(dst)) {
  5847. Type *ft = base_complex_elem_type(dst);
  5848. lbAddr gen = lb_add_local_generated(p, dst, true);
  5849. lbValue gp = lb_addr_get_ptr(p, gen);
  5850. lbValue real = lb_emit_conv(p, value, ft);
  5851. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5852. return lb_addr_load(p, gen);
  5853. }
  5854. if (is_type_float(src) && is_type_quaternion(dst)) {
  5855. Type *ft = base_complex_elem_type(dst);
  5856. lbAddr gen = lb_add_local_generated(p, dst, true);
  5857. lbValue gp = lb_addr_get_ptr(p, gen);
  5858. lbValue real = lb_emit_conv(p, value, ft);
  5859. // @QuaternionLayout
  5860. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5861. return lb_addr_load(p, gen);
  5862. }
  5863. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5864. Type *ft = base_complex_elem_type(dst);
  5865. lbAddr gen = lb_add_local_generated(p, dst, true);
  5866. lbValue gp = lb_addr_get_ptr(p, gen);
  5867. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5868. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5869. // @QuaternionLayout
  5870. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5871. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5872. return lb_addr_load(p, gen);
  5873. }
  5874. // float <-> integer
  5875. if (is_type_float(src) && is_type_integer(dst)) {
  5876. lbValue res = {};
  5877. res.type = t;
  5878. if (is_type_unsigned(dst)) {
  5879. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5880. } else {
  5881. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5882. }
  5883. return res;
  5884. }
  5885. if (is_type_integer(src) && is_type_float(dst)) {
  5886. lbValue res = {};
  5887. res.type = t;
  5888. if (is_type_unsigned(src)) {
  5889. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5890. } else {
  5891. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5892. }
  5893. return res;
  5894. }
  5895. // Pointer <-> uintptr
  5896. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5897. lbValue res = {};
  5898. res.type = t;
  5899. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5900. return res;
  5901. }
  5902. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5903. lbValue res = {};
  5904. res.type = t;
  5905. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5906. return res;
  5907. }
  5908. #if 1
  5909. if (is_type_union(dst)) {
  5910. for_array(i, dst->Union.variants) {
  5911. Type *vt = dst->Union.variants[i];
  5912. if (are_types_identical(vt, src_type)) {
  5913. lbAddr parent = lb_add_local_generated(p, t, true);
  5914. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5915. return lb_addr_load(p, parent);
  5916. }
  5917. }
  5918. }
  5919. #endif
  5920. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5921. // subtype polymorphism casting
  5922. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5923. Type *st = type_deref(src_type);
  5924. Type *pst = st;
  5925. st = type_deref(st);
  5926. bool st_is_ptr = is_type_pointer(src_type);
  5927. st = base_type(st);
  5928. Type *dt = t;
  5929. bool dt_is_ptr = type_deref(dt) != dt;
  5930. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5931. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5932. if (field_name.len > 0) {
  5933. // NOTE(bill): It can be casted
  5934. Selection sel = lookup_field(st, field_name, false, true);
  5935. if (sel.entity != nullptr) {
  5936. if (st_is_ptr) {
  5937. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5938. Type *rt = res.type;
  5939. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5940. res = lb_emit_load(p, res);
  5941. }
  5942. return res;
  5943. } else {
  5944. if (is_type_pointer(value.type)) {
  5945. Type *rt = value.type;
  5946. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5947. value = lb_emit_load(p, value);
  5948. } else {
  5949. value = lb_emit_deep_field_gep(p, value, sel);
  5950. return lb_emit_load(p, value);
  5951. }
  5952. }
  5953. return lb_emit_deep_field_ev(p, value, sel);
  5954. }
  5955. } else {
  5956. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5957. }
  5958. }
  5959. }
  5960. // Pointer <-> Pointer
  5961. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5962. lbValue res = {};
  5963. res.type = t;
  5964. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5965. return res;
  5966. }
  5967. // proc <-> proc
  5968. if (is_type_proc(src) && is_type_proc(dst)) {
  5969. lbValue res = {};
  5970. res.type = t;
  5971. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5972. return res;
  5973. }
  5974. // pointer -> proc
  5975. if (is_type_pointer(src) && is_type_proc(dst)) {
  5976. lbValue res = {};
  5977. res.type = t;
  5978. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5979. return res;
  5980. }
  5981. // proc -> pointer
  5982. if (is_type_proc(src) && is_type_pointer(dst)) {
  5983. lbValue res = {};
  5984. res.type = t;
  5985. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5986. return res;
  5987. }
  5988. // []byte/[]u8 <-> string
  5989. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5990. return lb_emit_transmute(p, value, t);
  5991. }
  5992. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5993. return lb_emit_transmute(p, value, t);
  5994. }
  5995. if (is_type_array(dst)) {
  5996. Type *elem = dst->Array.elem;
  5997. lbValue e = lb_emit_conv(p, value, elem);
  5998. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5999. lbAddr v = lb_add_local_generated(p, t, false);
  6000. isize index_count = cast(isize)dst->Array.count;
  6001. for (isize i = 0; i < index_count; i++) {
  6002. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  6003. lb_emit_store(p, elem, e);
  6004. }
  6005. return lb_addr_load(p, v);
  6006. }
  6007. if (is_type_any(dst)) {
  6008. if (is_type_untyped_nil(src)) {
  6009. return lb_const_nil(p->module, t);
  6010. }
  6011. if (is_type_untyped_undef(src)) {
  6012. return lb_const_undef(p->module, t);
  6013. }
  6014. lbAddr result = lb_add_local_generated(p, t, true);
  6015. Type *st = default_type(src_type);
  6016. lbValue data = lb_address_from_load_or_generate_local(p, value);
  6017. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  6018. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  6019. data = lb_emit_conv(p, data, t_rawptr);
  6020. lbValue id = lb_typeid(p->module, st);
  6021. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  6022. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  6023. lb_emit_store(p, any_data, data);
  6024. lb_emit_store(p, any_id, id);
  6025. return lb_addr_load(p, result);
  6026. }
  6027. i64 src_sz = type_size_of(src);
  6028. i64 dst_sz = type_size_of(dst);
  6029. if (src_sz == dst_sz) {
  6030. // bit_set <-> integer
  6031. if (is_type_integer(src) && is_type_bit_set(dst)) {
  6032. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  6033. res.type = dst;
  6034. return res;
  6035. }
  6036. if (is_type_bit_set(src) && is_type_integer(dst)) {
  6037. lbValue bs = value;
  6038. bs.type = bit_set_to_int(src);
  6039. return lb_emit_conv(p, bs, dst);
  6040. }
  6041. // typeid <-> integer
  6042. if (is_type_integer(src) && is_type_typeid(dst)) {
  6043. return lb_emit_transmute(p, value, dst);
  6044. }
  6045. if (is_type_typeid(src) && is_type_integer(dst)) {
  6046. return lb_emit_transmute(p, value, dst);
  6047. }
  6048. }
  6049. if (is_type_untyped(src)) {
  6050. if (is_type_string(src) && is_type_string(dst)) {
  6051. lbAddr result = lb_add_local_generated(p, t, false);
  6052. lb_addr_store(p, result, value);
  6053. return lb_addr_load(p, result);
  6054. }
  6055. }
  6056. gb_printf_err("%.*s\n", LIT(p->name));
  6057. gb_printf_err("lb_emit_conv: src -> dst\n");
  6058. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  6059. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  6060. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  6061. gb_printf_err("Not Identical %p != %p\n", src, dst);
  6062. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  6063. type_to_string(src_type), type_to_string(t),
  6064. LIT(p->name));
  6065. return {};
  6066. }
  6067. bool lb_is_type_aggregate(Type *t) {
  6068. t = base_type(t);
  6069. switch (t->kind) {
  6070. case Type_Basic:
  6071. switch (t->Basic.kind) {
  6072. case Basic_string:
  6073. case Basic_any:
  6074. return true;
  6075. // case Basic_complex32:
  6076. case Basic_complex64:
  6077. case Basic_complex128:
  6078. case Basic_quaternion128:
  6079. case Basic_quaternion256:
  6080. return true;
  6081. }
  6082. break;
  6083. case Type_Pointer:
  6084. return false;
  6085. case Type_Array:
  6086. case Type_Slice:
  6087. case Type_Struct:
  6088. case Type_Union:
  6089. case Type_Tuple:
  6090. case Type_DynamicArray:
  6091. case Type_Map:
  6092. case Type_SimdVector:
  6093. return true;
  6094. case Type_Named:
  6095. return lb_is_type_aggregate(t->Named.base);
  6096. }
  6097. return false;
  6098. }
  6099. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  6100. Type *src_type = value.type;
  6101. if (are_types_identical(t, src_type)) {
  6102. return value;
  6103. }
  6104. lbValue res = {};
  6105. res.type = t;
  6106. Type *src = base_type(src_type);
  6107. Type *dst = base_type(t);
  6108. lbModule *m = p->module;
  6109. i64 sz = type_size_of(src);
  6110. i64 dz = type_size_of(dst);
  6111. if (sz != dz) {
  6112. LLVMTypeRef s = lb_type(m, src);
  6113. LLVMTypeRef d = lb_type(m, dst);
  6114. i64 llvm_sz = lb_sizeof(s);
  6115. i64 llvm_dz = lb_sizeof(d);
  6116. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  6117. }
  6118. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  6119. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  6120. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  6121. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6122. return res;
  6123. }
  6124. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  6125. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6126. return res;
  6127. }
  6128. if (is_type_uintptr(src) && is_type_proc(dst)) {
  6129. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6130. return res;
  6131. }
  6132. if (is_type_proc(src) && is_type_uintptr(dst)) {
  6133. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6134. return res;
  6135. }
  6136. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  6137. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  6138. return res;
  6139. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  6140. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  6141. return res;
  6142. }
  6143. if (is_type_pointer(src) && is_type_pointer(dst)) {
  6144. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  6145. return res;
  6146. }
  6147. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  6148. lbValue s = lb_address_from_load_or_generate_local(p, value);
  6149. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  6150. return lb_emit_load(p, d);
  6151. }
  6152. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  6153. // GB_PANIC("lb_emit_transmute");
  6154. return res;
  6155. }
  6156. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  6157. GB_ASSERT(addr.kind == lbAddr_Context);
  6158. GB_ASSERT(addr.ctx.sel.index.count == 0);
  6159. lbModule *m = p->module;
  6160. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6161. args[0] = addr.addr;
  6162. lb_emit_runtime_call(p, "__init_context", args);
  6163. }
  6164. lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  6165. Type *pt = base_type(p->type);
  6166. GB_ASSERT(pt->kind == Type_Proc);
  6167. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  6168. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  6169. e->flags |= EntityFlag_NoAlias;
  6170. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  6171. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  6172. lbValue param = {context_ptr, e->type};
  6173. lb_add_entity(p->module, e, param);
  6174. lbAddr ctx_addr = {};
  6175. ctx_addr.kind = lbAddr_Context;
  6176. ctx_addr.addr = param;
  6177. lbContextData *cd = array_add_and_get(&p->context_stack);
  6178. cd->ctx = ctx_addr;
  6179. cd->scope_index = -1;
  6180. return cd;
  6181. }
  6182. lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  6183. ctx.kind = lbAddr_Context;
  6184. lbContextData *cd = array_add_and_get(&p->context_stack);
  6185. cd->ctx = ctx;
  6186. cd->scope_index = p->scope_index;
  6187. return cd;
  6188. }
  6189. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  6190. if (p->context_stack.count > 0) {
  6191. return p->context_stack[p->context_stack.count-1].ctx;
  6192. }
  6193. Type *pt = base_type(p->type);
  6194. GB_ASSERT(pt->kind == Type_Proc);
  6195. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  6196. lbAddr c = lb_add_local_generated(p, t_context, true);
  6197. c.kind = lbAddr_Context;
  6198. lb_emit_init_context(p, c);
  6199. lb_push_context_onto_stack(p, c);
  6200. lb_add_debug_context_variable(p, c);
  6201. return c;
  6202. }
  6203. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  6204. if (LLVMIsALoadInst(value.value)) {
  6205. lbValue res = {};
  6206. res.value = LLVMGetOperand(value.value, 0);
  6207. res.type = alloc_type_pointer(value.type);
  6208. return res;
  6209. }
  6210. GB_ASSERT(is_type_typed(value.type));
  6211. lbAddr res = lb_add_local_generated(p, value.type, false);
  6212. lb_addr_store(p, res, value);
  6213. return res.addr;
  6214. }
  6215. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  6216. if (LLVMIsALoadInst(value.value)) {
  6217. lbValue res = {};
  6218. res.value = LLVMGetOperand(value.value, 0);
  6219. res.type = alloc_type_pointer(value.type);
  6220. return res;
  6221. }
  6222. GB_PANIC("lb_address_from_load");
  6223. return {};
  6224. }
  6225. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  6226. i64 type_alignment = type_align_of(new_type);
  6227. if (alignment < type_alignment) {
  6228. alignment = type_alignment;
  6229. }
  6230. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  6231. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  6232. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  6233. lb_addr_store(p, ptr, val);
  6234. // ptr.kind = lbAddr_Context;
  6235. return ptr.addr;
  6236. }
  6237. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  6238. GB_ASSERT(is_type_pointer(s.type));
  6239. Type *t = base_type(type_deref(s.type));
  6240. Type *result_type = nullptr;
  6241. if (is_type_relative_pointer(t)) {
  6242. s = lb_addr_get_ptr(p, lb_addr(s));
  6243. }
  6244. if (is_type_struct(t)) {
  6245. result_type = get_struct_field_type(t, index);
  6246. } else if (is_type_union(t)) {
  6247. GB_ASSERT(index == -1);
  6248. return lb_emit_union_tag_ptr(p, s);
  6249. } else if (is_type_tuple(t)) {
  6250. GB_ASSERT(t->Tuple.variables.count > 0);
  6251. result_type = t->Tuple.variables[index]->type;
  6252. } else if (is_type_complex(t)) {
  6253. Type *ft = base_complex_elem_type(t);
  6254. switch (index) {
  6255. case 0: result_type = ft; break;
  6256. case 1: result_type = ft; break;
  6257. }
  6258. } else if (is_type_quaternion(t)) {
  6259. Type *ft = base_complex_elem_type(t);
  6260. switch (index) {
  6261. case 0: result_type = ft; break;
  6262. case 1: result_type = ft; break;
  6263. case 2: result_type = ft; break;
  6264. case 3: result_type = ft; break;
  6265. }
  6266. } else if (is_type_slice(t)) {
  6267. switch (index) {
  6268. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6269. case 1: result_type = t_int; break;
  6270. }
  6271. } else if (is_type_string(t)) {
  6272. switch (index) {
  6273. case 0: result_type = t_u8_ptr; break;
  6274. case 1: result_type = t_int; break;
  6275. }
  6276. } else if (is_type_any(t)) {
  6277. switch (index) {
  6278. case 0: result_type = t_rawptr; break;
  6279. case 1: result_type = t_typeid; break;
  6280. }
  6281. } else if (is_type_dynamic_array(t)) {
  6282. switch (index) {
  6283. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6284. case 1: result_type = t_int; break;
  6285. case 2: result_type = t_int; break;
  6286. case 3: result_type = t_allocator; break;
  6287. }
  6288. } else if (is_type_map(t)) {
  6289. init_map_internal_types(t);
  6290. Type *itp = alloc_type_pointer(t->Map.internal_type);
  6291. s = lb_emit_transmute(p, s, itp);
  6292. Type *gst = t->Map.internal_type;
  6293. GB_ASSERT(gst->kind == Type_Struct);
  6294. switch (index) {
  6295. case 0: result_type = get_struct_field_type(gst, 0); break;
  6296. case 1: result_type = get_struct_field_type(gst, 1); break;
  6297. }
  6298. } else if (is_type_array(t)) {
  6299. return lb_emit_array_epi(p, s, index);
  6300. } else if (is_type_relative_slice(t)) {
  6301. switch (index) {
  6302. case 0: result_type = t->RelativeSlice.base_integer; break;
  6303. case 1: result_type = t->RelativeSlice.base_integer; break;
  6304. }
  6305. } else {
  6306. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  6307. }
  6308. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  6309. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6310. index += 1;
  6311. }
  6312. if (lb_is_const(s)) {
  6313. lbModule *m = p->module;
  6314. lbValue res = {};
  6315. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  6316. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6317. res.type = alloc_type_pointer(result_type);
  6318. return res;
  6319. } else {
  6320. lbValue res = {};
  6321. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  6322. res.type = alloc_type_pointer(result_type);
  6323. return res;
  6324. }
  6325. }
  6326. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  6327. if (LLVMIsALoadInst(s.value)) {
  6328. lbValue res = {};
  6329. res.value = LLVMGetOperand(s.value, 0);
  6330. res.type = alloc_type_pointer(s.type);
  6331. lbValue ptr = lb_emit_struct_ep(p, res, index);
  6332. return lb_emit_load(p, ptr);
  6333. }
  6334. Type *t = base_type(s.type);
  6335. Type *result_type = nullptr;
  6336. switch (t->kind) {
  6337. case Type_Basic:
  6338. switch (t->Basic.kind) {
  6339. case Basic_string:
  6340. switch (index) {
  6341. case 0: result_type = t_u8_ptr; break;
  6342. case 1: result_type = t_int; break;
  6343. }
  6344. break;
  6345. case Basic_any:
  6346. switch (index) {
  6347. case 0: result_type = t_rawptr; break;
  6348. case 1: result_type = t_typeid; break;
  6349. }
  6350. break;
  6351. case Basic_complex64: case Basic_complex128:
  6352. {
  6353. Type *ft = base_complex_elem_type(t);
  6354. switch (index) {
  6355. case 0: result_type = ft; break;
  6356. case 1: result_type = ft; break;
  6357. }
  6358. break;
  6359. }
  6360. case Basic_quaternion128: case Basic_quaternion256:
  6361. {
  6362. Type *ft = base_complex_elem_type(t);
  6363. switch (index) {
  6364. case 0: result_type = ft; break;
  6365. case 1: result_type = ft; break;
  6366. case 2: result_type = ft; break;
  6367. case 3: result_type = ft; break;
  6368. }
  6369. break;
  6370. }
  6371. }
  6372. break;
  6373. case Type_Struct:
  6374. result_type = get_struct_field_type(t, index);
  6375. break;
  6376. case Type_Union:
  6377. GB_ASSERT(index == -1);
  6378. // return lb_emit_union_tag_value(p, s);
  6379. GB_PANIC("lb_emit_union_tag_value");
  6380. case Type_Tuple:
  6381. GB_ASSERT(t->Tuple.variables.count > 0);
  6382. result_type = t->Tuple.variables[index]->type;
  6383. if (t->Tuple.variables.count == 1) {
  6384. return s;
  6385. }
  6386. break;
  6387. case Type_Slice:
  6388. switch (index) {
  6389. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  6390. case 1: result_type = t_int; break;
  6391. }
  6392. break;
  6393. case Type_DynamicArray:
  6394. switch (index) {
  6395. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  6396. case 1: result_type = t_int; break;
  6397. case 2: result_type = t_int; break;
  6398. case 3: result_type = t_allocator; break;
  6399. }
  6400. break;
  6401. case Type_Map:
  6402. {
  6403. init_map_internal_types(t);
  6404. Type *gst = t->Map.generated_struct_type;
  6405. switch (index) {
  6406. case 0: result_type = get_struct_field_type(gst, 0); break;
  6407. case 1: result_type = get_struct_field_type(gst, 1); break;
  6408. }
  6409. }
  6410. break;
  6411. case Type_Array:
  6412. result_type = t->Array.elem;
  6413. break;
  6414. default:
  6415. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6416. break;
  6417. }
  6418. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6419. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6420. index += 1;
  6421. }
  6422. lbValue res = {};
  6423. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6424. res.type = result_type;
  6425. return res;
  6426. }
  6427. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6428. GB_ASSERT(sel.index.count > 0);
  6429. Type *type = type_deref(e.type);
  6430. for_array(i, sel.index) {
  6431. i32 index = cast(i32)sel.index[i];
  6432. if (is_type_pointer(type)) {
  6433. type = type_deref(type);
  6434. e = lb_emit_load(p, e);
  6435. }
  6436. type = core_type(type);
  6437. if (is_type_quaternion(type)) {
  6438. e = lb_emit_struct_ep(p, e, index);
  6439. } else if (is_type_raw_union(type)) {
  6440. type = get_struct_field_type(type, index);
  6441. GB_ASSERT(is_type_pointer(e.type));
  6442. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6443. } else if (is_type_struct(type)) {
  6444. type = get_struct_field_type(type, index);
  6445. e = lb_emit_struct_ep(p, e, index);
  6446. } else if (type->kind == Type_Union) {
  6447. GB_ASSERT(index == -1);
  6448. type = t_type_info_ptr;
  6449. e = lb_emit_struct_ep(p, e, index);
  6450. } else if (type->kind == Type_Tuple) {
  6451. type = type->Tuple.variables[index]->type;
  6452. e = lb_emit_struct_ep(p, e, index);
  6453. } else if (type->kind == Type_Basic) {
  6454. switch (type->Basic.kind) {
  6455. case Basic_any: {
  6456. if (index == 0) {
  6457. type = t_rawptr;
  6458. } else if (index == 1) {
  6459. type = t_type_info_ptr;
  6460. }
  6461. e = lb_emit_struct_ep(p, e, index);
  6462. break;
  6463. }
  6464. case Basic_string:
  6465. e = lb_emit_struct_ep(p, e, index);
  6466. break;
  6467. default:
  6468. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6469. break;
  6470. }
  6471. } else if (type->kind == Type_Slice) {
  6472. e = lb_emit_struct_ep(p, e, index);
  6473. } else if (type->kind == Type_DynamicArray) {
  6474. e = lb_emit_struct_ep(p, e, index);
  6475. } else if (type->kind == Type_Array) {
  6476. e = lb_emit_array_epi(p, e, index);
  6477. } else if (type->kind == Type_Map) {
  6478. e = lb_emit_struct_ep(p, e, index);
  6479. } else if (type->kind == Type_RelativePointer) {
  6480. e = lb_emit_struct_ep(p, e, index);
  6481. } else {
  6482. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6483. }
  6484. }
  6485. return e;
  6486. }
  6487. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6488. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6489. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6490. return lb_emit_load(p, res);
  6491. }
  6492. void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  6493. // NOTE(bill): The prev block may defer injection before it's terminator
  6494. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6495. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6496. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6497. return;
  6498. }
  6499. isize prev_context_stack_count = p->context_stack.count;
  6500. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  6501. defer (p->context_stack.count = prev_context_stack_count);
  6502. p->context_stack.count = d.context_stack_count;
  6503. lbBlock *b = lb_create_block(p, "defer");
  6504. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6505. lb_emit_jump(p, b);
  6506. }
  6507. lb_start_block(p, b);
  6508. if (d.kind == lbDefer_Node) {
  6509. lb_build_stmt(p, d.stmt);
  6510. } else if (d.kind == lbDefer_Instr) {
  6511. // NOTE(bill): Need to make a new copy
  6512. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6513. LLVMInsertIntoBuilder(p->builder, instr);
  6514. } else if (d.kind == lbDefer_Proc) {
  6515. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6516. }
  6517. }
  6518. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6519. isize count = p->defer_stmts.count;
  6520. isize i = count;
  6521. while (i --> 0) {
  6522. lbDefer const &d = p->defer_stmts[i];
  6523. if (kind == lbDeferExit_Default) {
  6524. if (p->scope_index == d.scope_index &&
  6525. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6526. lb_build_defer_stmt(p, d);
  6527. array_pop(&p->defer_stmts);
  6528. continue;
  6529. } else {
  6530. break;
  6531. }
  6532. } else if (kind == lbDeferExit_Return) {
  6533. lb_build_defer_stmt(p, d);
  6534. } else if (kind == lbDeferExit_Branch) {
  6535. GB_ASSERT(block != nullptr);
  6536. isize lower_limit = block->scope_index;
  6537. if (lower_limit < d.scope_index) {
  6538. lb_build_defer_stmt(p, d);
  6539. }
  6540. }
  6541. }
  6542. }
  6543. void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6544. Type *pt = base_type(p->type);
  6545. GB_ASSERT(pt->kind == Type_Proc);
  6546. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6547. GB_ASSERT(p->context_stack.count != 0);
  6548. }
  6549. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6550. d->kind = lbDefer_Node;
  6551. d->scope_index = scope_index;
  6552. d->context_stack_count = p->context_stack.count;
  6553. d->block = p->curr_block;
  6554. d->stmt = stmt;
  6555. }
  6556. void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6557. Type *pt = base_type(p->type);
  6558. GB_ASSERT(pt->kind == Type_Proc);
  6559. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6560. GB_ASSERT(p->context_stack.count != 0);
  6561. }
  6562. lbDefer *d = array_add_and_get(&p->defer_stmts);
  6563. d->kind = lbDefer_Proc;
  6564. d->scope_index = p->scope_index;
  6565. d->block = p->curr_block;
  6566. d->context_stack_count = p->context_stack.count;
  6567. d->proc.deferred = deferred;
  6568. d->proc.result_as_args = result_as_args;
  6569. }
  6570. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6571. Array<lbValue> array = {};
  6572. Type *t = base_type(value.type);
  6573. if (t == nullptr) {
  6574. // Do nothing
  6575. } else if (is_type_tuple(t)) {
  6576. GB_ASSERT(t->kind == Type_Tuple);
  6577. auto *rt = &t->Tuple;
  6578. if (rt->variables.count > 0) {
  6579. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6580. for_array(i, rt->variables) {
  6581. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6582. array[i] = elem;
  6583. }
  6584. }
  6585. } else {
  6586. array = array_make<lbValue>(permanent_allocator(), 1);
  6587. array[0] = value;
  6588. }
  6589. return array;
  6590. }
  6591. 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) {
  6592. unsigned arg_count = cast(unsigned)processed_args.count;
  6593. if (return_ptr.value != nullptr) {
  6594. arg_count += 1;
  6595. }
  6596. if (context_ptr.addr.value != nullptr) {
  6597. arg_count += 1;
  6598. }
  6599. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6600. isize arg_index = 0;
  6601. if (return_ptr.value != nullptr) {
  6602. args[arg_index++] = return_ptr.value;
  6603. }
  6604. for_array(i, processed_args) {
  6605. lbValue arg = processed_args[i];
  6606. args[arg_index++] = arg.value;
  6607. }
  6608. if (context_ptr.addr.value != nullptr) {
  6609. LLVMValueRef cp = context_ptr.addr.value;
  6610. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  6611. args[arg_index++] = cp;
  6612. }
  6613. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6614. GB_ASSERT(curr_block != p->decl_block->block);
  6615. {
  6616. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6617. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6618. LLVMValueRef fn = value.value;
  6619. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6620. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6621. }
  6622. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6623. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6624. LLVMValueRef ret = LLVMBuildCall2(p->builder, ft, fn, args, arg_count, "");;
  6625. lbValue res = {};
  6626. res.value = ret;
  6627. res.type = abi_rt;
  6628. return res;
  6629. }
  6630. }
  6631. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6632. // LLVMMetadataRef curr_loc = LLVMGetCurrentDebugLocation2(p->builder);
  6633. // LLVMSetCurrentDebugLocation2(p->builder, nullptr);
  6634. // defer (if (curr_loc) {
  6635. // LLVMSetCurrentDebugLocation2(p->builder, curr_loc);
  6636. // });
  6637. String name = make_string_c(c_name);
  6638. AstPackage *pkg = p->module->info->runtime_package;
  6639. Entity *e = scope_lookup_current(pkg->scope, name);
  6640. lbValue *found = nullptr;
  6641. if (p->module != e->code_gen_module) {
  6642. gb_mutex_lock(&p->module->mutex);
  6643. }
  6644. GB_ASSERT(e->code_gen_module != nullptr);
  6645. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6646. if (p->module != e->code_gen_module) {
  6647. gb_mutex_unlock(&p->module->mutex);
  6648. }
  6649. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6650. return lb_emit_call(p, *found, args);
  6651. }
  6652. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6653. lbModule *m = p->module;
  6654. Type *pt = base_type(value.type);
  6655. GB_ASSERT(pt->kind == Type_Proc);
  6656. Type *results = pt->Proc.results;
  6657. if (p->entity != nullptr) {
  6658. if (p->entity->flags & EntityFlag_Disabled) {
  6659. return {};
  6660. }
  6661. }
  6662. lbAddr context_ptr = {};
  6663. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6664. context_ptr = lb_find_or_generate_context_ptr(p);
  6665. }
  6666. defer (if (pt->Proc.diverging) {
  6667. LLVMBuildUnreachable(p->builder);
  6668. });
  6669. set_procedure_abi_types(pt);
  6670. bool is_c_vararg = pt->Proc.c_vararg;
  6671. isize param_count = pt->Proc.param_count;
  6672. if (is_c_vararg) {
  6673. GB_ASSERT(param_count-1 <= args.count);
  6674. param_count -= 1;
  6675. } else {
  6676. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6677. }
  6678. lbValue result = {};
  6679. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6680. {
  6681. lbFunctionType **ft_found = nullptr;
  6682. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6683. if (!ft_found) {
  6684. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6685. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6686. }
  6687. GB_ASSERT(ft_found != nullptr);
  6688. lbFunctionType *ft = *ft_found;
  6689. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6690. unsigned param_index = 0;
  6691. for (isize i = 0; i < param_count; i++) {
  6692. Entity *e = pt->Proc.params->Tuple.variables[i];
  6693. if (e->kind != Entity_Variable) {
  6694. continue;
  6695. }
  6696. GB_ASSERT(e->flags & EntityFlag_Param);
  6697. Type *original_type = e->type;
  6698. lbArgType *arg = &ft->args[param_index];
  6699. if (arg->kind == lbArg_Ignore) {
  6700. continue;
  6701. }
  6702. lbValue x = lb_emit_conv(p, args[i], original_type);
  6703. LLVMTypeRef xt = lb_type(p->module, x.type);
  6704. if (arg->kind == lbArg_Direct) {
  6705. LLVMTypeRef abi_type = arg->cast_type;
  6706. if (!abi_type) {
  6707. abi_type = arg->type;
  6708. }
  6709. if (xt == abi_type) {
  6710. array_add(&processed_args, x);
  6711. } else {
  6712. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6713. array_add(&processed_args, x);
  6714. }
  6715. } else if (arg->kind == lbArg_Indirect) {
  6716. lbValue ptr = {};
  6717. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6718. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6719. // i.e. `T const &` in C++
  6720. ptr = lb_address_from_load_or_generate_local(p, x);
  6721. } else {
  6722. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6723. }
  6724. array_add(&processed_args, ptr);
  6725. }
  6726. param_index += 1;
  6727. }
  6728. if (inlining == ProcInlining_none) {
  6729. inlining = p->inlining;
  6730. }
  6731. Type *rt = reduce_tuple_to_single_type(results);
  6732. if (return_by_pointer) {
  6733. lbValue return_ptr = {};
  6734. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6735. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6736. return_ptr = p->return_ptr_hint_value;
  6737. p->return_ptr_hint_used = true;
  6738. }
  6739. }
  6740. if (return_ptr.value == nullptr) {
  6741. lbAddr r = lb_add_local_generated(p, rt, true);
  6742. return_ptr = r.addr;
  6743. }
  6744. GB_ASSERT(is_type_pointer(return_ptr.type));
  6745. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6746. result = lb_emit_load(p, return_ptr);
  6747. } else if (rt != nullptr) {
  6748. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6749. if (ft->ret.cast_type) {
  6750. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  6751. }
  6752. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  6753. result.type = rt;
  6754. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  6755. result.type = t_llvm_bool;
  6756. }
  6757. if (!is_type_tuple(rt)) {
  6758. result = lb_emit_conv(p, result, rt);
  6759. }
  6760. } else {
  6761. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6762. }
  6763. }
  6764. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6765. if (found != nullptr) {
  6766. Entity *e = *found;
  6767. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6768. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6769. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6770. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6771. GB_ASSERT(deferred_found != nullptr);
  6772. lbValue deferred = *deferred_found;
  6773. auto in_args = args;
  6774. Array<lbValue> result_as_args = {};
  6775. switch (kind) {
  6776. case DeferredProcedure_none:
  6777. break;
  6778. case DeferredProcedure_in:
  6779. result_as_args = in_args;
  6780. break;
  6781. case DeferredProcedure_out:
  6782. result_as_args = lb_value_to_array(p, result);
  6783. break;
  6784. case DeferredProcedure_in_out:
  6785. {
  6786. auto out_args = lb_value_to_array(p, result);
  6787. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6788. array_copy(&result_as_args, in_args, 0);
  6789. array_copy(&result_as_args, out_args, in_args.count);
  6790. }
  6791. break;
  6792. }
  6793. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6794. }
  6795. }
  6796. return result;
  6797. }
  6798. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6799. Type *t = s.type;
  6800. GB_ASSERT(is_type_pointer(t));
  6801. Type *st = base_type(type_deref(t));
  6802. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6803. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6804. LLVMValueRef indices[2] = {};
  6805. indices[0] = llvm_zero(p->module);
  6806. indices[1] = lb_emit_conv(p, index, t_int).value;
  6807. Type *ptr = base_array_type(st);
  6808. lbValue res = {};
  6809. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6810. res.type = alloc_type_pointer(ptr);
  6811. return res;
  6812. }
  6813. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6814. Type *t = s.type;
  6815. GB_ASSERT(is_type_pointer(t));
  6816. Type *st = base_type(type_deref(t));
  6817. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6818. GB_ASSERT(0 <= index);
  6819. Type *ptr = base_array_type(st);
  6820. LLVMValueRef indices[2] = {
  6821. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6822. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6823. };
  6824. lbValue res = {};
  6825. if (lb_is_const(s)) {
  6826. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6827. } else {
  6828. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6829. }
  6830. res.type = alloc_type_pointer(ptr);
  6831. return res;
  6832. }
  6833. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6834. LLVMValueRef indices[1] = {index.value};
  6835. lbValue res = {};
  6836. res.type = ptr.type;
  6837. if (lb_is_const(ptr) && lb_is_const(index)) {
  6838. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6839. } else {
  6840. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6841. }
  6842. return res;
  6843. }
  6844. LLVMValueRef llvm_const_slice(lbModule *m, lbValue data, lbValue len) {
  6845. GB_ASSERT(is_type_pointer(data.type));
  6846. GB_ASSERT(are_types_identical(len.type, t_int));
  6847. LLVMValueRef vals[2] = {
  6848. data.value,
  6849. len.value,
  6850. };
  6851. return LLVMConstStructInContext(m->ctx, vals, gb_count_of(vals), false);
  6852. }
  6853. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6854. Type *t = lb_addr_type(slice);
  6855. GB_ASSERT(is_type_slice(t));
  6856. lbValue ptr = lb_addr_get_ptr(p, slice);
  6857. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6858. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6859. }
  6860. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6861. Type *t = lb_addr_type(string);
  6862. GB_ASSERT(is_type_string(t));
  6863. lbValue ptr = lb_addr_get_ptr(p, string);
  6864. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6865. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6866. }
  6867. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6868. Type *t = base_type(string.type);
  6869. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6870. return lb_emit_struct_ev(p, string, 0);
  6871. }
  6872. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6873. Type *t = base_type(string.type);
  6874. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6875. return lb_emit_struct_ev(p, string, 1);
  6876. }
  6877. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6878. GB_ASSERT(is_type_cstring(value.type));
  6879. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6880. args[0] = lb_emit_conv(p, value, t_cstring);
  6881. return lb_emit_runtime_call(p, "cstring_len", args);
  6882. }
  6883. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6884. Type *t = type_deref(array_ptr.type);
  6885. GB_ASSERT(is_type_array(t));
  6886. return lb_emit_struct_ep(p, array_ptr, 0);
  6887. }
  6888. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6889. GB_ASSERT(is_type_slice(slice.type));
  6890. return lb_emit_struct_ev(p, slice, 0);
  6891. }
  6892. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6893. GB_ASSERT(is_type_slice(slice.type));
  6894. return lb_emit_struct_ev(p, slice, 1);
  6895. }
  6896. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6897. GB_ASSERT(is_type_dynamic_array(da.type));
  6898. return lb_emit_struct_ev(p, da, 0);
  6899. }
  6900. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6901. GB_ASSERT(is_type_dynamic_array(da.type));
  6902. return lb_emit_struct_ev(p, da, 1);
  6903. }
  6904. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6905. GB_ASSERT(is_type_dynamic_array(da.type));
  6906. return lb_emit_struct_ev(p, da, 2);
  6907. }
  6908. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6909. GB_ASSERT(is_type_dynamic_array(da.type));
  6910. return lb_emit_struct_ev(p, da, 3);
  6911. }
  6912. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6913. Type *t = base_type(value.type);
  6914. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6915. init_map_internal_types(t);
  6916. Type *gst = t->Map.generated_struct_type;
  6917. i32 index = 1;
  6918. lbValue entries = lb_emit_struct_ev(p, value, index);
  6919. return entries;
  6920. }
  6921. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6922. Type *t = base_type(type_deref(value.type));
  6923. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6924. init_map_internal_types(t);
  6925. Type *gst = t->Map.generated_struct_type;
  6926. i32 index = 1;
  6927. lbValue entries = lb_emit_struct_ep(p, value, index);
  6928. return entries;
  6929. }
  6930. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6931. lbValue entries = lb_map_entries(p, value);
  6932. return lb_dynamic_array_len(p, entries);
  6933. }
  6934. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6935. lbValue entries = lb_map_entries(p, value);
  6936. return lb_dynamic_array_cap(p, entries);
  6937. }
  6938. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6939. Type *t = base_type(value.type);
  6940. bool is_ptr = false;
  6941. if (is_type_pointer(t)) {
  6942. is_ptr = true;
  6943. t = base_type(type_deref(t));
  6944. }
  6945. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6946. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6947. }
  6948. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6949. t->Struct.soa_kind == StructSoa_Dynamic);
  6950. isize n = 0;
  6951. Type *elem = base_type(t->Struct.soa_elem);
  6952. if (elem->kind == Type_Struct) {
  6953. n = elem->Struct.fields.count;
  6954. } else if (elem->kind == Type_Array) {
  6955. n = elem->Array.count;
  6956. } else {
  6957. GB_PANIC("Unreachable");
  6958. }
  6959. if (is_ptr) {
  6960. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6961. return lb_emit_load(p, v);
  6962. }
  6963. return lb_emit_struct_ev(p, value, cast(i32)n);
  6964. }
  6965. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6966. Type *t = base_type(value.type);
  6967. bool is_ptr = false;
  6968. if (is_type_pointer(t)) {
  6969. is_ptr = true;
  6970. t = base_type(type_deref(t));
  6971. }
  6972. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6973. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6974. }
  6975. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6976. isize n = 0;
  6977. Type *elem = base_type(t->Struct.soa_elem);
  6978. if (elem->kind == Type_Struct) {
  6979. n = elem->Struct.fields.count+1;
  6980. } else if (elem->kind == Type_Array) {
  6981. n = elem->Array.count+1;
  6982. } else {
  6983. GB_PANIC("Unreachable");
  6984. }
  6985. if (is_ptr) {
  6986. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6987. return lb_emit_load(p, v);
  6988. }
  6989. return lb_emit_struct_ev(p, value, cast(i32)n);
  6990. }
  6991. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  6992. GB_ASSERT(ce->args.count > 0);
  6993. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  6994. for_array(i, slices) {
  6995. Ast *arg = ce->args[i];
  6996. if (arg->kind == Ast_FieldValue) {
  6997. arg = arg->FieldValue.value;
  6998. }
  6999. slices[i] = lb_build_expr(p, arg);
  7000. }
  7001. lbValue len = lb_slice_len(p, slices[0]);
  7002. for (isize i = 1; i < slices.count; i++) {
  7003. lbValue other_len = lb_slice_len(p, slices[i]);
  7004. len = lb_emit_min(p, t_int, len, other_len);
  7005. }
  7006. GB_ASSERT(is_type_soa_struct(tv.type));
  7007. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7008. for_array(i, slices) {
  7009. lbValue src = lb_slice_elem(p, slices[i]);
  7010. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  7011. lb_emit_store(p, dst, src);
  7012. }
  7013. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  7014. lb_emit_store(p, len_dst, len);
  7015. return lb_addr_load(p, res);
  7016. }
  7017. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  7018. GB_ASSERT(ce->args.count == 1);
  7019. lbValue arg = lb_build_expr(p, ce->args[0]);
  7020. Type *t = base_type(arg.type);
  7021. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  7022. lbValue len = lb_soa_struct_len(p, arg);
  7023. lbAddr res = lb_add_local_generated(p, tv.type, true);
  7024. if (is_type_tuple(tv.type)) {
  7025. lbValue rp = lb_addr_get_ptr(p, res);
  7026. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  7027. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  7028. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  7029. lb_fill_slice(p, dst, ptr, len);
  7030. }
  7031. } else {
  7032. GB_ASSERT(is_type_slice(tv.type));
  7033. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  7034. lb_fill_slice(p, res, ptr, len);
  7035. }
  7036. return lb_addr_load(p, res);
  7037. }
  7038. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  7039. ast_node(ce, CallExpr, expr);
  7040. switch (id) {
  7041. case BuiltinProc_DIRECTIVE: {
  7042. ast_node(bd, BasicDirective, ce->proc);
  7043. String name = bd->name;
  7044. GB_ASSERT(name == "location");
  7045. String procedure = p->entity->token.string;
  7046. TokenPos pos = ast_token(ce->proc).pos;
  7047. if (ce->args.count > 0) {
  7048. Ast *ident = unselector_expr(ce->args[0]);
  7049. GB_ASSERT(ident->kind == Ast_Ident);
  7050. Entity *e = entity_of_node(ident);
  7051. GB_ASSERT(e != nullptr);
  7052. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  7053. procedure = e->parent_proc_decl->entity->token.string;
  7054. } else {
  7055. procedure = str_lit("");
  7056. }
  7057. pos = e->token.pos;
  7058. }
  7059. return lb_emit_source_code_location(p, procedure, pos);
  7060. }
  7061. case BuiltinProc_type_info_of: {
  7062. Ast *arg = ce->args[0];
  7063. TypeAndValue tav = type_and_value_of_expr(arg);
  7064. if (tav.mode == Addressing_Type) {
  7065. Type *t = default_type(type_of_expr(arg));
  7066. return lb_type_info(p->module, t);
  7067. }
  7068. GB_ASSERT(is_type_typeid(tav.type));
  7069. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7070. args[0] = lb_build_expr(p, arg);
  7071. return lb_emit_runtime_call(p, "__type_info_of", args);
  7072. }
  7073. case BuiltinProc_typeid_of: {
  7074. Ast *arg = ce->args[0];
  7075. TypeAndValue tav = type_and_value_of_expr(arg);
  7076. GB_ASSERT(tav.mode == Addressing_Type);
  7077. Type *t = default_type(type_of_expr(arg));
  7078. return lb_typeid(p->module, t);
  7079. }
  7080. case BuiltinProc_len: {
  7081. lbValue v = lb_build_expr(p, ce->args[0]);
  7082. Type *t = base_type(v.type);
  7083. if (is_type_pointer(t)) {
  7084. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7085. v = lb_emit_load(p, v);
  7086. t = type_deref(t);
  7087. }
  7088. if (is_type_cstring(t)) {
  7089. return lb_cstring_len(p, v);
  7090. } else if (is_type_string(t)) {
  7091. return lb_string_len(p, v);
  7092. } else if (is_type_array(t)) {
  7093. GB_PANIC("Array lengths are constant");
  7094. } else if (is_type_slice(t)) {
  7095. return lb_slice_len(p, v);
  7096. } else if (is_type_dynamic_array(t)) {
  7097. return lb_dynamic_array_len(p, v);
  7098. } else if (is_type_map(t)) {
  7099. return lb_map_len(p, v);
  7100. } else if (is_type_soa_struct(t)) {
  7101. return lb_soa_struct_len(p, v);
  7102. }
  7103. GB_PANIC("Unreachable");
  7104. break;
  7105. }
  7106. case BuiltinProc_cap: {
  7107. lbValue v = lb_build_expr(p, ce->args[0]);
  7108. Type *t = base_type(v.type);
  7109. if (is_type_pointer(t)) {
  7110. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  7111. v = lb_emit_load(p, v);
  7112. t = type_deref(t);
  7113. }
  7114. if (is_type_string(t)) {
  7115. GB_PANIC("Unreachable");
  7116. } else if (is_type_array(t)) {
  7117. GB_PANIC("Array lengths are constant");
  7118. } else if (is_type_slice(t)) {
  7119. return lb_slice_len(p, v);
  7120. } else if (is_type_dynamic_array(t)) {
  7121. return lb_dynamic_array_cap(p, v);
  7122. } else if (is_type_map(t)) {
  7123. return lb_map_cap(p, v);
  7124. } else if (is_type_soa_struct(t)) {
  7125. return lb_soa_struct_cap(p, v);
  7126. }
  7127. GB_PANIC("Unreachable");
  7128. break;
  7129. }
  7130. case BuiltinProc_swizzle: {
  7131. isize index_count = ce->args.count-1;
  7132. if (is_type_simd_vector(tv.type)) {
  7133. lbValue vec = lb_build_expr(p, ce->args[0]);
  7134. if (index_count == 0) {
  7135. return vec;
  7136. }
  7137. unsigned mask_len = cast(unsigned)index_count;
  7138. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  7139. for (isize i = 1; i < ce->args.count; i++) {
  7140. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7141. GB_ASSERT(is_type_integer(tv.type));
  7142. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7143. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  7144. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  7145. }
  7146. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  7147. LLVMValueRef v1 = vec.value;
  7148. LLVMValueRef v2 = vec.value;
  7149. lbValue res = {};
  7150. res.type = tv.type;
  7151. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  7152. return res;
  7153. }
  7154. lbAddr addr = lb_build_addr(p, ce->args[0]);
  7155. if (index_count == 0) {
  7156. return lb_addr_load(p, addr);
  7157. }
  7158. lbValue src = lb_addr_get_ptr(p, addr);
  7159. // TODO(bill): Should this be zeroed or not?
  7160. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  7161. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  7162. for (i32 i = 1; i < ce->args.count; i++) {
  7163. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  7164. GB_ASSERT(is_type_integer(tv.type));
  7165. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  7166. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  7167. i32 dst_index = i-1;
  7168. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  7169. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  7170. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  7171. }
  7172. return lb_addr_load(p, dst);
  7173. }
  7174. case BuiltinProc_complex: {
  7175. lbValue real = lb_build_expr(p, ce->args[0]);
  7176. lbValue imag = lb_build_expr(p, ce->args[1]);
  7177. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7178. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7179. Type *ft = base_complex_elem_type(tv.type);
  7180. real = lb_emit_conv(p, real, ft);
  7181. imag = lb_emit_conv(p, imag, ft);
  7182. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  7183. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  7184. return lb_emit_load(p, dst);
  7185. }
  7186. case BuiltinProc_quaternion: {
  7187. lbValue real = lb_build_expr(p, ce->args[0]);
  7188. lbValue imag = lb_build_expr(p, ce->args[1]);
  7189. lbValue jmag = lb_build_expr(p, ce->args[2]);
  7190. lbValue kmag = lb_build_expr(p, ce->args[3]);
  7191. // @QuaternionLayout
  7192. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  7193. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  7194. Type *ft = base_complex_elem_type(tv.type);
  7195. real = lb_emit_conv(p, real, ft);
  7196. imag = lb_emit_conv(p, imag, ft);
  7197. jmag = lb_emit_conv(p, jmag, ft);
  7198. kmag = lb_emit_conv(p, kmag, ft);
  7199. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  7200. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  7201. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  7202. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  7203. return lb_emit_load(p, dst);
  7204. }
  7205. case BuiltinProc_real: {
  7206. lbValue val = lb_build_expr(p, ce->args[0]);
  7207. if (is_type_complex(val.type)) {
  7208. lbValue real = lb_emit_struct_ev(p, val, 0);
  7209. return lb_emit_conv(p, real, tv.type);
  7210. } else if (is_type_quaternion(val.type)) {
  7211. // @QuaternionLayout
  7212. lbValue real = lb_emit_struct_ev(p, val, 3);
  7213. return lb_emit_conv(p, real, tv.type);
  7214. }
  7215. GB_PANIC("invalid type for real");
  7216. return {};
  7217. }
  7218. case BuiltinProc_imag: {
  7219. lbValue val = lb_build_expr(p, ce->args[0]);
  7220. if (is_type_complex(val.type)) {
  7221. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7222. return lb_emit_conv(p, imag, tv.type);
  7223. } else if (is_type_quaternion(val.type)) {
  7224. // @QuaternionLayout
  7225. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7226. return lb_emit_conv(p, imag, tv.type);
  7227. }
  7228. GB_PANIC("invalid type for imag");
  7229. return {};
  7230. }
  7231. case BuiltinProc_jmag: {
  7232. lbValue val = lb_build_expr(p, ce->args[0]);
  7233. if (is_type_quaternion(val.type)) {
  7234. // @QuaternionLayout
  7235. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7236. return lb_emit_conv(p, imag, tv.type);
  7237. }
  7238. GB_PANIC("invalid type for jmag");
  7239. return {};
  7240. }
  7241. case BuiltinProc_kmag: {
  7242. lbValue val = lb_build_expr(p, ce->args[0]);
  7243. if (is_type_quaternion(val.type)) {
  7244. // @QuaternionLayout
  7245. lbValue imag = lb_emit_struct_ev(p, val, 2);
  7246. return lb_emit_conv(p, imag, tv.type);
  7247. }
  7248. GB_PANIC("invalid type for kmag");
  7249. return {};
  7250. }
  7251. case BuiltinProc_conj: {
  7252. lbValue val = lb_build_expr(p, ce->args[0]);
  7253. lbValue res = {};
  7254. Type *t = val.type;
  7255. if (is_type_complex(t)) {
  7256. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7257. lbValue real = lb_emit_struct_ev(p, val, 0);
  7258. lbValue imag = lb_emit_struct_ev(p, val, 1);
  7259. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7260. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  7261. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  7262. } else if (is_type_quaternion(t)) {
  7263. // @QuaternionLayout
  7264. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7265. lbValue real = lb_emit_struct_ev(p, val, 3);
  7266. lbValue imag = lb_emit_struct_ev(p, val, 0);
  7267. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  7268. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  7269. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  7270. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  7271. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  7272. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  7273. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  7274. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  7275. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  7276. }
  7277. return lb_emit_load(p, res);
  7278. }
  7279. case BuiltinProc_expand_to_tuple: {
  7280. lbValue val = lb_build_expr(p, ce->args[0]);
  7281. Type *t = base_type(val.type);
  7282. if (!is_type_tuple(tv.type)) {
  7283. if (t->kind == Type_Struct) {
  7284. GB_ASSERT(t->Struct.fields.count == 1);
  7285. return lb_emit_struct_ev(p, val, 0);
  7286. } else if (t->kind == Type_Array) {
  7287. GB_ASSERT(t->Array.count == 1);
  7288. return lb_emit_array_epi(p, val, 0);
  7289. } else {
  7290. GB_PANIC("Unknown type of expand_to_tuple");
  7291. }
  7292. }
  7293. GB_ASSERT(is_type_tuple(tv.type));
  7294. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  7295. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  7296. if (t->kind == Type_Struct) {
  7297. for_array(src_index, t->Struct.fields) {
  7298. Entity *field = t->Struct.fields[src_index];
  7299. i32 field_index = field->Variable.field_index;
  7300. lbValue f = lb_emit_struct_ev(p, val, field_index);
  7301. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  7302. lb_emit_store(p, ep, f);
  7303. }
  7304. } else if (t->kind == Type_Array) {
  7305. // TODO(bill): Clean-up this code
  7306. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  7307. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  7308. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  7309. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  7310. lb_emit_store(p, ep, f);
  7311. }
  7312. } else {
  7313. GB_PANIC("Unknown type of expand_to_tuple");
  7314. }
  7315. return lb_emit_load(p, tuple);
  7316. }
  7317. case BuiltinProc_min: {
  7318. Type *t = type_of_expr(expr);
  7319. if (ce->args.count == 2) {
  7320. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7321. } else {
  7322. lbValue x = lb_build_expr(p, ce->args[0]);
  7323. for (isize i = 1; i < ce->args.count; i++) {
  7324. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  7325. }
  7326. return x;
  7327. }
  7328. }
  7329. case BuiltinProc_max: {
  7330. Type *t = type_of_expr(expr);
  7331. if (ce->args.count == 2) {
  7332. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  7333. } else {
  7334. lbValue x = lb_build_expr(p, ce->args[0]);
  7335. for (isize i = 1; i < ce->args.count; i++) {
  7336. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  7337. }
  7338. return x;
  7339. }
  7340. }
  7341. case BuiltinProc_abs: {
  7342. lbValue x = lb_build_expr(p, ce->args[0]);
  7343. Type *t = x.type;
  7344. if (is_type_unsigned(t)) {
  7345. return x;
  7346. }
  7347. if (is_type_quaternion(t)) {
  7348. i64 sz = 8*type_size_of(t);
  7349. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7350. args[0] = x;
  7351. switch (sz) {
  7352. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  7353. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  7354. }
  7355. GB_PANIC("Unknown complex type");
  7356. } else if (is_type_complex(t)) {
  7357. i64 sz = 8*type_size_of(t);
  7358. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7359. args[0] = x;
  7360. switch (sz) {
  7361. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  7362. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  7363. }
  7364. GB_PANIC("Unknown complex type");
  7365. } else if (is_type_float(t)) {
  7366. i64 sz = 8*type_size_of(t);
  7367. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7368. args[0] = x;
  7369. switch (sz) {
  7370. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7371. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7372. }
  7373. GB_PANIC("Unknown float type");
  7374. }
  7375. lbValue zero = lb_const_nil(p->module, t);
  7376. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7377. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7378. return lb_emit_select(p, cond, neg, x);
  7379. }
  7380. case BuiltinProc_clamp:
  7381. return lb_emit_clamp(p, type_of_expr(expr),
  7382. lb_build_expr(p, ce->args[0]),
  7383. lb_build_expr(p, ce->args[1]),
  7384. lb_build_expr(p, ce->args[2]));
  7385. case BuiltinProc_soa_zip:
  7386. return lb_soa_zip(p, ce, tv);
  7387. case BuiltinProc_soa_unzip:
  7388. return lb_soa_unzip(p, ce, tv);
  7389. // "Intrinsics"
  7390. case BuiltinProc_alloca:
  7391. {
  7392. lbValue sz = lb_build_expr(p, ce->args[0]);
  7393. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7394. lbValue res = {};
  7395. res.type = t_u8_ptr;
  7396. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7397. LLVMSetAlignment(res.value, cast(unsigned)al);
  7398. return res;
  7399. }
  7400. case BuiltinProc_cpu_relax:
  7401. if (build_context.metrics.arch == TargetArch_386 ||
  7402. build_context.metrics.arch == TargetArch_amd64) {
  7403. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7404. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7405. cast(char *)"pause", 5,
  7406. cast(char *)"", 0,
  7407. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7408. LLVMInlineAsmDialectATT
  7409. );
  7410. GB_ASSERT(the_asm != nullptr);
  7411. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7412. }
  7413. return {};
  7414. case BuiltinProc_atomic_fence:
  7415. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7416. return {};
  7417. case BuiltinProc_atomic_fence_acq:
  7418. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7419. return {};
  7420. case BuiltinProc_atomic_fence_rel:
  7421. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7422. return {};
  7423. case BuiltinProc_atomic_fence_acqrel:
  7424. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7425. return {};
  7426. case BuiltinProc_volatile_store:
  7427. case BuiltinProc_atomic_store:
  7428. case BuiltinProc_atomic_store_rel:
  7429. case BuiltinProc_atomic_store_relaxed:
  7430. case BuiltinProc_atomic_store_unordered: {
  7431. lbValue dst = lb_build_expr(p, ce->args[0]);
  7432. lbValue val = lb_build_expr(p, ce->args[1]);
  7433. val = lb_emit_conv(p, val, type_deref(dst.type));
  7434. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7435. switch (id) {
  7436. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  7437. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7438. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7439. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7440. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7441. }
  7442. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7443. return {};
  7444. }
  7445. case BuiltinProc_volatile_load:
  7446. case BuiltinProc_atomic_load:
  7447. case BuiltinProc_atomic_load_acq:
  7448. case BuiltinProc_atomic_load_relaxed:
  7449. case BuiltinProc_atomic_load_unordered: {
  7450. lbValue dst = lb_build_expr(p, ce->args[0]);
  7451. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7452. switch (id) {
  7453. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  7454. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7455. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7456. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7457. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7458. }
  7459. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7460. lbValue res = {};
  7461. res.value = instr;
  7462. res.type = type_deref(dst.type);
  7463. return res;
  7464. }
  7465. case BuiltinProc_atomic_add:
  7466. case BuiltinProc_atomic_add_acq:
  7467. case BuiltinProc_atomic_add_rel:
  7468. case BuiltinProc_atomic_add_acqrel:
  7469. case BuiltinProc_atomic_add_relaxed:
  7470. case BuiltinProc_atomic_sub:
  7471. case BuiltinProc_atomic_sub_acq:
  7472. case BuiltinProc_atomic_sub_rel:
  7473. case BuiltinProc_atomic_sub_acqrel:
  7474. case BuiltinProc_atomic_sub_relaxed:
  7475. case BuiltinProc_atomic_and:
  7476. case BuiltinProc_atomic_and_acq:
  7477. case BuiltinProc_atomic_and_rel:
  7478. case BuiltinProc_atomic_and_acqrel:
  7479. case BuiltinProc_atomic_and_relaxed:
  7480. case BuiltinProc_atomic_nand:
  7481. case BuiltinProc_atomic_nand_acq:
  7482. case BuiltinProc_atomic_nand_rel:
  7483. case BuiltinProc_atomic_nand_acqrel:
  7484. case BuiltinProc_atomic_nand_relaxed:
  7485. case BuiltinProc_atomic_or:
  7486. case BuiltinProc_atomic_or_acq:
  7487. case BuiltinProc_atomic_or_rel:
  7488. case BuiltinProc_atomic_or_acqrel:
  7489. case BuiltinProc_atomic_or_relaxed:
  7490. case BuiltinProc_atomic_xor:
  7491. case BuiltinProc_atomic_xor_acq:
  7492. case BuiltinProc_atomic_xor_rel:
  7493. case BuiltinProc_atomic_xor_acqrel:
  7494. case BuiltinProc_atomic_xor_relaxed:
  7495. case BuiltinProc_atomic_xchg:
  7496. case BuiltinProc_atomic_xchg_acq:
  7497. case BuiltinProc_atomic_xchg_rel:
  7498. case BuiltinProc_atomic_xchg_acqrel:
  7499. case BuiltinProc_atomic_xchg_relaxed: {
  7500. lbValue dst = lb_build_expr(p, ce->args[0]);
  7501. lbValue val = lb_build_expr(p, ce->args[1]);
  7502. val = lb_emit_conv(p, val, type_deref(dst.type));
  7503. LLVMAtomicRMWBinOp op = {};
  7504. LLVMAtomicOrdering ordering = {};
  7505. switch (id) {
  7506. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7507. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7508. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7509. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7510. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7511. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7512. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7513. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7514. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7515. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7516. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7517. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7518. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7519. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7520. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7521. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7522. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7523. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7524. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7525. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7526. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7527. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7528. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7529. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7530. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7531. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7532. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7533. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7534. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7535. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7536. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7537. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7538. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7539. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7540. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7541. }
  7542. lbValue res = {};
  7543. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7544. res.type = tv.type;
  7545. return res;
  7546. }
  7547. case BuiltinProc_atomic_cxchg:
  7548. case BuiltinProc_atomic_cxchg_acq:
  7549. case BuiltinProc_atomic_cxchg_rel:
  7550. case BuiltinProc_atomic_cxchg_acqrel:
  7551. case BuiltinProc_atomic_cxchg_relaxed:
  7552. case BuiltinProc_atomic_cxchg_failrelaxed:
  7553. case BuiltinProc_atomic_cxchg_failacq:
  7554. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7555. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7556. case BuiltinProc_atomic_cxchgweak:
  7557. case BuiltinProc_atomic_cxchgweak_acq:
  7558. case BuiltinProc_atomic_cxchgweak_rel:
  7559. case BuiltinProc_atomic_cxchgweak_acqrel:
  7560. case BuiltinProc_atomic_cxchgweak_relaxed:
  7561. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7562. case BuiltinProc_atomic_cxchgweak_failacq:
  7563. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7564. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7565. Type *type = expr->tav.type;
  7566. lbValue address = lb_build_expr(p, ce->args[0]);
  7567. Type *elem = type_deref(address.type);
  7568. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7569. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7570. old_value = lb_emit_conv(p, old_value, elem);
  7571. new_value = lb_emit_conv(p, new_value, elem);
  7572. LLVMAtomicOrdering success_ordering = {};
  7573. LLVMAtomicOrdering failure_ordering = {};
  7574. LLVMBool weak = false;
  7575. switch (id) {
  7576. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7577. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7578. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7579. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7580. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7581. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7582. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7583. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7584. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7585. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7586. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7587. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7588. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7589. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7590. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7591. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7592. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7593. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7594. }
  7595. // TODO(bill): Figure out how to make it weak
  7596. LLVMBool single_threaded = weak;
  7597. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7598. p->builder, address.value,
  7599. old_value.value, new_value.value,
  7600. success_ordering,
  7601. failure_ordering,
  7602. single_threaded
  7603. );
  7604. GB_ASSERT(tv.type->kind == Type_Tuple);
  7605. Type *fix_typed = alloc_type_tuple();
  7606. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7607. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7608. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7609. lbValue res = {};
  7610. res.value = value;
  7611. res.type = fix_typed;
  7612. return res;
  7613. }
  7614. case BuiltinProc_type_equal_proc:
  7615. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  7616. case BuiltinProc_type_hasher_proc:
  7617. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  7618. }
  7619. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  7620. return {};
  7621. }
  7622. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  7623. switch (param_value.kind) {
  7624. case ParameterValue_Constant:
  7625. if (is_type_constant_type(parameter_type)) {
  7626. return lb_const_value(p->module, parameter_type, param_value.value);
  7627. } else {
  7628. ExactValue ev = param_value.value;
  7629. lbValue arg = {};
  7630. Type *type = type_of_expr(param_value.original_ast_expr);
  7631. if (type != nullptr) {
  7632. arg = lb_const_value(p->module, type, ev);
  7633. } else {
  7634. arg = lb_const_value(p->module, parameter_type, param_value.value);
  7635. }
  7636. return lb_emit_conv(p, arg, parameter_type);
  7637. }
  7638. case ParameterValue_Nil:
  7639. return lb_const_nil(p->module, parameter_type);
  7640. case ParameterValue_Location:
  7641. {
  7642. String proc_name = {};
  7643. if (p->entity != nullptr) {
  7644. proc_name = p->entity->token.string;
  7645. }
  7646. return lb_emit_source_code_location(p, proc_name, pos);
  7647. }
  7648. case ParameterValue_Value:
  7649. return lb_build_expr(p, param_value.ast_value);
  7650. }
  7651. return lb_const_nil(p->module, parameter_type);
  7652. }
  7653. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  7654. lbModule *m = p->module;
  7655. TypeAndValue tv = type_and_value_of_expr(expr);
  7656. ast_node(ce, CallExpr, expr);
  7657. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  7658. AddressingMode proc_mode = proc_tv.mode;
  7659. if (proc_mode == Addressing_Type) {
  7660. GB_ASSERT(ce->args.count == 1);
  7661. lbValue x = lb_build_expr(p, ce->args[0]);
  7662. lbValue y = lb_emit_conv(p, x, tv.type);
  7663. return y;
  7664. }
  7665. Ast *pexpr = unparen_expr(ce->proc);
  7666. if (proc_mode == Addressing_Builtin) {
  7667. Entity *e = entity_of_node(pexpr);
  7668. BuiltinProcId id = BuiltinProc_Invalid;
  7669. if (e != nullptr) {
  7670. id = cast(BuiltinProcId)e->Builtin.id;
  7671. } else {
  7672. id = BuiltinProc_DIRECTIVE;
  7673. }
  7674. return lb_build_builtin_proc(p, expr, tv, id);
  7675. }
  7676. // NOTE(bill): Regular call
  7677. lbValue value = {};
  7678. Ast *proc_expr = unparen_expr(ce->proc);
  7679. if (proc_expr->tav.mode == Addressing_Constant) {
  7680. ExactValue v = proc_expr->tav.value;
  7681. switch (v.kind) {
  7682. case ExactValue_Integer:
  7683. {
  7684. u64 u = big_int_to_u64(&v.value_integer);
  7685. lbValue x = {};
  7686. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7687. x.type = t_uintptr;
  7688. x = lb_emit_conv(p, x, t_rawptr);
  7689. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7690. break;
  7691. }
  7692. case ExactValue_Pointer:
  7693. {
  7694. u64 u = cast(u64)v.value_pointer;
  7695. lbValue x = {};
  7696. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7697. x.type = t_uintptr;
  7698. x = lb_emit_conv(p, x, t_rawptr);
  7699. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7700. break;
  7701. }
  7702. }
  7703. }
  7704. if (value.value == nullptr) {
  7705. value = lb_build_expr(p, proc_expr);
  7706. }
  7707. GB_ASSERT(value.value != nullptr);
  7708. Type *proc_type_ = base_type(value.type);
  7709. GB_ASSERT(proc_type_->kind == Type_Proc);
  7710. TypeProc *pt = &proc_type_->Proc;
  7711. set_procedure_abi_types(proc_type_);
  7712. if (is_call_expr_field_value(ce)) {
  7713. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7714. for_array(arg_index, ce->args) {
  7715. Ast *arg = ce->args[arg_index];
  7716. ast_node(fv, FieldValue, arg);
  7717. GB_ASSERT(fv->field->kind == Ast_Ident);
  7718. String name = fv->field->Ident.token.string;
  7719. isize index = lookup_procedure_parameter(pt, name);
  7720. GB_ASSERT(index >= 0);
  7721. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7722. if (tav.mode == Addressing_Type) {
  7723. args[index] = lb_const_nil(m, tav.type);
  7724. } else {
  7725. args[index] = lb_build_expr(p, fv->value);
  7726. }
  7727. }
  7728. TypeTuple *params = &pt->params->Tuple;
  7729. for (isize i = 0; i < args.count; i++) {
  7730. Entity *e = params->variables[i];
  7731. if (e->kind == Entity_TypeName) {
  7732. args[i] = lb_const_nil(m, e->type);
  7733. } else if (e->kind == Entity_Constant) {
  7734. continue;
  7735. } else {
  7736. GB_ASSERT(e->kind == Entity_Variable);
  7737. if (args[i].value == nullptr) {
  7738. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7739. } else {
  7740. args[i] = lb_emit_conv(p, args[i], e->type);
  7741. }
  7742. }
  7743. }
  7744. for (isize i = 0; i < args.count; i++) {
  7745. Entity *e = params->variables[i];
  7746. if (args[i].type == nullptr) {
  7747. continue;
  7748. } else if (is_type_untyped_nil(args[i].type)) {
  7749. args[i] = lb_const_nil(m, e->type);
  7750. } else if (is_type_untyped_undef(args[i].type)) {
  7751. args[i] = lb_const_undef(m, e->type);
  7752. }
  7753. }
  7754. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7755. }
  7756. isize arg_index = 0;
  7757. isize arg_count = 0;
  7758. for_array(i, ce->args) {
  7759. Ast *arg = ce->args[i];
  7760. TypeAndValue tav = type_and_value_of_expr(arg);
  7761. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7762. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7763. Type *at = tav.type;
  7764. if (at->kind == Type_Tuple) {
  7765. arg_count += at->Tuple.variables.count;
  7766. } else {
  7767. arg_count++;
  7768. }
  7769. }
  7770. isize param_count = 0;
  7771. if (pt->params) {
  7772. GB_ASSERT(pt->params->kind == Type_Tuple);
  7773. param_count = pt->params->Tuple.variables.count;
  7774. }
  7775. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  7776. isize variadic_index = pt->variadic_index;
  7777. bool variadic = pt->variadic && variadic_index >= 0;
  7778. bool vari_expand = ce->ellipsis.pos.line != 0;
  7779. bool is_c_vararg = pt->c_vararg;
  7780. String proc_name = {};
  7781. if (p->entity != nullptr) {
  7782. proc_name = p->entity->token.string;
  7783. }
  7784. TokenPos pos = ast_token(ce->proc).pos;
  7785. TypeTuple *param_tuple = nullptr;
  7786. if (pt->params) {
  7787. GB_ASSERT(pt->params->kind == Type_Tuple);
  7788. param_tuple = &pt->params->Tuple;
  7789. }
  7790. for_array(i, ce->args) {
  7791. Ast *arg = ce->args[i];
  7792. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  7793. if (arg_tv.mode == Addressing_Type) {
  7794. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  7795. } else {
  7796. lbValue a = lb_build_expr(p, arg);
  7797. Type *at = a.type;
  7798. if (at->kind == Type_Tuple) {
  7799. for_array(i, at->Tuple.variables) {
  7800. Entity *e = at->Tuple.variables[i];
  7801. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7802. args[arg_index++] = v;
  7803. }
  7804. } else {
  7805. args[arg_index++] = a;
  7806. }
  7807. }
  7808. }
  7809. if (param_count > 0) {
  7810. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7811. GB_ASSERT(param_count < 1000000);
  7812. if (arg_count < param_count) {
  7813. isize end = cast(isize)param_count;
  7814. if (variadic) {
  7815. end = variadic_index;
  7816. }
  7817. while (arg_index < end) {
  7818. Entity *e = param_tuple->variables[arg_index];
  7819. GB_ASSERT(e->kind == Entity_Variable);
  7820. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7821. }
  7822. }
  7823. if (is_c_vararg) {
  7824. GB_ASSERT(variadic);
  7825. GB_ASSERT(!vari_expand);
  7826. isize i = 0;
  7827. for (; i < variadic_index; i++) {
  7828. Entity *e = param_tuple->variables[i];
  7829. if (e->kind == Entity_Variable) {
  7830. args[i] = lb_emit_conv(p, args[i], e->type);
  7831. }
  7832. }
  7833. Type *variadic_type = param_tuple->variables[i]->type;
  7834. GB_ASSERT(is_type_slice(variadic_type));
  7835. variadic_type = base_type(variadic_type)->Slice.elem;
  7836. if (!is_type_any(variadic_type)) {
  7837. for (; i < arg_count; i++) {
  7838. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7839. }
  7840. } else {
  7841. for (; i < arg_count; i++) {
  7842. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7843. }
  7844. }
  7845. } else if (variadic) {
  7846. isize i = 0;
  7847. for (; i < variadic_index; i++) {
  7848. Entity *e = param_tuple->variables[i];
  7849. if (e->kind == Entity_Variable) {
  7850. args[i] = lb_emit_conv(p, args[i], e->type);
  7851. }
  7852. }
  7853. if (!vari_expand) {
  7854. Type *variadic_type = param_tuple->variables[i]->type;
  7855. GB_ASSERT(is_type_slice(variadic_type));
  7856. variadic_type = base_type(variadic_type)->Slice.elem;
  7857. for (; i < arg_count; i++) {
  7858. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7859. }
  7860. }
  7861. } else {
  7862. for (isize i = 0; i < param_count; i++) {
  7863. Entity *e = param_tuple->variables[i];
  7864. if (e->kind == Entity_Variable) {
  7865. if (args[i].value == nullptr) {
  7866. continue;
  7867. }
  7868. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7869. args[i] = lb_emit_conv(p, args[i], e->type);
  7870. }
  7871. }
  7872. }
  7873. if (variadic && !vari_expand && !is_c_vararg) {
  7874. // variadic call argument generation
  7875. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7876. Type *elem_type = base_type(slice_type)->Slice.elem;
  7877. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7878. isize slice_len = arg_count+1 - (variadic_index+1);
  7879. if (slice_len > 0) {
  7880. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7881. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7882. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7883. lb_emit_store(p, addr, args[i]);
  7884. }
  7885. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7886. lbValue len = lb_const_int(m, t_int, slice_len);
  7887. lb_fill_slice(p, slice, base_elem, len);
  7888. }
  7889. arg_count = param_count;
  7890. args[variadic_index] = lb_addr_load(p, slice);
  7891. }
  7892. }
  7893. if (variadic && variadic_index+1 < param_count) {
  7894. for (isize i = variadic_index+1; i < param_count; i++) {
  7895. Entity *e = param_tuple->variables[i];
  7896. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7897. }
  7898. }
  7899. isize final_count = param_count;
  7900. if (is_c_vararg) {
  7901. final_count = arg_count;
  7902. }
  7903. if (param_tuple != nullptr) {
  7904. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7905. Entity *e = param_tuple->variables[i];
  7906. if (args[i].type == nullptr) {
  7907. continue;
  7908. } else if (is_type_untyped_nil(args[i].type)) {
  7909. args[i] = lb_const_nil(m, e->type);
  7910. } else if (is_type_untyped_undef(args[i].type)) {
  7911. args[i] = lb_const_undef(m, e->type);
  7912. }
  7913. }
  7914. }
  7915. auto call_args = array_slice(args, 0, final_count);
  7916. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7917. }
  7918. bool lb_is_const(lbValue value) {
  7919. LLVMValueRef v = value.value;
  7920. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7921. // TODO(bill): Is this correct behaviour?
  7922. return true;
  7923. }
  7924. if (LLVMIsConstant(v)) {
  7925. return true;
  7926. }
  7927. return false;
  7928. }
  7929. bool lb_is_const_or_global(lbValue value) {
  7930. if (lb_is_const(value)) {
  7931. return true;
  7932. }
  7933. if (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) {
  7934. LLVMTypeRef t = LLVMGetElementType(LLVMTypeOf(value.value));
  7935. if (!lb_is_type_kind(t, LLVMPointerTypeKind)) {
  7936. return false;
  7937. }
  7938. LLVMTypeRef elem = LLVMGetElementType(t);
  7939. return lb_is_type_kind(elem, LLVMFunctionTypeKind);
  7940. }
  7941. return false;
  7942. }
  7943. bool lb_is_const_nil(lbValue value) {
  7944. LLVMValueRef v = value.value;
  7945. if (LLVMIsConstant(v)) {
  7946. if (LLVMIsAConstantAggregateZero(v)) {
  7947. return true;
  7948. } else if (LLVMIsAConstantPointerNull(v)) {
  7949. return true;
  7950. }
  7951. }
  7952. return false;
  7953. }
  7954. String lb_get_const_string(lbModule *m, lbValue value) {
  7955. GB_ASSERT(lb_is_const(value));
  7956. Type *t = base_type(value.type);
  7957. GB_ASSERT(are_types_identical(t, t_string));
  7958. unsigned ptr_indices[1] = {0};
  7959. unsigned len_indices[1] = {1};
  7960. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7961. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7962. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7963. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7964. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7965. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7966. size_t length = 0;
  7967. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7968. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7969. return make_string(cast(u8 const *)text, real_length);
  7970. }
  7971. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7972. GB_ASSERT(is_type_pointer(addr.type));
  7973. Type *type = type_deref(addr.type);
  7974. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7975. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7976. }
  7977. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7978. AstPackage *pkg = m->info->runtime_package;
  7979. Entity *e = scope_lookup_current(pkg->scope, name);
  7980. lbValue *found = nullptr;
  7981. if (m != e->code_gen_module) {
  7982. gb_mutex_lock(&m->mutex);
  7983. }
  7984. GB_ASSERT(e->code_gen_module != nullptr);
  7985. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7986. if (m != e->code_gen_module) {
  7987. gb_mutex_unlock(&m->mutex);
  7988. }
  7989. GB_ASSERT(found != nullptr);
  7990. return found->value;
  7991. }
  7992. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7993. Type *vt = core_type(value.type);
  7994. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7995. // TODO(bill): lb_emit_byte_swap
  7996. lbValue res = {};
  7997. res.type = platform_type;
  7998. res.value = value.value;
  7999. int sz = cast(int)type_size_of(vt);
  8000. if (sz > 1) {
  8001. if (is_type_float(platform_type)) {
  8002. String name = {};
  8003. switch (sz) {
  8004. case 4: name = str_lit("bswap_f32"); break;
  8005. case 8: name = str_lit("bswap_f64"); break;
  8006. default: GB_PANIC("unhandled byteswap size"); break;
  8007. }
  8008. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  8009. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  8010. } else {
  8011. GB_ASSERT(is_type_integer(platform_type));
  8012. String name = {};
  8013. switch (sz) {
  8014. case 2: name = str_lit("bswap_16"); break;
  8015. case 4: name = str_lit("bswap_32"); break;
  8016. case 8: name = str_lit("bswap_64"); break;
  8017. case 16: name = str_lit("bswap_128"); break;
  8018. default: GB_PANIC("unhandled byteswap size"); break;
  8019. }
  8020. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  8021. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  8022. }
  8023. }
  8024. return res;
  8025. }
  8026. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  8027. lbLoopData data = {};
  8028. lbValue max = lb_const_int(p->module, t_int, count);
  8029. data.idx_addr = lb_add_local_generated(p, index_type, true);
  8030. data.body = lb_create_block(p, "loop.body");
  8031. data.done = lb_create_block(p, "loop.done");
  8032. data.loop = lb_create_block(p, "loop.loop");
  8033. lb_emit_jump(p, data.loop);
  8034. lb_start_block(p, data.loop);
  8035. data.idx = lb_addr_load(p, data.idx_addr);
  8036. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  8037. lb_emit_if(p, cond, data.body, data.done);
  8038. lb_start_block(p, data.body);
  8039. return data;
  8040. }
  8041. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  8042. if (data.idx_addr.addr.value != nullptr) {
  8043. lb_emit_increment(p, data.idx_addr.addr);
  8044. lb_emit_jump(p, data.loop);
  8045. lb_start_block(p, data.done);
  8046. }
  8047. }
  8048. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  8049. lbValue res = {};
  8050. res.type = t_llvm_bool;
  8051. Type *t = x.type;
  8052. if (is_type_pointer(t)) {
  8053. if (op_kind == Token_CmpEq) {
  8054. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8055. } else if (op_kind == Token_NotEq) {
  8056. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8057. }
  8058. return res;
  8059. } else if (is_type_cstring(t)) {
  8060. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  8061. if (op_kind == Token_CmpEq) {
  8062. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  8063. } else if (op_kind == Token_NotEq) {
  8064. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  8065. }
  8066. return res;
  8067. } else if (is_type_proc(t)) {
  8068. if (op_kind == Token_CmpEq) {
  8069. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  8070. } else if (op_kind == Token_NotEq) {
  8071. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  8072. }
  8073. return res;
  8074. } else if (is_type_any(t)) {
  8075. // TODO(bill): is this correct behaviour for nil comparison for any?
  8076. lbValue data = lb_emit_struct_ev(p, x, 0);
  8077. lbValue ti = lb_emit_struct_ev(p, x, 1);
  8078. if (op_kind == Token_CmpEq) {
  8079. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  8080. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  8081. res.value = LLVMBuildOr(p->builder, a, b, "");
  8082. return res;
  8083. } else if (op_kind == Token_NotEq) {
  8084. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  8085. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  8086. res.value = LLVMBuildAnd(p->builder, a, b, "");
  8087. return res;
  8088. }
  8089. } else if (is_type_slice(t)) {
  8090. lbValue len = lb_emit_struct_ev(p, x, 1);
  8091. if (op_kind == Token_CmpEq) {
  8092. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8093. return res;
  8094. } else if (op_kind == Token_NotEq) {
  8095. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8096. return res;
  8097. }
  8098. } else if (is_type_dynamic_array(t)) {
  8099. lbValue cap = lb_emit_struct_ev(p, x, 2);
  8100. if (op_kind == Token_CmpEq) {
  8101. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8102. return res;
  8103. } else if (op_kind == Token_NotEq) {
  8104. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8105. return res;
  8106. }
  8107. } else if (is_type_map(t)) {
  8108. lbValue cap = lb_map_cap(p, x);
  8109. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  8110. } else if (is_type_union(t)) {
  8111. if (type_size_of(t) == 0) {
  8112. if (op_kind == Token_CmpEq) {
  8113. return lb_const_bool(p->module, t_llvm_bool, true);
  8114. } else if (op_kind == Token_NotEq) {
  8115. return lb_const_bool(p->module, t_llvm_bool, false);
  8116. }
  8117. } else {
  8118. lbValue tag = lb_emit_union_tag_value(p, x);
  8119. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  8120. }
  8121. } else if (is_type_typeid(t)) {
  8122. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  8123. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  8124. } else if (is_type_soa_struct(t)) {
  8125. Type *bt = base_type(t);
  8126. if (bt->Struct.soa_kind == StructSoa_Slice) {
  8127. lbValue len = lb_soa_struct_len(p, x);
  8128. if (op_kind == Token_CmpEq) {
  8129. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  8130. return res;
  8131. } else if (op_kind == Token_NotEq) {
  8132. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  8133. return res;
  8134. }
  8135. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  8136. lbValue cap = lb_soa_struct_cap(p, x);
  8137. if (op_kind == Token_CmpEq) {
  8138. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  8139. return res;
  8140. } else if (op_kind == Token_NotEq) {
  8141. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  8142. return res;
  8143. }
  8144. }
  8145. } else if (is_type_struct(t) && type_has_nil(t)) {
  8146. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8147. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  8148. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8149. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  8150. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  8151. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  8152. return res;
  8153. }
  8154. return {};
  8155. }
  8156. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  8157. Type *original_type = type;
  8158. type = base_type(type);
  8159. GB_ASSERT(is_type_comparable(type));
  8160. Type *pt = alloc_type_pointer(type);
  8161. LLVMTypeRef ptr_type = lb_type(m, pt);
  8162. auto key = hash_type(type);
  8163. lbProcedure **found = map_get(&m->equal_procs, key);
  8164. lbProcedure *compare_proc = nullptr;
  8165. if (found) {
  8166. compare_proc = *found;
  8167. GB_ASSERT(compare_proc != nullptr);
  8168. return {compare_proc->value, compare_proc->type};
  8169. }
  8170. static u32 proc_index = 0;
  8171. char buf[16] = {};
  8172. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  8173. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8174. String proc_name = make_string_c(str);
  8175. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  8176. map_set(&m->equal_procs, key, p);
  8177. lb_begin_procedure_body(p);
  8178. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8179. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8180. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  8181. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  8182. lbValue lhs = {x, pt};
  8183. lbValue rhs = {y, pt};
  8184. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  8185. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  8186. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  8187. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  8188. lb_start_block(p, block_same_ptr);
  8189. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8190. lb_start_block(p, block_diff_ptr);
  8191. if (type->kind == Type_Struct) {
  8192. type_set_offsets(type);
  8193. lbBlock *block_false = lb_create_block(p, "bfalse");
  8194. lbValue res = lb_const_bool(m, t_bool, true);
  8195. for_array(i, type->Struct.fields) {
  8196. lbBlock *next_block = lb_create_block(p, "btrue");
  8197. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  8198. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  8199. lbValue left = lb_emit_load(p, pleft);
  8200. lbValue right = lb_emit_load(p, pright);
  8201. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8202. lb_emit_if(p, ok, next_block, block_false);
  8203. lb_emit_jump(p, next_block);
  8204. lb_start_block(p, next_block);
  8205. }
  8206. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  8207. lb_start_block(p, block_false);
  8208. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  8209. } else {
  8210. lbValue left = lb_emit_load(p, lhs);
  8211. lbValue right = lb_emit_load(p, rhs);
  8212. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  8213. ok = lb_emit_conv(p, ok, t_bool);
  8214. LLVMBuildRet(p->builder, ok.value);
  8215. }
  8216. lb_end_procedure_body(p);
  8217. compare_proc = p;
  8218. return {compare_proc->value, compare_proc->type};
  8219. }
  8220. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  8221. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  8222. i64 sz = type_size_of(type);
  8223. if (1 <= sz && sz <= 16) {
  8224. char name[20] = {};
  8225. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  8226. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8227. args[0] = data;
  8228. args[1] = seed;
  8229. return lb_emit_runtime_call(p, name, args);
  8230. }
  8231. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8232. args[0] = data;
  8233. args[1] = seed;
  8234. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  8235. return lb_emit_runtime_call(p, "default_hasher_n", args);
  8236. }
  8237. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  8238. Type *original_type = type;
  8239. type = core_type(type);
  8240. GB_ASSERT(is_type_valid_for_keys(type));
  8241. Type *pt = alloc_type_pointer(type);
  8242. LLVMTypeRef ptr_type = lb_type(m, pt);
  8243. auto key = hash_type(type);
  8244. lbProcedure **found = map_get(&m->hasher_procs, key);
  8245. if (found) {
  8246. GB_ASSERT(*found != nullptr);
  8247. return {(*found)->value, (*found)->type};
  8248. }
  8249. static u32 proc_index = 0;
  8250. char buf[16] = {};
  8251. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  8252. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  8253. String proc_name = make_string_c(str);
  8254. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  8255. map_set(&m->hasher_procs, key, p);
  8256. lb_begin_procedure_body(p);
  8257. defer (lb_end_procedure_body(p));
  8258. LLVMValueRef x = LLVMGetParam(p->value, 0);
  8259. LLVMValueRef y = LLVMGetParam(p->value, 1);
  8260. lbValue data = {x, t_rawptr};
  8261. lbValue seed = {y, t_uintptr};
  8262. if (is_type_simple_compare(type)) {
  8263. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  8264. LLVMBuildRet(p->builder, res.value);
  8265. return {p->value, p->type};
  8266. }
  8267. if (type->kind == Type_Struct) {
  8268. type_set_offsets(type);
  8269. data = lb_emit_conv(p, data, t_u8_ptr);
  8270. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8271. for_array(i, type->Struct.fields) {
  8272. i64 offset = type->Struct.offsets[i];
  8273. Entity *field = type->Struct.fields[i];
  8274. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  8275. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  8276. args[0] = ptr;
  8277. args[1] = seed;
  8278. seed = lb_emit_call(p, field_hasher, args);
  8279. }
  8280. LLVMBuildRet(p->builder, seed.value);
  8281. } else if (type->kind == Type_Array) {
  8282. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  8283. lb_addr_store(p, pres, seed);
  8284. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8285. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  8286. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  8287. data = lb_emit_conv(p, data, pt);
  8288. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8289. args[0] = ptr;
  8290. args[1] = lb_addr_load(p, pres);
  8291. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8292. lb_addr_store(p, pres, new_seed);
  8293. lb_loop_end(p, loop_data);
  8294. lbValue res = lb_addr_load(p, pres);
  8295. LLVMBuildRet(p->builder, res.value);
  8296. } else if (type->kind == Type_EnumeratedArray) {
  8297. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  8298. lb_addr_store(p, res, seed);
  8299. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8300. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  8301. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  8302. data = lb_emit_conv(p, data, pt);
  8303. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  8304. args[0] = ptr;
  8305. args[1] = lb_addr_load(p, res);
  8306. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  8307. lb_addr_store(p, res, new_seed);
  8308. lb_loop_end(p, loop_data);
  8309. lbValue vres = lb_addr_load(p, res);
  8310. LLVMBuildRet(p->builder, vres.value);
  8311. } else if (is_type_cstring(type)) {
  8312. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8313. args[0] = data;
  8314. args[1] = seed;
  8315. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  8316. LLVMBuildRet(p->builder, res.value);
  8317. } else if (is_type_string(type)) {
  8318. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8319. args[0] = data;
  8320. args[1] = seed;
  8321. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  8322. LLVMBuildRet(p->builder, res.value);
  8323. } else {
  8324. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  8325. }
  8326. return {p->value, p->type};
  8327. }
  8328. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  8329. Type *a = core_type(left.type);
  8330. Type *b = core_type(right.type);
  8331. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  8332. lbValue nil_check = {};
  8333. if (is_type_untyped_nil(left.type)) {
  8334. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  8335. } else if (is_type_untyped_nil(right.type)) {
  8336. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  8337. }
  8338. if (nil_check.value != nullptr) {
  8339. return nil_check;
  8340. }
  8341. if (are_types_identical(a, b)) {
  8342. // NOTE(bill): No need for a conversion
  8343. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  8344. left = lb_emit_conv(p, left, right.type);
  8345. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  8346. right = lb_emit_conv(p, right, left.type);
  8347. } else {
  8348. Type *lt = left.type;
  8349. Type *rt = right.type;
  8350. // if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  8351. // Type *blt = base_type(lt);
  8352. // Type *brt = base_type(rt);
  8353. // i64 bits = gb_max(blt->BitSet.bits, brt->BitSet.bits);
  8354. // i64 bytes = bits / 8;
  8355. // switch (bytes) {
  8356. // case 1:
  8357. // left = lb_emit_conv(p, left, t_u8);
  8358. // right = lb_emit_conv(p, right, t_u8);
  8359. // break;
  8360. // case 2:
  8361. // left = lb_emit_conv(p, left, t_u16);
  8362. // right = lb_emit_conv(p, right, t_u16);
  8363. // break;
  8364. // case 4:
  8365. // left = lb_emit_conv(p, left, t_u32);
  8366. // right = lb_emit_conv(p, right, t_u32);
  8367. // break;
  8368. // case 8:
  8369. // left = lb_emit_conv(p, left, t_u64);
  8370. // right = lb_emit_conv(p, right, t_u64);
  8371. // break;
  8372. // default: GB_PANIC("Unknown integer size"); break;
  8373. // }
  8374. // }
  8375. lt = left.type;
  8376. rt = right.type;
  8377. i64 ls = type_size_of(lt);
  8378. i64 rs = type_size_of(rt);
  8379. if (ls < rs) {
  8380. left = lb_emit_conv(p, left, rt);
  8381. } else if (ls > rs) {
  8382. right = lb_emit_conv(p, right, lt);
  8383. } else {
  8384. right = lb_emit_conv(p, right, lt);
  8385. }
  8386. }
  8387. if (is_type_array(a)) {
  8388. Type *tl = base_type(a);
  8389. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  8390. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  8391. TokenKind cmp_op = Token_And;
  8392. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  8393. if (op_kind == Token_NotEq) {
  8394. res = lb_const_bool(p->module, t_llvm_bool, false);
  8395. cmp_op = Token_Or;
  8396. } else if (op_kind == Token_CmpEq) {
  8397. res = lb_const_bool(p->module, t_llvm_bool, true);
  8398. cmp_op = Token_And;
  8399. }
  8400. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  8401. i32 count = cast(i32)tl->Array.count;
  8402. if (inline_array_arith) {
  8403. // inline
  8404. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8405. lb_addr_store(p, val, res);
  8406. for (i32 i = 0; i < count; i++) {
  8407. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  8408. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  8409. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8410. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8411. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8412. }
  8413. return lb_addr_load(p, val);
  8414. } else {
  8415. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  8416. // TODO(bill): Test to see if this is actually faster!!!!
  8417. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8418. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  8419. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  8420. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  8421. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  8422. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  8423. return lb_emit_conv(p, res, t_bool);
  8424. } else {
  8425. lbAddr val = lb_add_local_generated(p, t_bool, false);
  8426. lb_addr_store(p, val, res);
  8427. auto loop_data = lb_loop_start(p, count, t_i32);
  8428. {
  8429. lbValue i = loop_data.idx;
  8430. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  8431. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  8432. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  8433. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  8434. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  8435. }
  8436. lb_loop_end(p, loop_data);
  8437. return lb_addr_load(p, val);
  8438. }
  8439. }
  8440. }
  8441. if (is_type_struct(a) && is_type_comparable(a)) {
  8442. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  8443. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  8444. lbValue res = {};
  8445. if (is_type_simple_compare(a)) {
  8446. // TODO(bill): Test to see if this is actually faster!!!!
  8447. auto args = array_make<lbValue>(permanent_allocator(), 3);
  8448. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8449. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8450. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  8451. res = lb_emit_runtime_call(p, "memory_equal", args);
  8452. } else {
  8453. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  8454. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8455. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  8456. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  8457. res = lb_emit_call(p, value, args);
  8458. }
  8459. if (op_kind == Token_NotEq) {
  8460. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  8461. }
  8462. return res;
  8463. }
  8464. if (is_type_string(a)) {
  8465. if (is_type_cstring(a)) {
  8466. left = lb_emit_conv(p, left, t_string);
  8467. right = lb_emit_conv(p, right, t_string);
  8468. }
  8469. char const *runtime_procedure = nullptr;
  8470. switch (op_kind) {
  8471. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  8472. case Token_NotEq: runtime_procedure = "string_ne"; break;
  8473. case Token_Lt: runtime_procedure = "string_lt"; break;
  8474. case Token_Gt: runtime_procedure = "string_gt"; break;
  8475. case Token_LtEq: runtime_procedure = "string_le"; break;
  8476. case Token_GtEq: runtime_procedure = "string_gt"; break;
  8477. }
  8478. GB_ASSERT(runtime_procedure != nullptr);
  8479. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8480. args[0] = left;
  8481. args[1] = right;
  8482. return lb_emit_runtime_call(p, runtime_procedure, args);
  8483. }
  8484. if (is_type_complex(a)) {
  8485. char const *runtime_procedure = "";
  8486. i64 sz = 8*type_size_of(a);
  8487. switch (sz) {
  8488. case 64:
  8489. switch (op_kind) {
  8490. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  8491. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  8492. }
  8493. break;
  8494. case 128:
  8495. switch (op_kind) {
  8496. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  8497. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  8498. }
  8499. break;
  8500. }
  8501. GB_ASSERT(runtime_procedure != nullptr);
  8502. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8503. args[0] = left;
  8504. args[1] = right;
  8505. return lb_emit_runtime_call(p, runtime_procedure, args);
  8506. }
  8507. if (is_type_quaternion(a)) {
  8508. char const *runtime_procedure = "";
  8509. i64 sz = 8*type_size_of(a);
  8510. switch (sz) {
  8511. case 128:
  8512. switch (op_kind) {
  8513. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  8514. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  8515. }
  8516. break;
  8517. case 256:
  8518. switch (op_kind) {
  8519. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  8520. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  8521. }
  8522. break;
  8523. }
  8524. GB_ASSERT(runtime_procedure != nullptr);
  8525. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8526. args[0] = left;
  8527. args[1] = right;
  8528. return lb_emit_runtime_call(p, runtime_procedure, args);
  8529. }
  8530. if (is_type_bit_set(a)) {
  8531. switch (op_kind) {
  8532. case Token_Lt:
  8533. case Token_LtEq:
  8534. case Token_Gt:
  8535. case Token_GtEq:
  8536. {
  8537. Type *it = bit_set_to_int(a);
  8538. lbValue lhs = lb_emit_transmute(p, left, it);
  8539. lbValue rhs = lb_emit_transmute(p, right, it);
  8540. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  8541. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  8542. // (lhs & rhs) == lhs
  8543. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  8544. res.type = t_llvm_bool;
  8545. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  8546. // (lhs & rhs) == rhs
  8547. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  8548. res.type = t_llvm_bool;
  8549. }
  8550. // NOTE(bill): Strict subsets
  8551. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  8552. // res &~ (lhs == rhs)
  8553. lbValue eq = {};
  8554. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  8555. eq.type = t_llvm_bool;
  8556. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  8557. }
  8558. return res;
  8559. }
  8560. case Token_CmpEq:
  8561. case Token_NotEq:
  8562. {
  8563. LLVMIntPredicate pred = {};
  8564. switch (op_kind) {
  8565. case Token_CmpEq: pred = LLVMIntEQ; break;
  8566. case Token_NotEq: pred = LLVMIntNE; break;
  8567. }
  8568. lbValue res = {};
  8569. res.type = t_llvm_bool;
  8570. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8571. return res;
  8572. }
  8573. }
  8574. }
  8575. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  8576. Type *t = left.type;
  8577. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  8578. Type *platform_type = integer_endian_type_to_platform_type(t);
  8579. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  8580. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  8581. left = x;
  8582. right = y;
  8583. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  8584. Type *platform_type = integer_endian_type_to_platform_type(t);
  8585. lbValue x = lb_emit_conv(p, left, platform_type);
  8586. lbValue y = lb_emit_conv(p, right, platform_type);
  8587. left = x;
  8588. right = y;
  8589. }
  8590. }
  8591. a = core_type(left.type);
  8592. b = core_type(right.type);
  8593. lbValue res = {};
  8594. res.type = t_llvm_bool;
  8595. if (is_type_integer(a) ||
  8596. is_type_boolean(a) ||
  8597. is_type_pointer(a) ||
  8598. is_type_proc(a) ||
  8599. is_type_enum(a)) {
  8600. LLVMIntPredicate pred = {};
  8601. if (is_type_unsigned(left.type)) {
  8602. switch (op_kind) {
  8603. case Token_Gt: pred = LLVMIntUGT; break;
  8604. case Token_GtEq: pred = LLVMIntUGE; break;
  8605. case Token_Lt: pred = LLVMIntULT; break;
  8606. case Token_LtEq: pred = LLVMIntULE; break;
  8607. }
  8608. } else {
  8609. switch (op_kind) {
  8610. case Token_Gt: pred = LLVMIntSGT; break;
  8611. case Token_GtEq: pred = LLVMIntSGE; break;
  8612. case Token_Lt: pred = LLVMIntSLT; break;
  8613. case Token_LtEq: pred = LLVMIntSLE; break;
  8614. }
  8615. }
  8616. switch (op_kind) {
  8617. case Token_CmpEq: pred = LLVMIntEQ; break;
  8618. case Token_NotEq: pred = LLVMIntNE; break;
  8619. }
  8620. LLVMValueRef lhs = left.value;
  8621. LLVMValueRef rhs = right.value;
  8622. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  8623. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  8624. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  8625. }
  8626. }
  8627. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  8628. } else if (is_type_float(a)) {
  8629. LLVMRealPredicate pred = {};
  8630. switch (op_kind) {
  8631. case Token_CmpEq: pred = LLVMRealOEQ; break;
  8632. case Token_Gt: pred = LLVMRealOGT; break;
  8633. case Token_GtEq: pred = LLVMRealOGE; break;
  8634. case Token_Lt: pred = LLVMRealOLT; break;
  8635. case Token_LtEq: pred = LLVMRealOLE; break;
  8636. case Token_NotEq: pred = LLVMRealONE; break;
  8637. }
  8638. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  8639. } else if (is_type_typeid(a)) {
  8640. LLVMIntPredicate pred = {};
  8641. switch (op_kind) {
  8642. case Token_Gt: pred = LLVMIntUGT; break;
  8643. case Token_GtEq: pred = LLVMIntUGE; break;
  8644. case Token_Lt: pred = LLVMIntULT; break;
  8645. case Token_LtEq: pred = LLVMIntULE; break;
  8646. case Token_CmpEq: pred = LLVMIntEQ; break;
  8647. case Token_NotEq: pred = LLVMIntNE; break;
  8648. }
  8649. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8650. } else {
  8651. GB_PANIC("Unhandled comparison kind %s (%s) %.*s %s (%s)", type_to_string(left.type), type_to_string(base_type(left.type)), LIT(token_strings[op_kind]), type_to_string(right.type), type_to_string(base_type(right.type)));
  8652. }
  8653. return res;
  8654. }
  8655. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  8656. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  8657. if (found != nullptr) {
  8658. lbValue value = {};
  8659. value.value = (*found)->value;
  8660. value.type = (*found)->type;
  8661. return value;
  8662. }
  8663. ast_node(pl, ProcLit, expr);
  8664. // NOTE(bill): Generate a new name
  8665. // parent$count
  8666. isize name_len = prefix_name.len + 1 + 8 + 1;
  8667. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  8668. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  8669. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  8670. String name = make_string((u8 *)name_text, name_len-1);
  8671. Type *type = type_of_expr(expr);
  8672. set_procedure_abi_types(type);
  8673. Token token = {};
  8674. token.pos = ast_token(expr).pos;
  8675. token.kind = Token_Ident;
  8676. token.string = name;
  8677. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  8678. e->file = expr->file;
  8679. e->decl_info = pl->decl;
  8680. lbProcedure *p = lb_create_procedure(m, e);
  8681. lbValue value = {};
  8682. value.value = p->value;
  8683. value.type = p->type;
  8684. array_add(&m->procedures_to_generate, p);
  8685. if (parent != nullptr) {
  8686. array_add(&parent->children, p);
  8687. } else {
  8688. string_map_set(&m->members, name, value);
  8689. }
  8690. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  8691. return value;
  8692. }
  8693. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  8694. lbModule *m = p->module;
  8695. Type *src_type = value.type;
  8696. bool is_ptr = is_type_pointer(src_type);
  8697. bool is_tuple = true;
  8698. Type *tuple = type;
  8699. if (type->kind != Type_Tuple) {
  8700. is_tuple = false;
  8701. tuple = make_optional_ok_type(type);
  8702. }
  8703. lbAddr v = lb_add_local_generated(p, tuple, true);
  8704. if (is_ptr) {
  8705. value = lb_emit_load(p, value);
  8706. }
  8707. Type *src = base_type(type_deref(src_type));
  8708. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  8709. Type *dst = tuple->Tuple.variables[0]->type;
  8710. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  8711. lbValue tag = {};
  8712. lbValue dst_tag = {};
  8713. lbValue cond = {};
  8714. lbValue data = {};
  8715. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8716. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8717. if (is_type_union_maybe_pointer(src)) {
  8718. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8719. } else {
  8720. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  8721. dst_tag = lb_const_union_tag(m, src, dst);
  8722. }
  8723. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8724. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8725. if (data.value != nullptr) {
  8726. GB_ASSERT(is_type_union_maybe_pointer(src));
  8727. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8728. } else {
  8729. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8730. }
  8731. lb_emit_if(p, cond, ok_block, end_block);
  8732. lb_start_block(p, ok_block);
  8733. if (data.value == nullptr) {
  8734. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8735. }
  8736. lb_emit_store(p, gep0, data);
  8737. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8738. lb_emit_jump(p, end_block);
  8739. lb_start_block(p, end_block);
  8740. if (!is_tuple) {
  8741. if (do_conversion_check) {
  8742. // NOTE(bill): Panic on invalid conversion
  8743. Type *dst_type = tuple->Tuple.variables[0]->type;
  8744. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8745. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8746. args[0] = ok;
  8747. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  8748. args[2] = lb_const_int(m, t_i32, pos.line);
  8749. args[3] = lb_const_int(m, t_i32, pos.column);
  8750. args[4] = lb_typeid(m, src_type);
  8751. args[5] = lb_typeid(m, dst_type);
  8752. args[6] = lb_emit_conv(p, value_, t_rawptr);
  8753. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8754. }
  8755. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8756. }
  8757. return lb_addr_load(p, v);
  8758. }
  8759. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8760. lbModule *m = p->module;
  8761. Type *src_type = value.type;
  8762. if (is_type_pointer(src_type)) {
  8763. value = lb_emit_load(p, value);
  8764. }
  8765. bool is_tuple = true;
  8766. Type *tuple = type;
  8767. if (type->kind != Type_Tuple) {
  8768. is_tuple = false;
  8769. tuple = make_optional_ok_type(type);
  8770. }
  8771. Type *dst_type = tuple->Tuple.variables[0]->type;
  8772. lbAddr v = lb_add_local_generated(p, tuple, true);
  8773. lbValue dst_typeid = lb_typeid(m, dst_type);
  8774. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  8775. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  8776. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  8777. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  8778. lb_emit_if(p, cond, ok_block, end_block);
  8779. lb_start_block(p, ok_block);
  8780. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8781. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8782. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  8783. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  8784. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  8785. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8786. lb_emit_jump(p, end_block);
  8787. lb_start_block(p, end_block);
  8788. if (!is_tuple) {
  8789. // NOTE(bill): Panic on invalid conversion
  8790. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8791. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8792. args[0] = ok;
  8793. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  8794. args[2] = lb_const_int(m, t_i32, pos.line);
  8795. args[3] = lb_const_int(m, t_i32, pos.column);
  8796. args[4] = any_typeid;
  8797. args[5] = dst_typeid;
  8798. args[6] = lb_emit_struct_ev(p, value, 0);;
  8799. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8800. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  8801. }
  8802. return v;
  8803. }
  8804. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8805. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  8806. }
  8807. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  8808. lbModule *m = p->module;
  8809. u64 prev_state_flags = p->module->state_flags;
  8810. defer (p->module->state_flags = prev_state_flags);
  8811. if (expr->state_flags != 0) {
  8812. u64 in = expr->state_flags;
  8813. u64 out = p->module->state_flags;
  8814. if (in & StateFlag_bounds_check) {
  8815. out |= StateFlag_bounds_check;
  8816. out &= ~StateFlag_no_bounds_check;
  8817. } else if (in & StateFlag_no_bounds_check) {
  8818. out |= StateFlag_no_bounds_check;
  8819. out &= ~StateFlag_bounds_check;
  8820. }
  8821. p->module->state_flags = out;
  8822. }
  8823. expr = unparen_expr(expr);
  8824. TokenPos expr_pos = ast_token(expr).pos;
  8825. TypeAndValue tv = type_and_value_of_expr(expr);
  8826. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %s\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), token_pos_to_string(expr_pos), LIT(p->name), type_to_string(p->type));
  8827. if (tv.value.kind != ExactValue_Invalid) {
  8828. // NOTE(bill): Short on constant values
  8829. return lb_const_value(p->module, tv.type, tv.value);
  8830. }
  8831. #if 0
  8832. LLVMMetadataRef prev_debug_location = nullptr;
  8833. if (p->debug_info != nullptr) {
  8834. prev_debug_location = LLVMGetCurrentDebugLocation2(p->builder);
  8835. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, expr));
  8836. }
  8837. defer (if (prev_debug_location != nullptr) {
  8838. LLVMSetCurrentDebugLocation2(p->builder, prev_debug_location);
  8839. });
  8840. #endif
  8841. switch (expr->kind) {
  8842. case_ast_node(bl, BasicLit, expr);
  8843. TokenPos pos = bl->token.pos;
  8844. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  8845. case_end;
  8846. case_ast_node(bd, BasicDirective, expr);
  8847. TokenPos pos = bd->token.pos;
  8848. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name));
  8849. case_end;
  8850. case_ast_node(i, Implicit, expr);
  8851. return lb_addr_load(p, lb_build_addr(p, expr));
  8852. case_end;
  8853. case_ast_node(u, Undef, expr)
  8854. lbValue res = {};
  8855. if (is_type_untyped(tv.type)) {
  8856. res.value = nullptr;
  8857. res.type = t_untyped_undef;
  8858. } else {
  8859. res.value = LLVMGetUndef(lb_type(m, tv.type));
  8860. res.type = tv.type;
  8861. }
  8862. return res;
  8863. case_end;
  8864. case_ast_node(i, Ident, expr);
  8865. Entity *e = entity_from_expr(expr);
  8866. e = strip_entity_wrapping(e);
  8867. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  8868. if (e->kind == Entity_Builtin) {
  8869. Token token = ast_token(expr);
  8870. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  8871. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  8872. token_pos_to_string(token.pos));
  8873. return {};
  8874. } else if (e->kind == Entity_Nil) {
  8875. lbValue res = {};
  8876. res.value = nullptr;
  8877. res.type = e->type;
  8878. return res;
  8879. }
  8880. GB_ASSERT(e->kind != Entity_ProcGroup);
  8881. auto *found = map_get(&p->module->values, hash_entity(e));
  8882. if (found) {
  8883. auto v = *found;
  8884. // NOTE(bill): This is because pointers are already pointers in LLVM
  8885. if (is_type_proc(v.type)) {
  8886. return v;
  8887. }
  8888. return lb_emit_load(p, v);
  8889. } else if (e != nullptr && e->kind == Entity_Variable) {
  8890. return lb_addr_load(p, lb_build_addr(p, expr));
  8891. }
  8892. gb_printf_err("Error in: %s\n", token_pos_to_string(i->token.pos));
  8893. String pkg = {};
  8894. if (e->pkg) {
  8895. pkg = e->pkg->name;
  8896. }
  8897. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(pkg), LIT(e->token.string), e, type_to_string(e->type), expr);
  8898. return {};
  8899. case_end;
  8900. case_ast_node(de, DerefExpr, expr);
  8901. return lb_addr_load(p, lb_build_addr(p, expr));
  8902. case_end;
  8903. case_ast_node(se, SelectorExpr, expr);
  8904. TypeAndValue tav = type_and_value_of_expr(expr);
  8905. GB_ASSERT(tav.mode != Addressing_Invalid);
  8906. return lb_addr_load(p, lb_build_addr(p, expr));
  8907. case_end;
  8908. case_ast_node(ise, ImplicitSelectorExpr, expr);
  8909. TypeAndValue tav = type_and_value_of_expr(expr);
  8910. GB_ASSERT(tav.mode == Addressing_Constant);
  8911. return lb_const_value(p->module, tv.type, tv.value);
  8912. case_end;
  8913. case_ast_node(se, SelectorCallExpr, expr);
  8914. GB_ASSERT(se->modified_call);
  8915. TypeAndValue tav = type_and_value_of_expr(expr);
  8916. GB_ASSERT(tav.mode != Addressing_Invalid);
  8917. return lb_build_expr(p, se->call);
  8918. case_end;
  8919. case_ast_node(te, TernaryExpr, expr);
  8920. LLVMValueRef incoming_values[2] = {};
  8921. LLVMBasicBlockRef incoming_blocks[2] = {};
  8922. GB_ASSERT(te->y != nullptr);
  8923. lbBlock *then = lb_create_block(p, "if.then");
  8924. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8925. lbBlock *else_ = lb_create_block(p, "if.else");
  8926. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8927. lb_start_block(p, then);
  8928. Type *type = default_type(type_of_expr(expr));
  8929. lb_open_scope(p, nullptr);
  8930. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8931. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8932. lb_emit_jump(p, done);
  8933. lb_start_block(p, else_);
  8934. lb_open_scope(p, nullptr);
  8935. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8936. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8937. lb_emit_jump(p, done);
  8938. lb_start_block(p, done);
  8939. lbValue res = {};
  8940. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8941. res.type = type;
  8942. GB_ASSERT(p->curr_block->preds.count >= 2);
  8943. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8944. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8945. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8946. return res;
  8947. case_end;
  8948. case_ast_node(te, TernaryIfExpr, expr);
  8949. LLVMValueRef incoming_values[2] = {};
  8950. LLVMBasicBlockRef incoming_blocks[2] = {};
  8951. GB_ASSERT(te->y != nullptr);
  8952. lbBlock *then = lb_create_block(p, "if.then");
  8953. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8954. lbBlock *else_ = lb_create_block(p, "if.else");
  8955. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8956. lb_start_block(p, then);
  8957. Type *type = default_type(type_of_expr(expr));
  8958. lb_open_scope(p, nullptr);
  8959. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8960. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8961. lb_emit_jump(p, done);
  8962. lb_start_block(p, else_);
  8963. lb_open_scope(p, nullptr);
  8964. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8965. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8966. lb_emit_jump(p, done);
  8967. lb_start_block(p, done);
  8968. lbValue res = {};
  8969. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8970. res.type = type;
  8971. GB_ASSERT(p->curr_block->preds.count >= 2);
  8972. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8973. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8974. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8975. return res;
  8976. case_end;
  8977. case_ast_node(te, TernaryWhenExpr, expr);
  8978. TypeAndValue tav = type_and_value_of_expr(te->cond);
  8979. GB_ASSERT(tav.mode == Addressing_Constant);
  8980. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  8981. if (tav.value.value_bool) {
  8982. return lb_build_expr(p, te->x);
  8983. } else {
  8984. return lb_build_expr(p, te->y);
  8985. }
  8986. case_end;
  8987. case_ast_node(ta, TypeAssertion, expr);
  8988. TokenPos pos = ast_token(expr).pos;
  8989. Type *type = tv.type;
  8990. lbValue e = lb_build_expr(p, ta->expr);
  8991. Type *t = type_deref(e.type);
  8992. if (is_type_union(t)) {
  8993. return lb_emit_union_cast(p, e, type, pos);
  8994. } else if (is_type_any(t)) {
  8995. return lb_emit_any_cast(p, e, type, pos);
  8996. } else {
  8997. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8998. }
  8999. case_end;
  9000. case_ast_node(tc, TypeCast, expr);
  9001. lbValue e = lb_build_expr(p, tc->expr);
  9002. switch (tc->token.kind) {
  9003. case Token_cast:
  9004. return lb_emit_conv(p, e, tv.type);
  9005. case Token_transmute:
  9006. return lb_emit_transmute(p, e, tv.type);
  9007. }
  9008. GB_PANIC("Invalid AST TypeCast");
  9009. case_end;
  9010. case_ast_node(ac, AutoCast, expr);
  9011. return lb_build_expr(p, ac->expr);
  9012. case_end;
  9013. case_ast_node(ue, UnaryExpr, expr);
  9014. switch (ue->op.kind) {
  9015. case Token_And: {
  9016. Ast *ue_expr = unparen_expr(ue->expr);
  9017. if (ue_expr->kind == Ast_CompoundLit) {
  9018. lbValue v = lb_build_expr(p, ue->expr);
  9019. Type *type = v.type;
  9020. lbAddr addr = {};
  9021. if (p->is_startup) {
  9022. addr = lb_add_global_generated(p->module, type, v);
  9023. } else {
  9024. addr = lb_add_local_generated(p, type, false);
  9025. }
  9026. lb_addr_store(p, addr, v);
  9027. return addr.addr;
  9028. } else if (ue_expr->kind == Ast_TypeAssertion) {
  9029. GB_ASSERT(is_type_pointer(tv.type));
  9030. ast_node(ta, TypeAssertion, ue_expr);
  9031. TokenPos pos = ast_token(expr).pos;
  9032. Type *type = type_of_expr(ue_expr);
  9033. GB_ASSERT(!is_type_tuple(type));
  9034. lbValue e = lb_build_expr(p, ta->expr);
  9035. Type *t = type_deref(e.type);
  9036. if (is_type_union(t)) {
  9037. lbValue v = e;
  9038. if (!is_type_pointer(v.type)) {
  9039. v = lb_address_from_load_or_generate_local(p, v);
  9040. }
  9041. Type *src_type = type_deref(v.type);
  9042. Type *dst_type = type;
  9043. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  9044. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  9045. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  9046. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9047. args[0] = ok;
  9048. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9049. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9050. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9051. args[4] = lb_typeid(p->module, src_type);
  9052. args[5] = lb_typeid(p->module, dst_type);
  9053. lb_emit_runtime_call(p, "type_assertion_check", args);
  9054. lbValue data_ptr = v;
  9055. return lb_emit_conv(p, data_ptr, tv.type);
  9056. } else if (is_type_any(t)) {
  9057. lbValue v = e;
  9058. if (is_type_pointer(v.type)) {
  9059. v = lb_emit_load(p, v);
  9060. }
  9061. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  9062. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  9063. lbValue id = lb_typeid(p->module, type);
  9064. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  9065. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9066. args[0] = ok;
  9067. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  9068. args[2] = lb_const_int(p->module, t_i32, pos.line);
  9069. args[3] = lb_const_int(p->module, t_i32, pos.column);
  9070. args[4] = any_id;
  9071. args[5] = id;
  9072. lb_emit_runtime_call(p, "type_assertion_check", args);
  9073. return lb_emit_conv(p, data_ptr, tv.type);
  9074. } else {
  9075. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  9076. }
  9077. }
  9078. return lb_build_addr_ptr(p, ue->expr);
  9079. }
  9080. default:
  9081. {
  9082. lbValue v = lb_build_expr(p, ue->expr);
  9083. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  9084. }
  9085. }
  9086. case_end;
  9087. case_ast_node(be, BinaryExpr, expr);
  9088. return lb_build_binary_expr(p, expr);
  9089. case_end;
  9090. case_ast_node(pl, ProcLit, expr);
  9091. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  9092. case_end;
  9093. case_ast_node(cl, CompoundLit, expr);
  9094. return lb_addr_load(p, lb_build_addr(p, expr));
  9095. case_end;
  9096. case_ast_node(ce, CallExpr, expr);
  9097. lbValue res = lb_build_call_expr(p, expr);
  9098. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  9099. GB_ASSERT(is_type_tuple(res.type));
  9100. GB_ASSERT(res.type->Tuple.variables.count == 2);
  9101. return lb_emit_struct_ev(p, res, 0);
  9102. }
  9103. return res;
  9104. case_end;
  9105. case_ast_node(se, SliceExpr, expr);
  9106. return lb_addr_load(p, lb_build_addr(p, expr));
  9107. case_end;
  9108. case_ast_node(ie, IndexExpr, expr);
  9109. return lb_addr_load(p, lb_build_addr(p, expr));
  9110. case_end;
  9111. case_ast_node(ia, InlineAsmExpr, expr);
  9112. Type *t = type_of_expr(expr);
  9113. GB_ASSERT(is_type_asm_proc(t));
  9114. String asm_string = {};
  9115. String constraints_string = {};
  9116. TypeAndValue tav;
  9117. tav = type_and_value_of_expr(ia->asm_string);
  9118. GB_ASSERT(is_type_string(tav.type));
  9119. GB_ASSERT(tav.value.kind == ExactValue_String);
  9120. asm_string = tav.value.value_string;
  9121. tav = type_and_value_of_expr(ia->constraints_string);
  9122. GB_ASSERT(is_type_string(tav.type));
  9123. GB_ASSERT(tav.value.kind == ExactValue_String);
  9124. constraints_string = tav.value.value_string;
  9125. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  9126. switch (ia->dialect) {
  9127. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  9128. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  9129. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  9130. default: GB_PANIC("Unhandled inline asm dialect"); break;
  9131. }
  9132. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  9133. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  9134. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  9135. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  9136. ia->has_side_effects, ia->is_align_stack, dialect
  9137. );
  9138. GB_ASSERT(the_asm != nullptr);
  9139. return {the_asm, t};
  9140. case_end;
  9141. }
  9142. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  9143. return {};
  9144. }
  9145. lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  9146. lbAddr *found = map_get(&p->module->soa_values, hash_entity(e));
  9147. GB_ASSERT(found != nullptr);
  9148. return *found;
  9149. }
  9150. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  9151. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  9152. String name = e->token.string;
  9153. Entity *parent = e->using_parent;
  9154. Selection sel = lookup_field(parent->type, name, false);
  9155. GB_ASSERT(sel.entity != nullptr);
  9156. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  9157. lbValue v = {};
  9158. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  9159. // NOTE(bill): using SOA value (probably from for-in statement)
  9160. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  9161. v = lb_addr_get_ptr(p, parent_addr);
  9162. } else if (pv != nullptr) {
  9163. v = *pv;
  9164. } else {
  9165. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  9166. v = lb_build_addr_ptr(p, e->using_expr);
  9167. }
  9168. GB_ASSERT(v.value != nullptr);
  9169. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  9170. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  9171. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  9172. return ptr;
  9173. }
  9174. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  9175. GB_ASSERT(e != nullptr);
  9176. if (e->kind == Entity_Constant) {
  9177. Type *t = default_type(type_of_expr(expr));
  9178. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  9179. lbAddr g = lb_add_global_generated(p->module, t, v);
  9180. return g;
  9181. }
  9182. lbValue v = {};
  9183. lbValue *found = map_get(&p->module->values, hash_entity(e));
  9184. if (found) {
  9185. v = *found;
  9186. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  9187. // NOTE(bill): Calculate the using variable every time
  9188. v = lb_get_using_variable(p, e);
  9189. } else if (e->flags & EntityFlag_SoaPtrField) {
  9190. return lb_get_soa_variable_addr(p, e);
  9191. }
  9192. if (v.value == nullptr) {
  9193. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  9194. LIT(p->name),
  9195. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  9196. GB_PANIC("Unknown value");
  9197. }
  9198. return lb_addr(v);
  9199. }
  9200. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  9201. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  9202. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  9203. map_type = base_type(map_type);
  9204. GB_ASSERT(map_type->kind == Type_Map);
  9205. Type *key_type = map_type->Map.key;
  9206. Type *val_type = map_type->Map.value;
  9207. // NOTE(bill): Removes unnecessary allocation if split gep
  9208. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  9209. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  9210. lb_emit_store(p, gep0, m);
  9211. i64 entry_size = type_size_of (map_type->Map.entry_type);
  9212. i64 entry_align = type_align_of (map_type->Map.entry_type);
  9213. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  9214. i64 key_size = type_size_of (map_type->Map.key);
  9215. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  9216. i64 value_size = type_size_of (map_type->Map.value);
  9217. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  9218. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  9219. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  9220. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  9221. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  9222. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  9223. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  9224. return lb_addr_load(p, h);
  9225. }
  9226. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  9227. if (true) {
  9228. return {};
  9229. }
  9230. lbValue hashed_key = {};
  9231. if (lb_is_const(key)) {
  9232. u64 hash = 0xcbf29ce484222325;
  9233. if (is_type_cstring(key_type)) {
  9234. size_t length = 0;
  9235. char const *text = LLVMGetAsString(key.value, &length);
  9236. hash = fnv64a(text, cast(isize)length);
  9237. } else if (is_type_string(key_type)) {
  9238. unsigned data_indices[] = {0};
  9239. unsigned len_indices[] = {1};
  9240. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  9241. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  9242. isize length = LLVMConstIntGetSExtValue(len);
  9243. char const *text = nullptr;
  9244. if (false && length != 0) {
  9245. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  9246. return {};
  9247. }
  9248. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  9249. size_t ulength = 0;
  9250. text = LLVMGetAsString(data, &ulength);
  9251. gb_printf_err("%td %td %s\n", length, ulength, text);
  9252. length = gb_min(length, cast(isize)ulength);
  9253. }
  9254. hash = fnv64a(text, cast(isize)length);
  9255. } else {
  9256. return {};
  9257. }
  9258. // TODO(bill): other const hash types
  9259. if (build_context.word_size == 4) {
  9260. hash &= 0xffffffffull;
  9261. }
  9262. hashed_key = lb_const_int(m, t_uintptr, hash);
  9263. }
  9264. return hashed_key;
  9265. }
  9266. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  9267. Type *hash_type = t_u64;
  9268. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  9269. lbValue vp = lb_addr_get_ptr(p, v);
  9270. Type *t = base_type(key.type);
  9271. key = lb_emit_conv(p, key, key_type);
  9272. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  9273. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  9274. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  9275. if (hashed_key.value == nullptr) {
  9276. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  9277. auto args = array_make<lbValue>(permanent_allocator(), 2);
  9278. args[0] = key_ptr;
  9279. args[1] = lb_const_int(p->module, t_uintptr, 0);
  9280. hashed_key = lb_emit_call(p, hasher, args);
  9281. }
  9282. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  9283. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  9284. return lb_addr_load(p, v);
  9285. }
  9286. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  9287. lbValue map_key, lbValue map_value, Ast *node) {
  9288. map_type = base_type(map_type);
  9289. GB_ASSERT(map_type->kind == Type_Map);
  9290. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  9291. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  9292. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  9293. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  9294. lb_addr_store(p, value_addr, v);
  9295. auto args = array_make<lbValue>(permanent_allocator(), 4);
  9296. args[0] = h;
  9297. args[1] = key;
  9298. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  9299. args[3] = lb_emit_source_code_location(p, node);
  9300. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  9301. }
  9302. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  9303. expr = unparen_expr(expr);
  9304. switch (expr->kind) {
  9305. case_ast_node(i, Implicit, expr);
  9306. lbAddr v = {};
  9307. switch (i->kind) {
  9308. case Token_context:
  9309. v = lb_find_or_generate_context_ptr(p);
  9310. break;
  9311. }
  9312. GB_ASSERT(v.addr.value != nullptr);
  9313. return v;
  9314. case_end;
  9315. case_ast_node(i, Ident, expr);
  9316. if (is_blank_ident(expr)) {
  9317. lbAddr val = {};
  9318. return val;
  9319. }
  9320. String name = i->token.string;
  9321. Entity *e = entity_of_node(expr);
  9322. return lb_build_addr_from_entity(p, e, expr);
  9323. case_end;
  9324. case_ast_node(se, SelectorExpr, expr);
  9325. Ast *sel = unparen_expr(se->selector);
  9326. if (sel->kind == Ast_Ident) {
  9327. String selector = sel->Ident.token.string;
  9328. TypeAndValue tav = type_and_value_of_expr(se->expr);
  9329. if (tav.mode == Addressing_Invalid) {
  9330. // NOTE(bill): Imports
  9331. Entity *imp = entity_of_node(se->expr);
  9332. if (imp != nullptr) {
  9333. GB_ASSERT(imp->kind == Entity_ImportName);
  9334. }
  9335. return lb_build_addr(p, unparen_expr(se->selector));
  9336. }
  9337. Type *type = base_type(tav.type);
  9338. if (tav.mode == Addressing_Type) { // Addressing_Type
  9339. Selection sel = lookup_field(type, selector, true);
  9340. Entity *e = sel.entity;
  9341. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  9342. GB_ASSERT(e->flags & EntityFlag_TypeField);
  9343. String name = e->token.string;
  9344. /*if (name == "names") {
  9345. lbValue ti_ptr = lb_type_info(m, type);
  9346. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  9347. lbValue names_ptr = nullptr;
  9348. if (is_type_enum(type)) {
  9349. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  9350. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  9351. } else if (type->kind == Type_Struct) {
  9352. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  9353. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  9354. }
  9355. return ir_addr(names_ptr);
  9356. } else */{
  9357. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  9358. }
  9359. GB_PANIC("Unreachable");
  9360. }
  9361. Selection sel = lookup_field(type, selector, false);
  9362. GB_ASSERT(sel.entity != nullptr);
  9363. {
  9364. lbAddr addr = lb_build_addr(p, se->expr);
  9365. if (addr.kind == lbAddr_Map) {
  9366. lbValue v = lb_addr_load(p, addr);
  9367. lbValue a = lb_address_from_load_or_generate_local(p, v);
  9368. a = lb_emit_deep_field_gep(p, a, sel);
  9369. return lb_addr(a);
  9370. } else if (addr.kind == lbAddr_Context) {
  9371. GB_ASSERT(sel.index.count > 0);
  9372. if (addr.ctx.sel.index.count >= 0) {
  9373. sel = selection_combine(addr.ctx.sel, sel);
  9374. }
  9375. addr.ctx.sel = sel;
  9376. addr.kind = lbAddr_Context;
  9377. return addr;
  9378. } else if (addr.kind == lbAddr_SoaVariable) {
  9379. lbValue index = addr.soa.index;
  9380. i32 first_index = sel.index[0];
  9381. Selection sub_sel = sel;
  9382. sub_sel.index.data += 1;
  9383. sub_sel.index.count -= 1;
  9384. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  9385. Type *t = base_type(type_deref(addr.addr.type));
  9386. GB_ASSERT(is_type_soa_struct(t));
  9387. // TODO(bill): Bounds check
  9388. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  9389. lbValue len = lb_soa_struct_len(p, addr.addr);
  9390. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  9391. }
  9392. lbValue item = {};
  9393. if (t->Struct.soa_kind == StructSoa_Fixed) {
  9394. item = lb_emit_array_ep(p, arr, index);
  9395. } else {
  9396. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  9397. }
  9398. if (sub_sel.index.count > 0) {
  9399. item = lb_emit_deep_field_gep(p, item, sub_sel);
  9400. }
  9401. return lb_addr(item);
  9402. }
  9403. lbValue a = lb_addr_get_ptr(p, addr);
  9404. a = lb_emit_deep_field_gep(p, a, sel);
  9405. return lb_addr(a);
  9406. }
  9407. } else {
  9408. GB_PANIC("Unsupported selector expression");
  9409. }
  9410. case_end;
  9411. case_ast_node(se, SelectorCallExpr, expr);
  9412. GB_ASSERT(se->modified_call);
  9413. TypeAndValue tav = type_and_value_of_expr(expr);
  9414. GB_ASSERT(tav.mode != Addressing_Invalid);
  9415. return lb_build_addr(p, se->call);
  9416. case_end;
  9417. case_ast_node(ta, TypeAssertion, expr);
  9418. TokenPos pos = ast_token(expr).pos;
  9419. lbValue e = lb_build_expr(p, ta->expr);
  9420. Type *t = type_deref(e.type);
  9421. if (is_type_union(t)) {
  9422. Type *type = type_of_expr(expr);
  9423. lbAddr v = lb_add_local_generated(p, type, false);
  9424. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  9425. return v;
  9426. } else if (is_type_any(t)) {
  9427. Type *type = type_of_expr(expr);
  9428. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  9429. } else {
  9430. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  9431. }
  9432. case_end;
  9433. case_ast_node(ue, UnaryExpr, expr);
  9434. switch (ue->op.kind) {
  9435. case Token_And: {
  9436. return lb_build_addr(p, ue->expr);
  9437. }
  9438. default:
  9439. GB_PANIC("Invalid unary expression for lb_build_addr");
  9440. }
  9441. case_end;
  9442. case_ast_node(be, BinaryExpr, expr);
  9443. lbValue v = lb_build_expr(p, expr);
  9444. Type *t = v.type;
  9445. if (is_type_pointer(t)) {
  9446. return lb_addr(v);
  9447. }
  9448. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  9449. case_end;
  9450. case_ast_node(ie, IndexExpr, expr);
  9451. Type *t = base_type(type_of_expr(ie->expr));
  9452. bool deref = is_type_pointer(t);
  9453. t = base_type(type_deref(t));
  9454. if (is_type_soa_struct(t)) {
  9455. // SOA STRUCTURES!!!!
  9456. lbValue val = lb_build_addr_ptr(p, ie->expr);
  9457. if (deref) {
  9458. val = lb_emit_load(p, val);
  9459. }
  9460. lbValue index = lb_build_expr(p, ie->index);
  9461. return lb_addr_soa_variable(val, index, ie->index);
  9462. }
  9463. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  9464. // SOA Structures for slices/dynamic arrays
  9465. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  9466. lbValue field = lb_build_expr(p, ie->expr);
  9467. lbValue index = lb_build_expr(p, ie->index);
  9468. if (!build_context.no_bounds_check) {
  9469. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  9470. // GB_ASSERT(LLVMIsALoadInst(field.value));
  9471. // lbValue a = {};
  9472. // a.value = LLVMGetOperand(field.value, 0);
  9473. // a.type = alloc_type_pointer(field.type);
  9474. // irInstr *b = &a->Instr;
  9475. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  9476. // lbValue base_struct = b->StructElementPtr.address;
  9477. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  9478. // lbValue len = ir_soa_struct_len(p, base_struct);
  9479. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9480. }
  9481. lbValue val = lb_emit_ptr_offset(p, field, index);
  9482. return lb_addr(val);
  9483. }
  9484. if (!is_type_indexable(t)) {
  9485. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9486. if (found != nullptr) {
  9487. if (found->kind == TypeAtomOp_index_get) {
  9488. return lb_build_addr(p, found->node);
  9489. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  9490. return lb_addr(lb_build_expr(p, found->node));
  9491. } else if (found->kind == TypeAtomOp_index_set) {
  9492. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  9493. if (deref) {
  9494. ptr = lb_emit_load(p, ptr);
  9495. }
  9496. lbAddr addr = {lbAddr_AtomOp_index_set};
  9497. addr.addr = ptr;
  9498. addr.index_set.index = lb_build_expr(p, ie->index);
  9499. addr.index_set.node = found->node;
  9500. return addr;
  9501. }
  9502. }
  9503. }
  9504. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  9505. if (is_type_map(t)) {
  9506. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  9507. if (deref) {
  9508. map_val = lb_emit_load(p, map_val);
  9509. }
  9510. lbValue key = lb_build_expr(p, ie->index);
  9511. key = lb_emit_conv(p, key, t->Map.key);
  9512. Type *result_type = type_of_expr(expr);
  9513. return lb_addr_map(map_val, key, t, result_type);
  9514. }
  9515. switch (t->kind) {
  9516. case Type_Array: {
  9517. lbValue array = {};
  9518. array = lb_build_addr_ptr(p, ie->expr);
  9519. if (deref) {
  9520. array = lb_emit_load(p, array);
  9521. }
  9522. lbValue index = lb_build_expr(p, ie->index);
  9523. index = lb_emit_conv(p, index, t_int);
  9524. lbValue elem = lb_emit_array_ep(p, array, index);
  9525. auto index_tv = type_and_value_of_expr(ie->index);
  9526. if (index_tv.mode != Addressing_Constant) {
  9527. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  9528. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9529. }
  9530. return lb_addr(elem);
  9531. }
  9532. case Type_EnumeratedArray: {
  9533. lbValue array = {};
  9534. array = lb_build_addr_ptr(p, ie->expr);
  9535. if (deref) {
  9536. array = lb_emit_load(p, array);
  9537. }
  9538. Type *index_type = t->EnumeratedArray.index;
  9539. auto index_tv = type_and_value_of_expr(ie->index);
  9540. lbValue index = {};
  9541. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  9542. if (index_tv.mode == Addressing_Constant) {
  9543. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  9544. index = lb_const_value(p->module, index_type, idx);
  9545. } else {
  9546. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9547. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  9548. }
  9549. } else {
  9550. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9551. }
  9552. lbValue elem = lb_emit_array_ep(p, array, index);
  9553. if (index_tv.mode != Addressing_Constant) {
  9554. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  9555. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9556. }
  9557. return lb_addr(elem);
  9558. }
  9559. case Type_Slice: {
  9560. lbValue slice = {};
  9561. slice = lb_build_expr(p, ie->expr);
  9562. if (deref) {
  9563. slice = lb_emit_load(p, slice);
  9564. }
  9565. lbValue elem = lb_slice_elem(p, slice);
  9566. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9567. lbValue len = lb_slice_len(p, slice);
  9568. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9569. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9570. return lb_addr(v);
  9571. }
  9572. case Type_RelativeSlice: {
  9573. lbAddr slice_addr = {};
  9574. if (deref) {
  9575. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  9576. } else {
  9577. slice_addr = lb_build_addr(p, ie->expr);
  9578. }
  9579. lbValue slice = lb_addr_load(p, slice_addr);
  9580. lbValue elem = lb_slice_elem(p, slice);
  9581. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9582. lbValue len = lb_slice_len(p, slice);
  9583. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9584. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9585. return lb_addr(v);
  9586. }
  9587. case Type_DynamicArray: {
  9588. lbValue dynamic_array = {};
  9589. dynamic_array = lb_build_expr(p, ie->expr);
  9590. if (deref) {
  9591. dynamic_array = lb_emit_load(p, dynamic_array);
  9592. }
  9593. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  9594. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  9595. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9596. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9597. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9598. return lb_addr(v);
  9599. }
  9600. case Type_Basic: { // Basic_string
  9601. lbValue str;
  9602. lbValue elem;
  9603. lbValue len;
  9604. lbValue index;
  9605. str = lb_build_expr(p, ie->expr);
  9606. if (deref) {
  9607. str = lb_emit_load(p, str);
  9608. }
  9609. elem = lb_string_elem(p, str);
  9610. len = lb_string_len(p, str);
  9611. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9612. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9613. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  9614. }
  9615. }
  9616. case_end;
  9617. case_ast_node(se, SliceExpr, expr);
  9618. lbValue low = lb_const_int(p->module, t_int, 0);
  9619. lbValue high = {};
  9620. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  9621. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  9622. bool no_indices = se->low == nullptr && se->high == nullptr;
  9623. {
  9624. Type *type = base_type(type_of_expr(se->expr));
  9625. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  9626. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  9627. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  9628. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9629. if (found) {
  9630. lbValue base = lb_build_expr(p, found->node);
  9631. Type *slice_type = base.type;
  9632. lbValue len = lb_slice_len(p, base);
  9633. if (high.value == nullptr) high = len;
  9634. if (!no_indices) {
  9635. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9636. }
  9637. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9638. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9639. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9640. lb_fill_slice(p, slice, elem, new_len);
  9641. return slice;
  9642. }
  9643. }
  9644. }
  9645. }
  9646. lbAddr addr = lb_build_addr(p, se->expr);
  9647. lbValue base = lb_addr_load(p, addr);
  9648. Type *type = base_type(base.type);
  9649. if (is_type_pointer(type)) {
  9650. type = base_type(type_deref(type));
  9651. addr = lb_addr(base);
  9652. base = lb_addr_load(p, addr);
  9653. }
  9654. switch (type->kind) {
  9655. case Type_Slice: {
  9656. Type *slice_type = type;
  9657. lbValue len = lb_slice_len(p, base);
  9658. if (high.value == nullptr) high = len;
  9659. if (!no_indices) {
  9660. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9661. }
  9662. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9663. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9664. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9665. lb_fill_slice(p, slice, elem, new_len);
  9666. return slice;
  9667. }
  9668. case Type_RelativeSlice:
  9669. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  9670. break;
  9671. case Type_DynamicArray: {
  9672. Type *elem_type = type->DynamicArray.elem;
  9673. Type *slice_type = alloc_type_slice(elem_type);
  9674. lbValue len = lb_dynamic_array_len(p, base);
  9675. if (high.value == nullptr) high = len;
  9676. if (!no_indices) {
  9677. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9678. }
  9679. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  9680. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9681. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9682. lb_fill_slice(p, slice, elem, new_len);
  9683. return slice;
  9684. }
  9685. case Type_Array: {
  9686. Type *slice_type = alloc_type_slice(type->Array.elem);
  9687. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  9688. if (high.value == nullptr) high = len;
  9689. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  9690. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  9691. if (!low_const || !high_const) {
  9692. if (!no_indices) {
  9693. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9694. }
  9695. }
  9696. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  9697. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9698. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9699. lb_fill_slice(p, slice, elem, new_len);
  9700. return slice;
  9701. }
  9702. case Type_Basic: {
  9703. GB_ASSERT(type == t_string);
  9704. lbValue len = lb_string_len(p, base);
  9705. if (high.value == nullptr) high = len;
  9706. if (!no_indices) {
  9707. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9708. }
  9709. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  9710. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9711. lbAddr str = lb_add_local_generated(p, t_string, false);
  9712. lb_fill_string(p, str, elem, new_len);
  9713. return str;
  9714. }
  9715. case Type_Struct:
  9716. if (is_type_soa_struct(type)) {
  9717. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  9718. if (high.value == nullptr) high = len;
  9719. if (!no_indices) {
  9720. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9721. }
  9722. #if 1
  9723. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  9724. if (type->Struct.soa_kind == StructSoa_Fixed) {
  9725. i32 field_count = cast(i32)type->Struct.fields.count;
  9726. for (i32 i = 0; i < field_count; i++) {
  9727. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9728. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  9729. field_src = lb_emit_array_ep(p, field_src, low);
  9730. lb_emit_store(p, field_dst, field_src);
  9731. }
  9732. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9733. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9734. lb_emit_store(p, len_dst, new_len);
  9735. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  9736. if (no_indices) {
  9737. lb_addr_store(p, dst, base);
  9738. } else {
  9739. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  9740. for (i32 i = 0; i < field_count; i++) {
  9741. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9742. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9743. field_src = lb_emit_ptr_offset(p, field_src, low);
  9744. lb_emit_store(p, field_dst, field_src);
  9745. }
  9746. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9747. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9748. lb_emit_store(p, len_dst, new_len);
  9749. }
  9750. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9751. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9752. for (i32 i = 0; i < field_count; i++) {
  9753. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9754. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9755. field_src = lb_emit_ptr_offset(p, field_src, low);
  9756. lb_emit_store(p, field_dst, field_src);
  9757. }
  9758. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9759. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9760. lb_emit_store(p, len_dst, new_len);
  9761. }
  9762. return dst;
  9763. #endif
  9764. }
  9765. break;
  9766. }
  9767. GB_PANIC("Unknown slicable type");
  9768. case_end;
  9769. case_ast_node(de, DerefExpr, expr);
  9770. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  9771. lbAddr addr = lb_build_addr(p, de->expr);
  9772. addr.relative.deref = true;
  9773. return addr;
  9774. }
  9775. lbValue addr = lb_build_expr(p, de->expr);
  9776. return lb_addr(addr);
  9777. case_end;
  9778. case_ast_node(ce, CallExpr, expr);
  9779. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  9780. lbValue e = lb_build_expr(p, expr);
  9781. lbAddr v = lb_add_local_generated(p, e.type, false);
  9782. lb_addr_store(p, v, e);
  9783. return v;
  9784. case_end;
  9785. case_ast_node(cl, CompoundLit, expr);
  9786. Type *type = type_of_expr(expr);
  9787. Type *bt = base_type(type);
  9788. lbAddr v = lb_add_local_generated(p, type, true);
  9789. Type *et = nullptr;
  9790. switch (bt->kind) {
  9791. case Type_Array: et = bt->Array.elem; break;
  9792. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  9793. case Type_Slice: et = bt->Slice.elem; break;
  9794. case Type_BitSet: et = bt->BitSet.elem; break;
  9795. case Type_SimdVector: et = bt->SimdVector.elem; break;
  9796. }
  9797. String proc_name = {};
  9798. if (p->entity) {
  9799. proc_name = p->entity->token.string;
  9800. }
  9801. TokenPos pos = ast_token(expr).pos;
  9802. switch (bt->kind) {
  9803. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  9804. case Type_Struct: {
  9805. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  9806. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  9807. bool is_raw_union = is_type_raw_union(bt);
  9808. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  9809. TypeStruct *st = &bt->Struct;
  9810. if (cl->elems.count > 0) {
  9811. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9812. for_array(field_index, cl->elems) {
  9813. Ast *elem = cl->elems[field_index];
  9814. lbValue field_expr = {};
  9815. Entity *field = nullptr;
  9816. isize index = field_index;
  9817. if (elem->kind == Ast_FieldValue) {
  9818. ast_node(fv, FieldValue, elem);
  9819. String name = fv->field->Ident.token.string;
  9820. Selection sel = lookup_field(bt, name, false);
  9821. index = sel.index[0];
  9822. elem = fv->value;
  9823. TypeAndValue tav = type_and_value_of_expr(elem);
  9824. } else {
  9825. TypeAndValue tav = type_and_value_of_expr(elem);
  9826. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  9827. index = sel.index[0];
  9828. }
  9829. field = st->fields[index];
  9830. Type *ft = field->type;
  9831. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  9832. continue;
  9833. }
  9834. field_expr = lb_build_expr(p, elem);
  9835. Type *fet = field_expr.type;
  9836. GB_ASSERT(fet->kind != Type_Tuple);
  9837. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  9838. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  9839. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  9840. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9841. lb_emit_store_union_variant(p, gep, field_expr, fet);
  9842. } else {
  9843. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9844. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9845. lb_emit_store(p, gep, fv);
  9846. }
  9847. }
  9848. }
  9849. break;
  9850. }
  9851. case Type_Map: {
  9852. if (cl->elems.count == 0) {
  9853. break;
  9854. }
  9855. {
  9856. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9857. args[0] = lb_gen_map_header(p, v.addr, type);
  9858. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  9859. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  9860. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  9861. }
  9862. for_array(field_index, cl->elems) {
  9863. Ast *elem = cl->elems[field_index];
  9864. ast_node(fv, FieldValue, elem);
  9865. lbValue key = lb_build_expr(p, fv->field);
  9866. lbValue value = lb_build_expr(p, fv->value);
  9867. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  9868. }
  9869. break;
  9870. }
  9871. case Type_Array: {
  9872. if (cl->elems.count > 0) {
  9873. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9874. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9875. // NOTE(bill): Separate value, gep, store into their own chunks
  9876. for_array(i, cl->elems) {
  9877. Ast *elem = cl->elems[i];
  9878. if (elem->kind == Ast_FieldValue) {
  9879. ast_node(fv, FieldValue, elem);
  9880. if (lb_is_elem_const(fv->value, et)) {
  9881. continue;
  9882. }
  9883. if (is_ast_range(fv->field)) {
  9884. ast_node(ie, BinaryExpr, fv->field);
  9885. TypeAndValue lo_tav = ie->left->tav;
  9886. TypeAndValue hi_tav = ie->right->tav;
  9887. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9888. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9889. TokenKind op = ie->op.kind;
  9890. i64 lo = exact_value_to_i64(lo_tav.value);
  9891. i64 hi = exact_value_to_i64(hi_tav.value);
  9892. if (op == Token_Ellipsis) {
  9893. hi += 1;
  9894. }
  9895. lbValue value = lb_build_expr(p, fv->value);
  9896. for (i64 k = lo; k < hi; k++) {
  9897. lbCompoundLitElemTempData data = {};
  9898. data.value = value;
  9899. data.elem_index = cast(i32)k;
  9900. array_add(&temp_data, data);
  9901. }
  9902. } else {
  9903. auto tav = fv->field->tav;
  9904. GB_ASSERT(tav.mode == Addressing_Constant);
  9905. i64 index = exact_value_to_i64(tav.value);
  9906. lbValue value = lb_build_expr(p, fv->value);
  9907. lbCompoundLitElemTempData data = {};
  9908. data.value = lb_emit_conv(p, value, et);
  9909. data.expr = fv->value;
  9910. data.elem_index = cast(i32)index;
  9911. array_add(&temp_data, data);
  9912. }
  9913. } else {
  9914. if (lb_is_elem_const(elem, et)) {
  9915. continue;
  9916. }
  9917. lbCompoundLitElemTempData data = {};
  9918. data.expr = elem;
  9919. data.elem_index = cast(i32)i;
  9920. array_add(&temp_data, data);
  9921. }
  9922. }
  9923. for_array(i, temp_data) {
  9924. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  9925. }
  9926. for_array(i, temp_data) {
  9927. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9928. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9929. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9930. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9931. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9932. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9933. lbValue field_expr = temp_data[i].value;
  9934. Ast *expr = temp_data[i].expr;
  9935. p->return_ptr_hint_value = temp_data[i].gep;
  9936. p->return_ptr_hint_ast = unparen_expr(expr);
  9937. if (field_expr.value == nullptr) {
  9938. field_expr = lb_build_expr(p, expr);
  9939. }
  9940. Type *t = field_expr.type;
  9941. GB_ASSERT(t->kind != Type_Tuple);
  9942. lbValue ev = lb_emit_conv(p, field_expr, et);
  9943. if (!p->return_ptr_hint_used) {
  9944. temp_data[i].value = ev;
  9945. }
  9946. }
  9947. for_array(i, temp_data) {
  9948. if (temp_data[i].value.value != nullptr) {
  9949. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9950. }
  9951. }
  9952. }
  9953. break;
  9954. }
  9955. case Type_EnumeratedArray: {
  9956. if (cl->elems.count > 0) {
  9957. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9958. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9959. // NOTE(bill): Separate value, gep, store into their own chunks
  9960. for_array(i, cl->elems) {
  9961. Ast *elem = cl->elems[i];
  9962. if (elem->kind == Ast_FieldValue) {
  9963. ast_node(fv, FieldValue, elem);
  9964. if (lb_is_elem_const(fv->value, et)) {
  9965. continue;
  9966. }
  9967. if (is_ast_range(fv->field)) {
  9968. ast_node(ie, BinaryExpr, fv->field);
  9969. TypeAndValue lo_tav = ie->left->tav;
  9970. TypeAndValue hi_tav = ie->right->tav;
  9971. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9972. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9973. TokenKind op = ie->op.kind;
  9974. i64 lo = exact_value_to_i64(lo_tav.value);
  9975. i64 hi = exact_value_to_i64(hi_tav.value);
  9976. if (op == Token_Ellipsis) {
  9977. hi += 1;
  9978. }
  9979. lbValue value = lb_build_expr(p, fv->value);
  9980. for (i64 k = lo; k < hi; k++) {
  9981. lbCompoundLitElemTempData data = {};
  9982. data.value = value;
  9983. data.elem_index = cast(i32)k;
  9984. array_add(&temp_data, data);
  9985. }
  9986. } else {
  9987. auto tav = fv->field->tav;
  9988. GB_ASSERT(tav.mode == Addressing_Constant);
  9989. i64 index = exact_value_to_i64(tav.value);
  9990. lbValue value = lb_build_expr(p, fv->value);
  9991. lbCompoundLitElemTempData data = {};
  9992. data.value = lb_emit_conv(p, value, et);
  9993. data.expr = fv->value;
  9994. data.elem_index = cast(i32)index;
  9995. array_add(&temp_data, data);
  9996. }
  9997. } else {
  9998. if (lb_is_elem_const(elem, et)) {
  9999. continue;
  10000. }
  10001. lbCompoundLitElemTempData data = {};
  10002. data.expr = elem;
  10003. data.elem_index = cast(i32)i;
  10004. array_add(&temp_data, data);
  10005. }
  10006. }
  10007. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  10008. for_array(i, temp_data) {
  10009. i32 index = temp_data[i].elem_index - index_offset;
  10010. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  10011. }
  10012. for_array(i, temp_data) {
  10013. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  10014. auto return_ptr_hint_value = p->return_ptr_hint_value;
  10015. auto return_ptr_hint_used = p->return_ptr_hint_used;
  10016. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  10017. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  10018. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  10019. lbValue field_expr = temp_data[i].value;
  10020. Ast *expr = temp_data[i].expr;
  10021. p->return_ptr_hint_value = temp_data[i].gep;
  10022. p->return_ptr_hint_ast = unparen_expr(expr);
  10023. if (field_expr.value == nullptr) {
  10024. field_expr = lb_build_expr(p, expr);
  10025. }
  10026. Type *t = field_expr.type;
  10027. GB_ASSERT(t->kind != Type_Tuple);
  10028. lbValue ev = lb_emit_conv(p, field_expr, et);
  10029. if (!p->return_ptr_hint_used) {
  10030. temp_data[i].value = ev;
  10031. }
  10032. }
  10033. for_array(i, temp_data) {
  10034. if (temp_data[i].value.value != nullptr) {
  10035. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10036. }
  10037. }
  10038. }
  10039. break;
  10040. }
  10041. case Type_Slice: {
  10042. if (cl->elems.count > 0) {
  10043. Type *elem_type = bt->Slice.elem;
  10044. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  10045. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  10046. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  10047. lbValue data = lb_slice_elem(p, slice);
  10048. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  10049. for_array(i, cl->elems) {
  10050. Ast *elem = cl->elems[i];
  10051. if (elem->kind == Ast_FieldValue) {
  10052. ast_node(fv, FieldValue, elem);
  10053. if (lb_is_elem_const(fv->value, et)) {
  10054. continue;
  10055. }
  10056. if (is_ast_range(fv->field)) {
  10057. ast_node(ie, BinaryExpr, fv->field);
  10058. TypeAndValue lo_tav = ie->left->tav;
  10059. TypeAndValue hi_tav = ie->right->tav;
  10060. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10061. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10062. TokenKind op = ie->op.kind;
  10063. i64 lo = exact_value_to_i64(lo_tav.value);
  10064. i64 hi = exact_value_to_i64(hi_tav.value);
  10065. if (op == Token_Ellipsis) {
  10066. hi += 1;
  10067. }
  10068. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10069. for (i64 k = lo; k < hi; k++) {
  10070. lbCompoundLitElemTempData data = {};
  10071. data.value = value;
  10072. data.elem_index = cast(i32)k;
  10073. array_add(&temp_data, data);
  10074. }
  10075. } else {
  10076. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10077. i64 index = exact_value_to_i64(fv->field->tav.value);
  10078. lbValue field_expr = lb_build_expr(p, fv->value);
  10079. GB_ASSERT(!is_type_tuple(field_expr.type));
  10080. lbValue ev = lb_emit_conv(p, field_expr, et);
  10081. lbCompoundLitElemTempData data = {};
  10082. data.value = ev;
  10083. data.elem_index = cast(i32)index;
  10084. array_add(&temp_data, data);
  10085. }
  10086. } else {
  10087. if (lb_is_elem_const(elem, et)) {
  10088. continue;
  10089. }
  10090. lbValue field_expr = lb_build_expr(p, elem);
  10091. GB_ASSERT(!is_type_tuple(field_expr.type));
  10092. lbValue ev = lb_emit_conv(p, field_expr, et);
  10093. lbCompoundLitElemTempData data = {};
  10094. data.value = ev;
  10095. data.elem_index = cast(i32)i;
  10096. array_add(&temp_data, data);
  10097. }
  10098. }
  10099. for_array(i, temp_data) {
  10100. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  10101. }
  10102. for_array(i, temp_data) {
  10103. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  10104. }
  10105. {
  10106. lbValue count = {};
  10107. count.type = t_int;
  10108. if (lb_is_const(slice)) {
  10109. unsigned indices[1] = {1};
  10110. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  10111. } else {
  10112. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  10113. }
  10114. lb_fill_slice(p, v, data, count);
  10115. }
  10116. }
  10117. break;
  10118. }
  10119. case Type_DynamicArray: {
  10120. if (cl->elems.count == 0) {
  10121. break;
  10122. }
  10123. Type *et = bt->DynamicArray.elem;
  10124. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  10125. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  10126. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  10127. {
  10128. auto args = array_make<lbValue>(permanent_allocator(), 5);
  10129. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  10130. args[1] = size;
  10131. args[2] = align;
  10132. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  10133. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  10134. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  10135. }
  10136. lbValue items = lb_generate_local_array(p, et, item_count);
  10137. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  10138. for_array(i, cl->elems) {
  10139. Ast *elem = cl->elems[i];
  10140. if (elem->kind == Ast_FieldValue) {
  10141. ast_node(fv, FieldValue, elem);
  10142. if (is_ast_range(fv->field)) {
  10143. ast_node(ie, BinaryExpr, fv->field);
  10144. TypeAndValue lo_tav = ie->left->tav;
  10145. TypeAndValue hi_tav = ie->right->tav;
  10146. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  10147. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  10148. TokenKind op = ie->op.kind;
  10149. i64 lo = exact_value_to_i64(lo_tav.value);
  10150. i64 hi = exact_value_to_i64(hi_tav.value);
  10151. if (op == Token_Ellipsis) {
  10152. hi += 1;
  10153. }
  10154. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  10155. for (i64 k = lo; k < hi; k++) {
  10156. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  10157. lb_emit_store(p, ep, value);
  10158. }
  10159. } else {
  10160. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  10161. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  10162. lbValue ev = lb_build_expr(p, fv->value);
  10163. lbValue value = lb_emit_conv(p, ev, et);
  10164. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  10165. lb_emit_store(p, ep, value);
  10166. }
  10167. } else {
  10168. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  10169. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  10170. lb_emit_store(p, ep, value);
  10171. }
  10172. }
  10173. {
  10174. auto args = array_make<lbValue>(permanent_allocator(), 6);
  10175. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  10176. args[1] = size;
  10177. args[2] = align;
  10178. args[3] = lb_emit_conv(p, items, t_rawptr);
  10179. args[4] = lb_const_int(p->module, t_int, item_count);
  10180. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  10181. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  10182. }
  10183. break;
  10184. }
  10185. case Type_Basic: {
  10186. GB_ASSERT(is_type_any(bt));
  10187. if (cl->elems.count > 0) {
  10188. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10189. String field_names[2] = {
  10190. str_lit("data"),
  10191. str_lit("id"),
  10192. };
  10193. Type *field_types[2] = {
  10194. t_rawptr,
  10195. t_typeid,
  10196. };
  10197. for_array(field_index, cl->elems) {
  10198. Ast *elem = cl->elems[field_index];
  10199. lbValue field_expr = {};
  10200. isize index = field_index;
  10201. if (elem->kind == Ast_FieldValue) {
  10202. ast_node(fv, FieldValue, elem);
  10203. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  10204. index = sel.index[0];
  10205. elem = fv->value;
  10206. } else {
  10207. TypeAndValue tav = type_and_value_of_expr(elem);
  10208. Selection sel = lookup_field(bt, field_names[field_index], false);
  10209. index = sel.index[0];
  10210. }
  10211. field_expr = lb_build_expr(p, elem);
  10212. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  10213. Type *ft = field_types[index];
  10214. lbValue fv = lb_emit_conv(p, field_expr, ft);
  10215. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  10216. lb_emit_store(p, gep, fv);
  10217. }
  10218. }
  10219. break;
  10220. }
  10221. case Type_BitSet: {
  10222. i64 sz = type_size_of(type);
  10223. if (cl->elems.count > 0 && sz > 0) {
  10224. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  10225. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  10226. for_array(i, cl->elems) {
  10227. Ast *elem = cl->elems[i];
  10228. GB_ASSERT(elem->kind != Ast_FieldValue);
  10229. if (lb_is_elem_const(elem, et)) {
  10230. continue;
  10231. }
  10232. lbValue expr = lb_build_expr(p, elem);
  10233. GB_ASSERT(expr.type->kind != Type_Tuple);
  10234. Type *it = bit_set_to_int(bt);
  10235. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  10236. lbValue e = lb_emit_conv(p, expr, it);
  10237. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  10238. e = lb_emit_arith(p, Token_Shl, one, e, it);
  10239. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  10240. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  10241. new_value = lb_emit_transmute(p, new_value, type);
  10242. lb_addr_store(p, v, new_value);
  10243. }
  10244. }
  10245. break;
  10246. }
  10247. }
  10248. return v;
  10249. case_end;
  10250. case_ast_node(tc, TypeCast, expr);
  10251. Type *type = type_of_expr(expr);
  10252. lbValue x = lb_build_expr(p, tc->expr);
  10253. lbValue e = {};
  10254. switch (tc->token.kind) {
  10255. case Token_cast:
  10256. e = lb_emit_conv(p, x, type);
  10257. break;
  10258. case Token_transmute:
  10259. e = lb_emit_transmute(p, x, type);
  10260. break;
  10261. default:
  10262. GB_PANIC("Invalid AST TypeCast");
  10263. }
  10264. lbAddr v = lb_add_local_generated(p, type, false);
  10265. lb_addr_store(p, v, e);
  10266. return v;
  10267. case_end;
  10268. case_ast_node(ac, AutoCast, expr);
  10269. return lb_build_addr(p, ac->expr);
  10270. case_end;
  10271. }
  10272. TokenPos token_pos = ast_token(expr).pos;
  10273. GB_PANIC("Unexpected address expression\n"
  10274. "\tAst: %.*s @ "
  10275. "%s\n",
  10276. LIT(ast_strings[expr->kind]),
  10277. token_pos_to_string(token_pos));
  10278. return {};
  10279. }
  10280. void lb_init_module(lbModule *m, Checker *c) {
  10281. m->info = &c->info;
  10282. m->ctx = LLVMGetGlobalContext();
  10283. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  10284. // m->debug_builder = nullptr;
  10285. if (build_context.ODIN_DEBUG) {
  10286. enum {DEBUG_METADATA_VERSION = 3};
  10287. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  10288. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  10289. if (build_context.metrics.os == TargetOs_windows) {
  10290. LLVMMetadataRef ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true));
  10291. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "CodeView", 8, ref);
  10292. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  10293. }
  10294. }
  10295. m->state_flags = 0;
  10296. m->state_flags |= StateFlag_bounds_check;
  10297. gb_mutex_init(&m->mutex);
  10298. gbAllocator a = heap_allocator();
  10299. map_init(&m->types, a);
  10300. map_init(&m->llvm_types, a);
  10301. map_init(&m->values, a);
  10302. map_init(&m->soa_values, a);
  10303. string_map_init(&m->members, a);
  10304. map_init(&m->procedure_values, a);
  10305. string_map_init(&m->procedures, a);
  10306. string_map_init(&m->const_strings, a);
  10307. map_init(&m->anonymous_proc_lits, a);
  10308. map_init(&m->function_type_map, a);
  10309. map_init(&m->equal_procs, a);
  10310. map_init(&m->hasher_procs, a);
  10311. array_init(&m->procedures_to_generate, a, 0, 1024);
  10312. array_init(&m->foreign_library_paths, a, 0, 1024);
  10313. map_init(&m->debug_values, a);
  10314. array_init(&m->debug_incomplete_types, a, 0, 1024);
  10315. }
  10316. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  10317. if (global_error_collector.count != 0) {
  10318. return false;
  10319. }
  10320. isize tc = c->parser->total_token_count;
  10321. if (tc < 2) {
  10322. return false;
  10323. }
  10324. String init_fullpath = c->parser->init_fullpath;
  10325. if (build_context.out_filepath.len == 0) {
  10326. gen->output_name = remove_directory_from_path(init_fullpath);
  10327. gen->output_name = remove_extension_from_path(gen->output_name);
  10328. gen->output_name = string_trim_whitespace(gen->output_name);
  10329. if (gen->output_name.len == 0) {
  10330. gen->output_name = c->info.init_scope->pkg->name;
  10331. }
  10332. gen->output_base = gen->output_name;
  10333. } else {
  10334. gen->output_name = build_context.out_filepath;
  10335. gen->output_name = string_trim_whitespace(gen->output_name);
  10336. if (gen->output_name.len == 0) {
  10337. gen->output_name = c->info.init_scope->pkg->name;
  10338. }
  10339. isize pos = string_extension_position(gen->output_name);
  10340. if (pos < 0) {
  10341. gen->output_base = gen->output_name;
  10342. } else {
  10343. gen->output_base = substring(gen->output_name, 0, pos);
  10344. }
  10345. }
  10346. gbAllocator ha = heap_allocator();
  10347. array_init(&gen->output_object_paths, ha);
  10348. gen->output_base = path_to_full_path(ha, gen->output_base);
  10349. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  10350. output_file_path = gb_string_appendc(output_file_path, ".obj");
  10351. defer (gb_string_free(output_file_path));
  10352. gen->info = &c->info;
  10353. lb_init_module(&gen->module, c);
  10354. return true;
  10355. }
  10356. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  10357. GB_ASSERT(type != nullptr);
  10358. type = default_type(type);
  10359. isize max_len = 7+8+1;
  10360. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  10361. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  10362. m->global_generated_index++;
  10363. String name = make_string(str, len-1);
  10364. Scope *scope = nullptr;
  10365. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  10366. lbValue g = {};
  10367. g.type = alloc_type_pointer(type);
  10368. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  10369. if (value.value != nullptr) {
  10370. GB_ASSERT(LLVMIsConstant(value.value));
  10371. LLVMSetInitializer(g.value, value.value);
  10372. } else {
  10373. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  10374. }
  10375. lb_add_entity(m, e, g);
  10376. lb_add_member(m, name, g);
  10377. return lb_addr(g);
  10378. }
  10379. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  10380. AstPackage *p = m->info->runtime_package;
  10381. Entity *e = scope_lookup_current(p->scope, name);
  10382. lbValue *found = map_get(&m->values, hash_entity(e));
  10383. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  10384. lbValue value = *found;
  10385. return value;
  10386. }
  10387. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  10388. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  10389. lbValue *found = map_get(&m->values, hash_entity(e));
  10390. GB_ASSERT_MSG(found != nullptr, "Unable to find value '%.*s.%.*s'", LIT(pkg), LIT(name));
  10391. lbValue value = *found;
  10392. return value;
  10393. }
  10394. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  10395. i32 index = cast(i32)lb_type_info_index(m->info, type);
  10396. GB_ASSERT(index >= 0);
  10397. // gb_printf_err("%d %s\n", index, type_to_string(type));
  10398. LLVMValueRef indices[2] = {
  10399. LLVMConstInt(lb_type(m, t_int), 0, false),
  10400. LLVMConstInt(lb_type(m, t_int), index, false),
  10401. };
  10402. lbValue res = {};
  10403. res.type = t_type_info_ptr;
  10404. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  10405. return res;
  10406. }
  10407. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  10408. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  10409. lb_global_type_info_member_types_index += cast(i32)count;
  10410. return offset;
  10411. }
  10412. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  10413. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  10414. lb_global_type_info_member_names_index += cast(i32)count;
  10415. return offset;
  10416. }
  10417. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  10418. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  10419. lb_global_type_info_member_offsets_index += cast(i32)count;
  10420. return offset;
  10421. }
  10422. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  10423. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  10424. lb_global_type_info_member_usings_index += cast(i32)count;
  10425. return offset;
  10426. }
  10427. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  10428. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  10429. lb_global_type_info_member_tags_index += cast(i32)count;
  10430. return offset;
  10431. }
  10432. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  10433. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  10434. return lb_addr_get_ptr(p, addr);
  10435. }
  10436. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  10437. Token token = {Token_Ident};
  10438. isize name_len = prefix.len + 1 + 20;
  10439. auto suffix_id = cast(unsigned long long)id;
  10440. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  10441. gb_snprintf(text, name_len,
  10442. "%.*s-%llu", LIT(prefix), suffix_id);
  10443. text[name_len] = 0;
  10444. String s = make_string_c(text);
  10445. Type *t = alloc_type_array(elem_type, count);
  10446. lbValue g = {};
  10447. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  10448. g.type = alloc_type_pointer(t);
  10449. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  10450. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  10451. string_map_set(&m->members, s, g);
  10452. return g;
  10453. }
  10454. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  10455. lbModule *m = p->module;
  10456. LLVMContextRef ctx = m->ctx;
  10457. CheckerInfo *info = m->info;
  10458. {
  10459. // NOTE(bill): Set the type_table slice with the global backing array
  10460. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  10461. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  10462. GB_ASSERT(is_type_array(type));
  10463. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  10464. LLVMValueRef values[2] = {
  10465. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  10466. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  10467. };
  10468. LLVMValueRef slice = llvm_const_named_struct(llvm_addr_type(global_type_table), values, gb_count_of(values));
  10469. LLVMSetInitializer(global_type_table.value, slice);
  10470. }
  10471. // Useful types
  10472. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  10473. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  10474. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  10475. Type *t_type_info_flags = type_info_flags_entity->type;
  10476. i32 type_info_member_types_index = 0;
  10477. i32 type_info_member_names_index = 0;
  10478. i32 type_info_member_offsets_index = 0;
  10479. for_array(type_info_type_index, info->type_info_types) {
  10480. Type *t = info->type_info_types[type_info_type_index];
  10481. if (t == nullptr || t == t_invalid) {
  10482. continue;
  10483. }
  10484. isize entry_index = lb_type_info_index(info, t, false);
  10485. if (entry_index <= 0) {
  10486. continue;
  10487. }
  10488. lbValue tag = {};
  10489. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  10490. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  10491. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  10492. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  10493. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  10494. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  10495. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  10496. switch (t->kind) {
  10497. case Type_Named: {
  10498. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  10499. LLVMValueRef pkg_name = nullptr;
  10500. if (t->Named.type_name->pkg) {
  10501. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  10502. } else {
  10503. pkg_name = LLVMConstNull(lb_type(m, t_string));
  10504. }
  10505. String proc_name = {};
  10506. if (t->Named.type_name->parent_proc_decl) {
  10507. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  10508. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  10509. proc_name = decl->entity->token.string;
  10510. }
  10511. }
  10512. TokenPos pos = t->Named.type_name->token.pos;
  10513. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  10514. LLVMValueRef vals[4] = {
  10515. lb_const_string(p->module, t->Named.type_name->token.string).value,
  10516. lb_get_type_info_ptr(m, t->Named.base).value,
  10517. pkg_name,
  10518. loc.value
  10519. };
  10520. lbValue res = {};
  10521. res.type = type_deref(tag.type);
  10522. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10523. lb_emit_store(p, tag, res);
  10524. break;
  10525. }
  10526. case Type_Basic:
  10527. switch (t->Basic.kind) {
  10528. case Basic_bool:
  10529. case Basic_b8:
  10530. case Basic_b16:
  10531. case Basic_b32:
  10532. case Basic_b64:
  10533. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  10534. break;
  10535. case Basic_i8:
  10536. case Basic_u8:
  10537. case Basic_i16:
  10538. case Basic_u16:
  10539. case Basic_i32:
  10540. case Basic_u32:
  10541. case Basic_i64:
  10542. case Basic_u64:
  10543. case Basic_i128:
  10544. case Basic_u128:
  10545. case Basic_i16le:
  10546. case Basic_u16le:
  10547. case Basic_i32le:
  10548. case Basic_u32le:
  10549. case Basic_i64le:
  10550. case Basic_u64le:
  10551. case Basic_i128le:
  10552. case Basic_u128le:
  10553. case Basic_i16be:
  10554. case Basic_u16be:
  10555. case Basic_i32be:
  10556. case Basic_u32be:
  10557. case Basic_i64be:
  10558. case Basic_u64be:
  10559. case Basic_i128be:
  10560. case Basic_u128be:
  10561. case Basic_int:
  10562. case Basic_uint:
  10563. case Basic_uintptr: {
  10564. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  10565. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  10566. // NOTE(bill): This is matches the runtime layout
  10567. u8 endianness_value = 0;
  10568. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10569. endianness_value = 1;
  10570. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10571. endianness_value = 2;
  10572. }
  10573. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10574. LLVMValueRef vals[2] = {
  10575. is_signed.value,
  10576. endianness.value,
  10577. };
  10578. lbValue res = {};
  10579. res.type = type_deref(tag.type);
  10580. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10581. lb_emit_store(p, tag, res);
  10582. break;
  10583. }
  10584. case Basic_rune:
  10585. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  10586. break;
  10587. // case Basic_f16:
  10588. case Basic_f32:
  10589. case Basic_f64:
  10590. case Basic_f32le:
  10591. case Basic_f64le:
  10592. case Basic_f32be:
  10593. case Basic_f64be:
  10594. {
  10595. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  10596. // NOTE(bill): This is matches the runtime layout
  10597. u8 endianness_value = 0;
  10598. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10599. endianness_value = 1;
  10600. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10601. endianness_value = 2;
  10602. }
  10603. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10604. LLVMValueRef vals[1] = {
  10605. endianness.value,
  10606. };
  10607. lbValue res = {};
  10608. res.type = type_deref(tag.type);
  10609. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10610. lb_emit_store(p, tag, res);
  10611. }
  10612. break;
  10613. // case Basic_complex32:
  10614. case Basic_complex64:
  10615. case Basic_complex128:
  10616. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  10617. break;
  10618. case Basic_quaternion128:
  10619. case Basic_quaternion256:
  10620. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  10621. break;
  10622. case Basic_rawptr:
  10623. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10624. break;
  10625. case Basic_string:
  10626. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10627. break;
  10628. case Basic_cstring:
  10629. {
  10630. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10631. LLVMValueRef vals[1] = {
  10632. lb_const_bool(m, t_bool, true).value,
  10633. };
  10634. lbValue res = {};
  10635. res.type = type_deref(tag.type);
  10636. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10637. lb_emit_store(p, tag, res);
  10638. }
  10639. break;
  10640. case Basic_any:
  10641. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  10642. break;
  10643. case Basic_typeid:
  10644. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  10645. break;
  10646. }
  10647. break;
  10648. case Type_Pointer: {
  10649. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10650. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  10651. LLVMValueRef vals[1] = {
  10652. gep.value,
  10653. };
  10654. lbValue res = {};
  10655. res.type = type_deref(tag.type);
  10656. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10657. lb_emit_store(p, tag, res);
  10658. break;
  10659. }
  10660. case Type_Array: {
  10661. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  10662. i64 ez = type_size_of(t->Array.elem);
  10663. LLVMValueRef vals[3] = {
  10664. lb_get_type_info_ptr(m, t->Array.elem).value,
  10665. lb_const_int(m, t_int, ez).value,
  10666. lb_const_int(m, t_int, t->Array.count).value,
  10667. };
  10668. lbValue res = {};
  10669. res.type = type_deref(tag.type);
  10670. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10671. lb_emit_store(p, tag, res);
  10672. break;
  10673. }
  10674. case Type_EnumeratedArray: {
  10675. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  10676. LLVMValueRef vals[6] = {
  10677. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  10678. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  10679. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  10680. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  10681. // Unions
  10682. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10683. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10684. };
  10685. lbValue res = {};
  10686. res.type = type_deref(tag.type);
  10687. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10688. lb_emit_store(p, tag, res);
  10689. // NOTE(bill): Union assignment
  10690. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  10691. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  10692. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  10693. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  10694. lb_emit_store(p, min_value, min_v);
  10695. lb_emit_store(p, max_value, max_v);
  10696. break;
  10697. }
  10698. case Type_DynamicArray: {
  10699. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  10700. LLVMValueRef vals[2] = {
  10701. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  10702. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  10703. };
  10704. lbValue res = {};
  10705. res.type = type_deref(tag.type);
  10706. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10707. lb_emit_store(p, tag, res);
  10708. break;
  10709. }
  10710. case Type_Slice: {
  10711. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  10712. LLVMValueRef vals[2] = {
  10713. lb_get_type_info_ptr(m, t->Slice.elem).value,
  10714. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  10715. };
  10716. lbValue res = {};
  10717. res.type = type_deref(tag.type);
  10718. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10719. lb_emit_store(p, tag, res);
  10720. break;
  10721. }
  10722. case Type_Proc: {
  10723. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  10724. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10725. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10726. if (t->Proc.params != nullptr) {
  10727. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  10728. }
  10729. if (t->Proc.results != nullptr) {
  10730. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  10731. }
  10732. LLVMValueRef vals[4] = {
  10733. params,
  10734. results,
  10735. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  10736. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  10737. };
  10738. lbValue res = {};
  10739. res.type = type_deref(tag.type);
  10740. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10741. lb_emit_store(p, tag, res);
  10742. break;
  10743. }
  10744. case Type_Tuple: {
  10745. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  10746. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  10747. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  10748. for_array(i, t->Tuple.variables) {
  10749. // NOTE(bill): offset is not used for tuples
  10750. Entity *f = t->Tuple.variables[i];
  10751. lbValue index = lb_const_int(m, t_int, i);
  10752. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10753. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  10754. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10755. if (f->token.string.len > 0) {
  10756. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10757. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10758. }
  10759. }
  10760. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  10761. LLVMValueRef types_slice = llvm_const_slice(m, memory_types, count);
  10762. LLVMValueRef names_slice = llvm_const_slice(m, memory_names, count);
  10763. LLVMValueRef vals[2] = {
  10764. types_slice,
  10765. names_slice,
  10766. };
  10767. lbValue res = {};
  10768. res.type = type_deref(tag.type);
  10769. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10770. lb_emit_store(p, tag, res);
  10771. break;
  10772. }
  10773. case Type_Enum:
  10774. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  10775. {
  10776. GB_ASSERT(t->Enum.base_type != nullptr);
  10777. // GB_ASSERT_MSG(type_size_of(t_type_info_enum_value) == 16, "%lld == 16", cast(long long)type_size_of(t_type_info_enum_value));
  10778. LLVMValueRef vals[3] = {};
  10779. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  10780. if (t->Enum.fields.count > 0) {
  10781. auto fields = t->Enum.fields;
  10782. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  10783. str_lit("$enum_names"), cast(i64)entry_index);
  10784. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  10785. str_lit("$enum_values"), cast(i64)entry_index);
  10786. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10787. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10788. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10789. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  10790. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  10791. for_array(i, fields) {
  10792. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  10793. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  10794. }
  10795. LLVMValueRef name_init = llvm_const_array(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  10796. LLVMValueRef value_init = llvm_const_array(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  10797. LLVMSetInitializer(name_array.value, name_init);
  10798. LLVMSetInitializer(value_array.value, value_init);
  10799. lbValue v_count = lb_const_int(m, t_int, fields.count);
  10800. vals[1] = llvm_const_slice(m, lb_array_elem(p, name_array), v_count);
  10801. vals[2] = llvm_const_slice(m, lb_array_elem(p, value_array), v_count);
  10802. } else {
  10803. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  10804. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  10805. }
  10806. lbValue res = {};
  10807. res.type = type_deref(tag.type);
  10808. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10809. lb_emit_store(p, tag, res);
  10810. }
  10811. break;
  10812. case Type_Union: {
  10813. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  10814. {
  10815. LLVMValueRef vals[6] = {};
  10816. isize variant_count = gb_max(0, t->Union.variants.count);
  10817. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  10818. // NOTE(bill): Zeroth is nil so ignore it
  10819. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10820. Type *vt = t->Union.variants[variant_index];
  10821. lbValue tip = lb_get_type_info_ptr(m, vt);
  10822. lbValue index = lb_const_int(m, t_int, variant_index);
  10823. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10824. lb_emit_store(p, type_info, lb_type_info(m, vt));
  10825. }
  10826. lbValue count = lb_const_int(m, t_int, variant_count);
  10827. vals[0] = llvm_const_slice(m, memory_types, count);
  10828. i64 tag_size = union_tag_size(t);
  10829. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10830. if (tag_size > 0) {
  10831. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  10832. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  10833. } else {
  10834. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  10835. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10836. }
  10837. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  10838. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  10839. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  10840. lbValue res = {};
  10841. res.type = type_deref(tag.type);
  10842. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10843. lb_emit_store(p, tag, res);
  10844. }
  10845. break;
  10846. }
  10847. case Type_Struct: {
  10848. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  10849. LLVMValueRef vals[12] = {};
  10850. {
  10851. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  10852. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  10853. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  10854. vals[5] = is_packed.value;
  10855. vals[6] = is_raw_union.value;
  10856. vals[7] = is_custom_align.value;
  10857. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  10858. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  10859. }
  10860. if (t->Struct.soa_kind != StructSoa_None) {
  10861. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  10862. Type *kind_type = type_deref(kind.type);
  10863. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  10864. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  10865. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  10866. vals[9] = soa_kind.value;
  10867. vals[10] = soa_type.value;
  10868. vals[11] = soa_len.value;
  10869. }
  10870. }
  10871. isize count = t->Struct.fields.count;
  10872. if (count > 0) {
  10873. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  10874. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  10875. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  10876. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  10877. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  10878. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10879. for (isize source_index = 0; source_index < count; source_index++) {
  10880. // TODO(bill): Order fields in source order not layout order
  10881. Entity *f = t->Struct.fields[source_index];
  10882. lbValue tip = lb_get_type_info_ptr(m, f->type);
  10883. i64 foffset = 0;
  10884. if (!t->Struct.is_raw_union) {
  10885. foffset = t->Struct.offsets[f->Variable.field_index];
  10886. }
  10887. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10888. lbValue index = lb_const_int(m, t_int, source_index);
  10889. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10890. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  10891. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  10892. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10893. if (f->token.string.len > 0) {
  10894. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10895. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10896. }
  10897. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  10898. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  10899. if (t->Struct.tags.count > 0) {
  10900. String tag_string = t->Struct.tags[source_index];
  10901. if (tag_string.len > 0) {
  10902. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  10903. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  10904. }
  10905. }
  10906. }
  10907. lbValue cv = lb_const_int(m, t_int, count);
  10908. vals[0] = llvm_const_slice(m, memory_types, cv);
  10909. vals[1] = llvm_const_slice(m, memory_names, cv);
  10910. vals[2] = llvm_const_slice(m, memory_offsets, cv);
  10911. vals[3] = llvm_const_slice(m, memory_usings, cv);
  10912. vals[4] = llvm_const_slice(m, memory_tags, cv);
  10913. }
  10914. for (isize i = 0; i < gb_count_of(vals); i++) {
  10915. if (vals[i] == nullptr) {
  10916. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  10917. }
  10918. }
  10919. lbValue res = {};
  10920. res.type = type_deref(tag.type);
  10921. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10922. lb_emit_store(p, tag, res);
  10923. break;
  10924. }
  10925. case Type_Map: {
  10926. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  10927. init_map_internal_types(t);
  10928. LLVMValueRef vals[5] = {
  10929. lb_get_type_info_ptr(m, t->Map.key).value,
  10930. lb_get_type_info_ptr(m, t->Map.value).value,
  10931. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  10932. lb_get_equal_proc_for_type(m, t->Map.key).value,
  10933. lb_get_hasher_proc_for_type(m, t->Map.key).value
  10934. };
  10935. lbValue res = {};
  10936. res.type = type_deref(tag.type);
  10937. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10938. lb_emit_store(p, tag, res);
  10939. break;
  10940. }
  10941. case Type_BitSet:
  10942. {
  10943. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  10944. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10945. LLVMValueRef vals[4] = {
  10946. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  10947. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  10948. lb_const_int(m, t_i64, t->BitSet.lower).value,
  10949. lb_const_int(m, t_i64, t->BitSet.upper).value,
  10950. };
  10951. if (t->BitSet.underlying != nullptr) {
  10952. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  10953. }
  10954. lbValue res = {};
  10955. res.type = type_deref(tag.type);
  10956. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10957. lb_emit_store(p, tag, res);
  10958. }
  10959. break;
  10960. case Type_SimdVector:
  10961. {
  10962. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  10963. LLVMValueRef vals[4] = {};
  10964. if (t->SimdVector.is_x86_mmx) {
  10965. vals[3] = lb_const_bool(m, t_bool, true).value;
  10966. } else {
  10967. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  10968. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  10969. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  10970. }
  10971. lbValue res = {};
  10972. res.type = type_deref(tag.type);
  10973. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10974. lb_emit_store(p, tag, res);
  10975. }
  10976. break;
  10977. case Type_RelativePointer:
  10978. {
  10979. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  10980. LLVMValueRef vals[2] = {
  10981. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  10982. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  10983. };
  10984. lbValue res = {};
  10985. res.type = type_deref(tag.type);
  10986. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  10987. lb_emit_store(p, tag, res);
  10988. }
  10989. break;
  10990. case Type_RelativeSlice:
  10991. {
  10992. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  10993. LLVMValueRef vals[2] = {
  10994. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  10995. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  10996. };
  10997. lbValue res = {};
  10998. res.type = type_deref(tag.type);
  10999. res.value = llvm_const_named_struct(lb_type(m, res.type), vals, gb_count_of(vals));
  11000. lb_emit_store(p, tag, res);
  11001. }
  11002. break;
  11003. }
  11004. if (tag.value != nullptr) {
  11005. Type *tag_type = type_deref(tag.type);
  11006. GB_ASSERT(is_type_named(tag_type));
  11007. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  11008. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  11009. } else {
  11010. if (t != t_llvm_bool) {
  11011. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  11012. }
  11013. }
  11014. }
  11015. }
  11016. void lb_generate_code(lbGenerator *gen) {
  11017. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  11018. TIME_SECTION("LLVM Initializtion");
  11019. lbModule *m = &gen->module;
  11020. LLVMModuleRef mod = gen->module.mod;
  11021. CheckerInfo *info = gen->info;
  11022. auto *min_dep_set = &info->minimum_dependency_set;
  11023. LLVMInitializeAllTargetInfos();
  11024. LLVMInitializeAllTargets();
  11025. LLVMInitializeAllTargetMCs();
  11026. LLVMInitializeAllAsmPrinters();
  11027. LLVMInitializeAllAsmParsers();
  11028. LLVMInitializeAllDisassemblers();
  11029. LLVMInitializeNativeTarget();
  11030. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  11031. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  11032. LLVMSetTarget(mod, target_triple);
  11033. LLVMTargetRef target = {};
  11034. char *llvm_error = nullptr;
  11035. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  11036. GB_ASSERT(target != nullptr);
  11037. TIME_SECTION("LLVM Create Target Machine");
  11038. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  11039. if (build_context.metrics.arch == TargetArch_wasm32) {
  11040. code_mode = LLVMCodeModelJITDefault;
  11041. }
  11042. char const *host_cpu_name = LLVMGetHostCPUName();
  11043. char const *llvm_cpu = "generic";
  11044. char const *llvm_features = "";
  11045. if (build_context.microarch.len != 0) {
  11046. if (build_context.microarch == "native") {
  11047. llvm_cpu = host_cpu_name;
  11048. } else {
  11049. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  11050. }
  11051. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  11052. llvm_features = LLVMGetHostCPUFeatures();
  11053. }
  11054. }
  11055. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  11056. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  11057. switch (build_context.optimization_level) {
  11058. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  11059. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  11060. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  11061. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  11062. }
  11063. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  11064. defer (LLVMDisposeTargetMachine(target_machine));
  11065. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  11066. if (m->debug_builder) { // Debug Info
  11067. for_array(i, info->files.entries) {
  11068. AstFile *f = info->files.entries[i].value;
  11069. String fullpath = f->fullpath;
  11070. String filename = remove_directory_from_path(fullpath);
  11071. String directory = directory_from_path(fullpath);
  11072. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  11073. cast(char const *)filename.text, filename.len,
  11074. cast(char const *)directory.text, directory.len);
  11075. lb_set_llvm_metadata(m, f, res);
  11076. }
  11077. gbString producer = gb_string_make(heap_allocator(), "odin");
  11078. producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  11079. #ifdef NIGHTLY
  11080. producer = gb_string_appendc(producer, "-nightly");
  11081. #endif
  11082. #ifdef GIT_SHA
  11083. producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  11084. #endif
  11085. gbString split_name = gb_string_make(heap_allocator(), "");
  11086. LLVMBool is_optimized = build_context.optimization_level > 0;
  11087. AstFile *init_file = m->info->init_package->files[0];
  11088. if (m->info->entry_point && m->info->entry_point->identifier && m->info->entry_point->identifier->file) {
  11089. init_file = m->info->entry_point->identifier->file;
  11090. }
  11091. LLVMBool split_debug_inlining = false;
  11092. LLVMBool debug_info_for_profiling = false;
  11093. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  11094. lb_get_llvm_metadata(m, init_file),
  11095. producer, gb_string_length(producer),
  11096. is_optimized, "", 0,
  11097. 1, split_name, gb_string_length(split_name),
  11098. LLVMDWARFEmissionFull,
  11099. 0, split_debug_inlining,
  11100. debug_info_for_profiling,
  11101. "", 0, // sys_root
  11102. "", 0 // SDK
  11103. );
  11104. GB_ASSERT(m->debug_compile_unit != nullptr);
  11105. }
  11106. TIME_SECTION("LLVM Global Variables");
  11107. {
  11108. { // Add type info data
  11109. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  11110. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  11111. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  11112. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  11113. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11114. LLVMSetLinkage(g, LLVMInternalLinkage);
  11115. lbValue value = {};
  11116. value.value = g;
  11117. value.type = alloc_type_pointer(t);
  11118. lb_global_type_info_data = lb_addr(value);
  11119. }
  11120. { // Type info member buffer
  11121. // NOTE(bill): Removes need for heap allocation by making it global memory
  11122. isize count = 0;
  11123. for_array(entry_index, m->info->type_info_types) {
  11124. Type *t = m->info->type_info_types[entry_index];
  11125. isize index = lb_type_info_index(m->info, t, false);
  11126. if (index < 0) {
  11127. continue;
  11128. }
  11129. switch (t->kind) {
  11130. case Type_Union:
  11131. count += t->Union.variants.count;
  11132. break;
  11133. case Type_Struct:
  11134. count += t->Struct.fields.count;
  11135. break;
  11136. case Type_Tuple:
  11137. count += t->Tuple.variables.count;
  11138. break;
  11139. }
  11140. }
  11141. if (count > 0) {
  11142. {
  11143. char const *name = LB_TYPE_INFO_TYPES_NAME;
  11144. Type *t = alloc_type_array(t_type_info_ptr, count);
  11145. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11146. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11147. LLVMSetLinkage(g, LLVMInternalLinkage);
  11148. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  11149. }
  11150. {
  11151. char const *name = LB_TYPE_INFO_NAMES_NAME;
  11152. Type *t = alloc_type_array(t_string, count);
  11153. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11154. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11155. LLVMSetLinkage(g, LLVMInternalLinkage);
  11156. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  11157. }
  11158. {
  11159. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  11160. Type *t = alloc_type_array(t_uintptr, count);
  11161. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11162. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11163. LLVMSetLinkage(g, LLVMInternalLinkage);
  11164. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  11165. }
  11166. {
  11167. char const *name = LB_TYPE_INFO_USINGS_NAME;
  11168. Type *t = alloc_type_array(t_bool, count);
  11169. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11170. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11171. LLVMSetLinkage(g, LLVMInternalLinkage);
  11172. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  11173. }
  11174. {
  11175. char const *name = LB_TYPE_INFO_TAGS_NAME;
  11176. Type *t = alloc_type_array(t_string, count);
  11177. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  11178. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  11179. LLVMSetLinkage(g, LLVMInternalLinkage);
  11180. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  11181. }
  11182. }
  11183. }
  11184. }
  11185. isize global_variable_max_count = 0;
  11186. Entity *entry_point = info->entry_point;
  11187. bool has_dll_main = false;
  11188. bool has_win_main = false;
  11189. for_array(i, info->entities) {
  11190. Entity *e = info->entities[i];
  11191. String name = e->token.string;
  11192. bool is_global = e->pkg != nullptr;
  11193. if (e->kind == Entity_Variable) {
  11194. global_variable_max_count++;
  11195. } else if (e->kind == Entity_Procedure && !is_global) {
  11196. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  11197. GB_ASSERT(e == entry_point);
  11198. // entry_point = e;
  11199. }
  11200. if (e->Procedure.is_export ||
  11201. (e->Procedure.link_name.len > 0) ||
  11202. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  11203. if (!has_dll_main && name == "DllMain") {
  11204. has_dll_main = true;
  11205. } else if (!has_win_main && name == "WinMain") {
  11206. has_win_main = true;
  11207. }
  11208. }
  11209. }
  11210. }
  11211. struct GlobalVariable {
  11212. lbValue var;
  11213. lbValue init;
  11214. DeclInfo *decl;
  11215. bool is_initialized;
  11216. };
  11217. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  11218. for_array(i, info->variable_init_order) {
  11219. DeclInfo *d = info->variable_init_order[i];
  11220. Entity *e = d->entity;
  11221. if ((e->scope->flags & ScopeFlag_File) == 0) {
  11222. continue;
  11223. }
  11224. if (!ptr_set_exists(min_dep_set, e)) {
  11225. continue;
  11226. }
  11227. DeclInfo *decl = decl_info_of_entity(e);
  11228. if (decl == nullptr) {
  11229. continue;
  11230. }
  11231. GB_ASSERT(e->kind == Entity_Variable);
  11232. bool is_foreign = e->Variable.is_foreign;
  11233. bool is_export = e->Variable.is_export;
  11234. String name = lb_get_entity_name(m, e);
  11235. lbValue g = {};
  11236. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  11237. g.type = alloc_type_pointer(e->type);
  11238. if (e->Variable.thread_local_model != "") {
  11239. LLVMSetThreadLocal(g.value, true);
  11240. String m = e->Variable.thread_local_model;
  11241. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  11242. if (m == "default") {
  11243. mode = LLVMGeneralDynamicTLSModel;
  11244. } else if (m == "localdynamic") {
  11245. mode = LLVMLocalDynamicTLSModel;
  11246. } else if (m == "initialexec") {
  11247. mode = LLVMInitialExecTLSModel;
  11248. } else if (m == "localexec") {
  11249. mode = LLVMLocalExecTLSModel;
  11250. } else {
  11251. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  11252. }
  11253. LLVMSetThreadLocalMode(g.value, mode);
  11254. }
  11255. if (is_foreign) {
  11256. LLVMSetExternallyInitialized(g.value, true);
  11257. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  11258. } else {
  11259. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  11260. }
  11261. if (is_export) {
  11262. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  11263. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  11264. }
  11265. if (e->flags & EntityFlag_Static) {
  11266. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  11267. }
  11268. GlobalVariable var = {};
  11269. var.var = g;
  11270. var.decl = decl;
  11271. if (decl->init_expr != nullptr) {
  11272. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  11273. if (!is_type_any(e->type)) {
  11274. if (tav.mode != Addressing_Invalid) {
  11275. if (tav.value.kind != ExactValue_Invalid) {
  11276. ExactValue v = tav.value;
  11277. lbValue init = lb_const_value(m, tav.type, v);
  11278. LLVMSetInitializer(g.value, init.value);
  11279. var.is_initialized = true;
  11280. }
  11281. }
  11282. }
  11283. if (!var.is_initialized &&
  11284. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  11285. var.is_initialized = true;
  11286. }
  11287. }
  11288. array_add(&global_variables, var);
  11289. lb_add_entity(m, e, g);
  11290. lb_add_member(m, name, g);
  11291. if (m->debug_builder) {
  11292. String global_name = e->token.string;
  11293. if (global_name.len != 0 && global_name != "_") {
  11294. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  11295. LLVMMetadataRef llvm_scope = llvm_file;
  11296. LLVMBool local_to_unit = e->flags & EntityFlag_Static;
  11297. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  11298. LLVMMetadataRef llvm_decl = nullptr;
  11299. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  11300. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  11301. m->debug_builder, llvm_scope,
  11302. cast(char const *)global_name.text, global_name.len,
  11303. "", 0, // linkage
  11304. llvm_file, e->token.pos.line,
  11305. lb_debug_type(m, e->type),
  11306. local_to_unit,
  11307. llvm_expr,
  11308. llvm_decl,
  11309. align_in_bits
  11310. );
  11311. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  11312. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  11313. }
  11314. }
  11315. }
  11316. TIME_SECTION("LLVM Global Procedures and Types");
  11317. for_array(i, info->entities) {
  11318. Entity *e = info->entities[i];
  11319. String name = e->token.string;
  11320. DeclInfo *decl = e->decl_info;
  11321. Scope * scope = e->scope;
  11322. if ((scope->flags & ScopeFlag_File) == 0) {
  11323. continue;
  11324. }
  11325. Scope *package_scope = scope->parent;
  11326. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  11327. switch (e->kind) {
  11328. case Entity_Variable:
  11329. // NOTE(bill): Handled above as it requires a specific load order
  11330. continue;
  11331. case Entity_ProcGroup:
  11332. continue;
  11333. case Entity_TypeName:
  11334. case Entity_Procedure:
  11335. break;
  11336. }
  11337. bool polymorphic_struct = false;
  11338. if (e->type != nullptr && e->kind == Entity_TypeName) {
  11339. Type *bt = base_type(e->type);
  11340. if (bt->kind == Type_Struct) {
  11341. polymorphic_struct = is_type_polymorphic(bt);
  11342. }
  11343. }
  11344. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  11345. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  11346. continue;
  11347. }
  11348. String mangled_name = lb_get_entity_name(m, e);
  11349. switch (e->kind) {
  11350. case Entity_TypeName:
  11351. lb_type(m, e->type);
  11352. break;
  11353. case Entity_Procedure:
  11354. {
  11355. lbProcedure *p = lb_create_procedure(m, e);
  11356. array_add(&m->procedures_to_generate, p);
  11357. }
  11358. break;
  11359. }
  11360. }
  11361. TIME_SECTION("LLVM Registry Initializtion");
  11362. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  11363. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  11364. defer (LLVMDisposePassManager(default_function_pass_manager));
  11365. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  11366. lb_populate_function_pass_manager(default_function_pass_manager, false);
  11367. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  11368. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  11369. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  11370. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11371. lb_populate_function_pass_manager(default_function_pass_manager_without_memcpy, true);
  11372. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  11373. TIME_SECTION("LLVM Runtime Type Information Creation");
  11374. lbProcedure *startup_type_info = nullptr;
  11375. lbProcedure *startup_runtime = nullptr;
  11376. { // Startup Type Info
  11377. Type *params = alloc_type_tuple();
  11378. Type *results = alloc_type_tuple();
  11379. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11380. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  11381. p->is_startup = true;
  11382. startup_type_info = p;
  11383. lb_begin_procedure_body(p);
  11384. lb_setup_type_info_data(p);
  11385. lb_end_procedure_body(p);
  11386. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11387. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11388. LLVMDumpValue(p->value);
  11389. gb_printf_err("\n\n\n\n");
  11390. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11391. }
  11392. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11393. }
  11394. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  11395. { // Startup Runtime
  11396. Type *params = alloc_type_tuple();
  11397. Type *results = alloc_type_tuple();
  11398. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  11399. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  11400. p->is_startup = true;
  11401. startup_runtime = p;
  11402. lb_begin_procedure_body(p);
  11403. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  11404. for_array(i, global_variables) {
  11405. auto *var = &global_variables[i];
  11406. if (var->is_initialized) {
  11407. continue;
  11408. }
  11409. Entity *e = var->decl->entity;
  11410. GB_ASSERT(e->kind == Entity_Variable);
  11411. if (var->decl->init_expr != nullptr) {
  11412. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  11413. lbValue init = lb_build_expr(p, var->decl->init_expr);
  11414. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  11415. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  11416. if (lb_is_const_or_global(init)) {
  11417. if (!var->is_initialized) {
  11418. LLVMSetInitializer(var->var.value, init.value);
  11419. var->is_initialized = true;
  11420. continue;
  11421. }
  11422. } else {
  11423. var->init = init;
  11424. }
  11425. }
  11426. if (var->init.value != nullptr) {
  11427. GB_ASSERT(!var->is_initialized);
  11428. Type *t = type_deref(var->var.type);
  11429. if (is_type_any(t)) {
  11430. // NOTE(bill): Edge case for 'any' type
  11431. Type *var_type = default_type(var->init.type);
  11432. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  11433. lb_addr_store(p, g, var->init);
  11434. lbValue gp = lb_addr_get_ptr(p, g);
  11435. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  11436. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  11437. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  11438. lb_emit_store(p, ti, lb_type_info(m, var_type));
  11439. } else {
  11440. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  11441. LLVMTypeRef vt = LLVMGetElementType(pvt);
  11442. lbValue src0 = lb_emit_conv(p, var->init, t);
  11443. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  11444. LLVMValueRef dst = var->var.value;
  11445. LLVMBuildStore(p->builder, src, dst);
  11446. }
  11447. var->is_initialized = true;
  11448. }
  11449. }
  11450. lb_end_procedure_body(p);
  11451. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11452. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11453. LLVMDumpValue(p->value);
  11454. gb_printf_err("\n\n\n\n");
  11455. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11456. }
  11457. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11458. /*{
  11459. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  11460. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  11461. instr != last_instr;
  11462. instr = LLVMGetNextInstruction(instr)) {
  11463. if (LLVMIsAAllocaInst(instr)) {
  11464. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  11465. LLVMValueRef sz_val = LLVMSizeOf(type);
  11466. GB_ASSERT(LLVMIsConstant(sz_val));
  11467. gb_printf_err(">> 0x%p\n", sz_val);
  11468. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  11469. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  11470. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  11471. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  11472. gb_printf_err(">> %ll\n", sz);
  11473. }
  11474. }
  11475. }*/
  11476. }
  11477. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  11478. TIME_SECTION("LLVM DLL main");
  11479. Type *params = alloc_type_tuple();
  11480. Type *results = alloc_type_tuple();
  11481. String name = str_lit("main");
  11482. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  11483. name = str_lit("mainCRTStartup");
  11484. } else {
  11485. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  11486. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  11487. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  11488. }
  11489. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  11490. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  11491. Type *proc_type = alloc_type_proc(nullptr,
  11492. params, params->Tuple.variables.count,
  11493. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  11494. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  11495. p->is_startup = true;
  11496. lb_begin_procedure_body(p);
  11497. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  11498. if (build_context.command_kind == Command_test) {
  11499. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  11500. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  11501. Type *slice_type = alloc_type_slice(t_Internal_Test);
  11502. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  11503. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  11504. LLVMTypeRef lbt_Internal_Test = lb_type(m, t_Internal_Test);
  11505. LLVMValueRef indices[2] = {};
  11506. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  11507. for_array(i, m->info->testing_procedures) {
  11508. Entity *testing_proc = m->info->testing_procedures[i];
  11509. String name = testing_proc->token.string;
  11510. lbValue *found = map_get(&m->values, hash_entity(testing_proc));
  11511. GB_ASSERT(found != nullptr);
  11512. String pkg_name = {};
  11513. if (testing_proc->pkg != nullptr) {
  11514. pkg_name = testing_proc->pkg->name;
  11515. }
  11516. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  11517. lbValue v_name = lb_find_or_add_entity_string(m, name);
  11518. lbValue v_proc = *found;
  11519. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  11520. LLVMValueRef vals[3] = {};
  11521. vals[0] = v_pkg.value;
  11522. vals[1] = v_name.value;
  11523. vals[2] = v_proc.value;
  11524. GB_ASSERT(LLVMIsConstant(vals[0]));
  11525. GB_ASSERT(LLVMIsConstant(vals[1]));
  11526. GB_ASSERT(LLVMIsConstant(vals[2]));
  11527. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  11528. LLVMValueRef src = llvm_const_named_struct(lbt_Internal_Test, vals, gb_count_of(vals));
  11529. LLVMBuildStore(p->builder, src, dst);
  11530. }
  11531. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  11532. lb_fill_slice(p, all_tests_slice,
  11533. lb_array_elem(p, all_tests_array),
  11534. lb_const_int(m, t_int, m->info->testing_procedures.count));
  11535. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  11536. auto args = array_make<lbValue>(heap_allocator(), 1);
  11537. args[0] = lb_addr_load(p, all_tests_slice);
  11538. lb_emit_call(p, runner, args);
  11539. } else {
  11540. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  11541. GB_ASSERT(found != nullptr);
  11542. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  11543. }
  11544. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  11545. lb_end_procedure_body(p);
  11546. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11547. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  11548. LLVMDumpValue(p->value);
  11549. gb_printf_err("\n\n\n\n");
  11550. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  11551. }
  11552. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11553. }
  11554. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  11555. TIME_SECTION("LLVM Procedure Generation");
  11556. for_array(i, m->procedures_to_generate) {
  11557. lbProcedure *p = m->procedures_to_generate[i];
  11558. if (p->is_done) {
  11559. continue;
  11560. }
  11561. if (p->body != nullptr) { // Build Procedure
  11562. m->curr_procedure = p;
  11563. lb_begin_procedure_body(p);
  11564. lb_build_stmt(p, p->body);
  11565. lb_end_procedure_body(p);
  11566. p->is_done = true;
  11567. m->curr_procedure = nullptr;
  11568. }
  11569. lb_end_procedure(p);
  11570. // Add Flags
  11571. if (p->body != nullptr) {
  11572. if (p->name == "memcpy" || p->name == "memmove" ||
  11573. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  11574. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  11575. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  11576. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  11577. }
  11578. }
  11579. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11580. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  11581. LLVMDumpValue(p->value);
  11582. gb_printf_err("\n\n\n\n");
  11583. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11584. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11585. }
  11586. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  11587. gb_exit(1);
  11588. }
  11589. }
  11590. if (m->debug_builder != nullptr) {
  11591. TIME_SECTION("LLVM Debug Info Complete Types");
  11592. lb_debug_complete_types(m);
  11593. TIME_SECTION("LLVM Print Module to File");
  11594. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11595. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11596. gb_exit(1);
  11597. return;
  11598. }
  11599. TIME_SECTION("LLVM Debug Info Builder Finalize");
  11600. LLVMDIBuilderFinalize(m->debug_builder);
  11601. }
  11602. TIME_SECTION("LLVM Function Pass");
  11603. {
  11604. for_array(i, m->procedures_to_generate) {
  11605. lbProcedure *p = m->procedures_to_generate[i];
  11606. if (p->body != nullptr) { // Build Procedure
  11607. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  11608. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  11609. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  11610. } else {
  11611. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11612. }
  11613. }
  11614. }
  11615. }
  11616. for_array(i, m->equal_procs.entries) {
  11617. lbProcedure *p = m->equal_procs.entries[i].value;
  11618. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11619. }
  11620. for_array(i, m->hasher_procs.entries) {
  11621. lbProcedure *p = m->hasher_procs.entries[i].value;
  11622. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11623. }
  11624. }
  11625. TIME_SECTION("LLVM Module Pass");
  11626. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  11627. defer (LLVMDisposePassManager(module_pass_manager));
  11628. lb_populate_module_pass_manager(target_machine, module_pass_manager);
  11629. LLVMRunPassManager(module_pass_manager, mod);
  11630. llvm_error = nullptr;
  11631. defer (LLVMDisposeMessage(llvm_error));
  11632. String filepath_obj = {};
  11633. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  11634. if (build_context.build_mode == BuildMode_Assembly) {
  11635. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  11636. code_gen_file_type = LLVMAssemblyFile;
  11637. } else {
  11638. switch (build_context.metrics.os) {
  11639. case TargetOs_windows:
  11640. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  11641. break;
  11642. case TargetOs_darwin:
  11643. case TargetOs_linux:
  11644. case TargetOs_essence:
  11645. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  11646. break;
  11647. case TargetOs_js:
  11648. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  11649. break;
  11650. }
  11651. }
  11652. if (LLVMVerifyModule(mod, LLVMReturnStatusAction, &llvm_error)) {
  11653. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  11654. if (build_context.keep_temp_files) {
  11655. TIME_SECTION("LLVM Print Module to File");
  11656. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11657. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11658. gb_exit(1);
  11659. return;
  11660. }
  11661. }
  11662. gb_exit(1);
  11663. return;
  11664. }
  11665. llvm_error = nullptr;
  11666. if (build_context.keep_temp_files) {
  11667. TIME_SECTION("LLVM Print Module to File");
  11668. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11669. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11670. gb_exit(1);
  11671. return;
  11672. }
  11673. }
  11674. TIME_SECTION("LLVM Object Generation");
  11675. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  11676. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11677. gb_exit(1);
  11678. return;
  11679. }
  11680. array_add(&gen->output_object_paths, filepath_obj);
  11681. for_array(i, m->info->required_foreign_imports_through_force) {
  11682. Entity *e = m->info->required_foreign_imports_through_force[i];
  11683. lb_add_foreign_library_path(m, e);
  11684. }
  11685. #undef TIME_SECTION
  11686. }