llvm_backend.cpp 410 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207
  1. #include "llvm_backend.hpp"
  2. #include "llvm_abi.cpp"
  3. #ifdef USE_NEW_LLVM_ABI_SYSTEM
  4. #define USE_LLVM_ABI 1
  5. #else
  6. #define USE_LLVM_ABI 0
  7. #endif
  8. gb_global lbAddr lb_global_type_info_data = {};
  9. gb_global lbAddr lb_global_type_info_member_types = {};
  10. gb_global lbAddr lb_global_type_info_member_names = {};
  11. gb_global lbAddr lb_global_type_info_member_offsets = {};
  12. gb_global lbAddr lb_global_type_info_member_usings = {};
  13. gb_global lbAddr lb_global_type_info_member_tags = {};
  14. gb_global isize lb_global_type_info_data_index = 0;
  15. gb_global isize lb_global_type_info_member_types_index = 0;
  16. gb_global isize lb_global_type_info_member_names_index = 0;
  17. gb_global isize lb_global_type_info_member_offsets_index = 0;
  18. gb_global isize lb_global_type_info_member_usings_index = 0;
  19. gb_global isize lb_global_type_info_member_tags_index = 0;
  20. struct lbLoopData {
  21. lbAddr idx_addr;
  22. lbValue idx;
  23. lbBlock *body;
  24. lbBlock *done;
  25. lbBlock *loop;
  26. };
  27. struct lbCompoundLitElemTempData {
  28. Ast * expr;
  29. lbValue value;
  30. i32 elem_index;
  31. lbValue gep;
  32. };
  33. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  34. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  35. LLVMValueRef llvm_zero(lbModule *m) {
  36. return LLVMConstInt(lb_type(m, t_int), 0, false);
  37. }
  38. LLVMValueRef llvm_one(lbModule *m) {
  39. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  40. }
  41. lbValue lb_zero(lbModule *m, Type *t) {
  42. lbValue v = {};
  43. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  44. v.type = t;
  45. return v;
  46. }
  47. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  48. lbValue v = lb_find_or_add_entity_string(m, str);
  49. unsigned indices[1] = {0};
  50. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  51. }
  52. bool lb_is_instr_terminating(LLVMValueRef instr) {
  53. if (instr != nullptr) {
  54. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  55. switch (op) {
  56. case LLVMRet:
  57. case LLVMBr:
  58. case LLVMSwitch:
  59. case LLVMIndirectBr:
  60. case LLVMInvoke:
  61. case LLVMUnreachable:
  62. case LLVMCallBr:
  63. return true;
  64. }
  65. }
  66. return false;
  67. }
  68. lbAddr lb_addr(lbValue addr) {
  69. lbAddr v = {lbAddr_Default, addr};
  70. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  71. GB_ASSERT(is_type_pointer(addr.type));
  72. v.kind = lbAddr_RelativePointer;
  73. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  74. GB_ASSERT(is_type_pointer(addr.type));
  75. v.kind = lbAddr_RelativeSlice;
  76. }
  77. return v;
  78. }
  79. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  80. lbAddr v = {lbAddr_Map, addr};
  81. v.map.key = map_key;
  82. v.map.type = map_type;
  83. v.map.result = map_result;
  84. return v;
  85. }
  86. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  87. lbAddr v = {lbAddr_SoaVariable, addr};
  88. v.soa.index = index;
  89. v.soa.index_expr = index_expr;
  90. return v;
  91. }
  92. lbAddr lb_addr_bit_field(lbValue value, i32 index) {
  93. lbAddr addr = {};
  94. addr.kind = lbAddr_BitField;
  95. addr.addr = value;
  96. addr.bit_field.value_index = index;
  97. return addr;
  98. }
  99. Type *lb_addr_type(lbAddr const &addr) {
  100. if (addr.addr.value == nullptr) {
  101. return nullptr;
  102. }
  103. if (addr.kind == lbAddr_Map) {
  104. Type *t = base_type(addr.map.type);
  105. GB_ASSERT(is_type_map(t));
  106. return t->Map.value;
  107. }
  108. return type_deref(addr.addr.type);
  109. }
  110. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  111. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  112. }
  113. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  114. if (addr.addr.value == nullptr) {
  115. GB_PANIC("Illegal addr -> nullptr");
  116. return {};
  117. }
  118. switch (addr.kind) {
  119. case lbAddr_Map: {
  120. Type *map_type = base_type(addr.map.type);
  121. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  122. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  123. auto args = array_make<lbValue>(permanent_allocator(), 2);
  124. args[0] = h;
  125. args[1] = key;
  126. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  127. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  128. }
  129. case lbAddr_RelativePointer: {
  130. Type *rel_ptr = base_type(lb_addr_type(addr));
  131. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  132. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  133. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  134. offset = lb_emit_load(p, offset);
  135. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  136. offset = lb_emit_conv(p, offset, t_i64);
  137. }
  138. offset = lb_emit_conv(p, offset, t_uintptr);
  139. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  140. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  141. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  142. // NOTE(bill): nil check
  143. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  144. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  145. return final_ptr;
  146. }
  147. case lbAddr_BitField: {
  148. lbValue v = lb_addr_load(p, addr);
  149. return lb_address_from_load_or_generate_local(p, v);
  150. }
  151. case lbAddr_Context:
  152. GB_PANIC("lbAddr_Context should be handled elsewhere");
  153. }
  154. return addr.addr;
  155. }
  156. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  157. lbAddr addr = lb_build_addr(p, expr);
  158. return lb_addr_get_ptr(p, addr);
  159. }
  160. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  161. if (build_context.no_bounds_check) {
  162. return;
  163. }
  164. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  165. return;
  166. }
  167. index = lb_emit_conv(p, index, t_int);
  168. len = lb_emit_conv(p, len, t_int);
  169. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  170. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  171. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  172. auto args = array_make<lbValue>(permanent_allocator(), 5);
  173. args[0] = file;
  174. args[1] = line;
  175. args[2] = column;
  176. args[3] = index;
  177. args[4] = len;
  178. lb_emit_runtime_call(p, "bounds_check_error", args);
  179. }
  180. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  181. if (build_context.no_bounds_check) {
  182. return;
  183. }
  184. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  185. return;
  186. }
  187. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  188. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  189. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  190. high = lb_emit_conv(p, high, t_int);
  191. if (!lower_value_used) {
  192. auto args = array_make<lbValue>(permanent_allocator(), 5);
  193. args[0] = file;
  194. args[1] = line;
  195. args[2] = column;
  196. args[3] = high;
  197. args[4] = len;
  198. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  199. } else {
  200. // No need to convert unless used
  201. low = lb_emit_conv(p, low, t_int);
  202. auto args = array_make<lbValue>(permanent_allocator(), 6);
  203. args[0] = file;
  204. args[1] = line;
  205. args[2] = column;
  206. args[3] = low;
  207. args[4] = high;
  208. args[5] = len;
  209. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  210. }
  211. }
  212. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  213. if (addr.addr.value == nullptr) {
  214. return;
  215. }
  216. GB_ASSERT(value.type != nullptr);
  217. if (is_type_untyped_undef(value.type)) {
  218. Type *t = lb_addr_type(addr);
  219. value.type = t;
  220. value.value = LLVMGetUndef(lb_type(p->module, t));
  221. } else if (is_type_untyped_nil(value.type)) {
  222. Type *t = lb_addr_type(addr);
  223. value.type = t;
  224. value.value = LLVMConstNull(lb_type(p->module, t));
  225. }
  226. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  227. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  228. }
  229. if (addr.kind == lbAddr_RelativePointer) {
  230. Type *rel_ptr = base_type(lb_addr_type(addr));
  231. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  232. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  233. GB_ASSERT(is_type_pointer(addr.addr.type));
  234. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  235. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  236. lbValue offset = {};
  237. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  238. offset.type = t_uintptr;
  239. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  240. offset = lb_emit_conv(p, offset, t_i64);
  241. }
  242. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  243. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  244. offset = lb_emit_select(p,
  245. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  246. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  247. offset
  248. );
  249. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  250. return;
  251. } else if (addr.kind == lbAddr_RelativeSlice) {
  252. Type *rel_ptr = base_type(lb_addr_type(addr));
  253. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  254. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  255. GB_ASSERT(is_type_pointer(addr.addr.type));
  256. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  257. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  258. lbValue offset = {};
  259. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  260. offset.type = t_uintptr;
  261. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  262. offset = lb_emit_conv(p, offset, t_i64);
  263. }
  264. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  265. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  266. offset = lb_emit_select(p,
  267. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  268. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  269. offset
  270. );
  271. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  272. lbValue len = lb_slice_len(p, value);
  273. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  274. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  275. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  276. return;
  277. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  278. lbValue ptr = addr.addr;
  279. lbValue index = addr.index_set.index;
  280. Ast *node = addr.index_set.node;
  281. ast_node(ce, CallExpr, node);
  282. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  283. proc_type = base_type(proc_type);
  284. GB_ASSERT(is_type_proc(proc_type));
  285. TypeProc *pt = &proc_type->Proc;
  286. isize arg_count = 3;
  287. isize param_count = 0;
  288. if (pt->params) {
  289. GB_ASSERT(pt->params->kind == Type_Tuple);
  290. param_count = pt->params->Tuple.variables.count;
  291. }
  292. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  293. args[0] = ptr;
  294. args[1] = index;
  295. args[2] = value;
  296. isize arg_index = arg_count;
  297. if (arg_count < param_count) {
  298. lbModule *m = p->module;
  299. String proc_name = {};
  300. if (p->entity != nullptr) {
  301. proc_name = p->entity->token.string;
  302. }
  303. TokenPos pos = ast_token(ce->proc).pos;
  304. TypeTuple *param_tuple = &pt->params->Tuple;
  305. isize end = cast(isize)param_count;
  306. while (arg_index < end) {
  307. Entity *e = param_tuple->variables[arg_index];
  308. GB_ASSERT(e->kind == Entity_Variable);
  309. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  310. }
  311. }
  312. Entity *e = entity_from_expr(ce->proc);
  313. GB_ASSERT(e != nullptr);
  314. GB_ASSERT(is_type_polymorphic(e->type));
  315. {
  316. lbValue *found = nullptr;
  317. if (p->module != e->code_gen_module) {
  318. gb_mutex_lock(&p->module->mutex);
  319. }
  320. found = map_get(&e->code_gen_module->values, hash_entity(e));
  321. if (p->module != e->code_gen_module) {
  322. gb_mutex_unlock(&p->module->mutex);
  323. }
  324. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  325. lb_emit_call(p, *found, args);
  326. }
  327. return;
  328. } else if (addr.kind == lbAddr_Map) {
  329. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  330. return;
  331. } else if (addr.kind == lbAddr_BitField) {
  332. Type *bft = base_type(type_deref(addr.addr.type));
  333. GB_ASSERT(is_type_bit_field(bft));
  334. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  335. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  336. if (size_in_bits == 0) {
  337. return;
  338. }
  339. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  340. LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits);
  341. LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, "");
  342. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  343. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  344. LLVMBuildStore(p->builder, src, field_ptr);
  345. return;
  346. } else if (addr.kind == lbAddr_Context) {
  347. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  348. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  349. lb_addr_store(p, next_addr, old);
  350. lb_push_context_onto_stack(p, next_addr);
  351. lbValue next = lb_addr_get_ptr(p, next_addr);
  352. if (addr.ctx.sel.index.count > 0) {
  353. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  354. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  355. lb_emit_store(p, lhs, rhs);
  356. } else {
  357. lbValue lhs = next;
  358. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  359. lb_emit_store(p, lhs, rhs);
  360. }
  361. return;
  362. } else if (addr.kind == lbAddr_SoaVariable) {
  363. Type *t = type_deref(addr.addr.type);
  364. t = base_type(t);
  365. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  366. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  367. lbValue index = addr.soa.index;
  368. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  369. Type *t = base_type(type_deref(addr.addr.type));
  370. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  371. i64 count = t->Struct.soa_count;
  372. lbValue len = lb_const_int(p->module, t_int, count);
  373. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  374. }
  375. for_array(i, t->Struct.fields) {
  376. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  377. dst = lb_emit_array_ep(p, dst, index);
  378. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  379. lb_emit_store(p, dst, src);
  380. }
  381. return;
  382. }
  383. GB_ASSERT(value.value != nullptr);
  384. value = lb_emit_conv(p, value, lb_addr_type(addr));
  385. if (USE_LLVM_ABI) {
  386. lb_emit_store(p, addr.addr, value);
  387. } else {
  388. LLVMBuildStore(p->builder, value.value, addr.addr.value);
  389. }
  390. }
  391. void lb_const_store(lbValue ptr, lbValue value) {
  392. GB_ASSERT(lb_is_const(ptr));
  393. GB_ASSERT(lb_is_const(value));
  394. GB_ASSERT(is_type_pointer(ptr.type));
  395. LLVMSetInitializer(ptr.value, value.value);
  396. }
  397. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  398. GB_ASSERT(value.value != nullptr);
  399. Type *a = type_deref(ptr.type);
  400. if (is_type_boolean(a)) {
  401. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  402. value = lb_emit_conv(p, value, a);
  403. }
  404. Type *ca = core_type(a);
  405. if (ca->kind == Type_Basic) {
  406. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  407. }
  408. if (USE_LLVM_ABI && is_type_proc(a)) {
  409. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  410. // stored as regular pointer with no procedure information
  411. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  412. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  413. LLVMBuildStore(p->builder, v, ptr.value);
  414. } else {
  415. Type *ca = core_type(a);
  416. if (ca->kind == Type_Basic) {
  417. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  418. } else {
  419. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  420. }
  421. LLVMBuildStore(p->builder, value.value, ptr.value);
  422. }
  423. }
  424. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  425. lbModule *m = p->module;
  426. GB_ASSERT(value.value != nullptr);
  427. Type *t = type_deref(value.type);
  428. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  429. return lbValue{v, t};
  430. }
  431. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  432. GB_ASSERT(addr.addr.value != nullptr);
  433. if (addr.kind == lbAddr_RelativePointer) {
  434. Type *rel_ptr = base_type(lb_addr_type(addr));
  435. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  436. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  437. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  438. offset = lb_emit_load(p, offset);
  439. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  440. offset = lb_emit_conv(p, offset, t_i64);
  441. }
  442. offset = lb_emit_conv(p, offset, t_uintptr);
  443. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  444. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  445. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  446. // NOTE(bill): nil check
  447. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  448. lbValue final_ptr = {};
  449. final_ptr.type = absolute_ptr.type;
  450. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  451. return lb_emit_load(p, final_ptr);
  452. } else if (addr.kind == lbAddr_RelativeSlice) {
  453. Type *rel_ptr = base_type(lb_addr_type(addr));
  454. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  455. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  456. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  457. lbValue offset = lb_emit_load(p, offset_ptr);
  458. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  459. offset = lb_emit_conv(p, offset, t_i64);
  460. }
  461. offset = lb_emit_conv(p, offset, t_uintptr);
  462. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  463. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  464. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  465. Type *slice_elem = slice_type->Slice.elem;
  466. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  467. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  468. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  469. // NOTE(bill): nil check
  470. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  471. lbValue data = {};
  472. data.type = absolute_ptr.type;
  473. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  474. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  475. len = lb_emit_conv(p, len, t_int);
  476. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  477. lb_fill_slice(p, slice, data, len);
  478. return lb_addr_load(p, slice);
  479. } else if (addr.kind == lbAddr_Map) {
  480. Type *map_type = base_type(addr.map.type);
  481. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  482. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  483. lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key);
  484. auto args = array_make<lbValue>(permanent_allocator(), 2);
  485. args[0] = h;
  486. args[1] = key;
  487. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  488. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  489. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  490. lbBlock *then = lb_create_block(p, "map.get.then");
  491. lbBlock *done = lb_create_block(p, "map.get.done");
  492. lb_emit_if(p, ok, then, done);
  493. lb_start_block(p, then);
  494. {
  495. // TODO(bill): mem copy it instead?
  496. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  497. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  498. lb_emit_store(p, gep0, lb_emit_load(p, value));
  499. }
  500. lb_emit_jump(p, done);
  501. lb_start_block(p, done);
  502. if (is_type_tuple(addr.map.result)) {
  503. return lb_addr_load(p, v);
  504. } else {
  505. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  506. return lb_emit_load(p, single);
  507. }
  508. } else if (addr.kind == lbAddr_BitField) {
  509. Type *bft = base_type(type_deref(addr.addr.type));
  510. GB_ASSERT(is_type_bit_field(bft));
  511. unsigned value_index = cast(unsigned)addr.bit_field.value_index;
  512. i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits;
  513. i32 size_in_bytes = next_pow2((size_in_bits+7)/8);
  514. if (size_in_bytes == 0) {
  515. GB_ASSERT(size_in_bits == 0);
  516. lbValue res = {};
  517. res.type = t_i32;
  518. res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false);
  519. return res;
  520. }
  521. Type *int_type = nullptr;
  522. switch (size_in_bytes) {
  523. case 1: int_type = t_u8; break;
  524. case 2: int_type = t_u16; break;
  525. case 4: int_type = t_u32; break;
  526. case 8: int_type = t_u64; break;
  527. case 16: int_type = t_u128; break;
  528. }
  529. GB_ASSERT(int_type != nullptr);
  530. LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, "");
  531. LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, "");
  532. LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, "");
  533. lbValue res = {};
  534. res.type = int_type;
  535. res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), "");
  536. return res;
  537. } else if (addr.kind == lbAddr_Context) {
  538. if (addr.ctx.sel.index.count > 0) {
  539. lbValue a = addr.addr;
  540. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  541. return lb_emit_load(p, b);
  542. } else {
  543. return lb_emit_load(p, addr.addr);
  544. }
  545. } else if (addr.kind == lbAddr_SoaVariable) {
  546. Type *t = type_deref(addr.addr.type);
  547. t = base_type(t);
  548. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  549. Type *elem = t->Struct.soa_elem;
  550. lbValue len = {};
  551. if (t->Struct.soa_kind == StructSoa_Fixed) {
  552. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  553. } else {
  554. lbValue v = lb_emit_load(p, addr.addr);
  555. len = lb_soa_struct_len(p, v);
  556. }
  557. lbAddr res = lb_add_local_generated(p, elem, true);
  558. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  559. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  560. }
  561. if (t->Struct.soa_kind == StructSoa_Fixed) {
  562. for_array(i, t->Struct.fields) {
  563. Entity *field = t->Struct.fields[i];
  564. Type *base_type = field->type;
  565. GB_ASSERT(base_type->kind == Type_Array);
  566. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  567. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  568. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  569. lbValue src = lb_emit_load(p, src_ptr);
  570. lb_emit_store(p, dst, src);
  571. }
  572. } else {
  573. isize field_count = t->Struct.fields.count;
  574. if (t->Struct.soa_kind == StructSoa_Slice) {
  575. field_count -= 1;
  576. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  577. field_count -= 3;
  578. }
  579. for (isize i = 0; i < field_count; i++) {
  580. Entity *field = t->Struct.fields[i];
  581. Type *base_type = field->type;
  582. GB_ASSERT(base_type->kind == Type_Pointer);
  583. Type *elem = base_type->Pointer.elem;
  584. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  585. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  586. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  587. lbValue src = lb_emit_load(p, src_ptr);
  588. src = lb_emit_load(p, src);
  589. lb_emit_store(p, dst, src);
  590. }
  591. }
  592. return lb_addr_load(p, res);
  593. }
  594. if (is_type_proc(addr.addr.type)) {
  595. return addr.addr;
  596. }
  597. return lb_emit_load(p, addr.addr);
  598. }
  599. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  600. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  601. }
  602. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  603. Type *t = u.type;
  604. GB_ASSERT_MSG(is_type_pointer(t) &&
  605. is_type_union(type_deref(t)), "%s", type_to_string(t));
  606. Type *ut = type_deref(t);
  607. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  608. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  609. GB_ASSERT(type_size_of(ut) > 0);
  610. Type *tag_type = union_tag_type(ut);
  611. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  612. unsigned element_count = LLVMCountStructElementTypes(uvt);
  613. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  614. lbValue tag_ptr = {};
  615. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  616. tag_ptr.type = alloc_type_pointer(tag_type);
  617. return tag_ptr;
  618. }
  619. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  620. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  621. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  622. return lb_emit_load(p, tag_ptr);
  623. }
  624. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  625. Type *t = type_deref(parent.type);
  626. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  627. // No tag needed!
  628. } else {
  629. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  630. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  631. }
  632. }
  633. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  634. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  635. lb_emit_store(p, underlying, variant);
  636. lb_emit_store_union_variant_tag(p, parent, variant_type);
  637. }
  638. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  639. unsigned field_count = LLVMCountStructElementTypes(src);
  640. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  641. LLVMGetStructElementTypes(src, fields);
  642. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  643. }
  644. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  645. switch (alignment) {
  646. case 1:
  647. return LLVMArrayType(lb_type(m, t_u8), 0);
  648. case 2:
  649. return LLVMArrayType(lb_type(m, t_u16), 0);
  650. case 4:
  651. return LLVMArrayType(lb_type(m, t_u32), 0);
  652. case 8:
  653. return LLVMArrayType(lb_type(m, t_u64), 0);
  654. case 16:
  655. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  656. default:
  657. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  658. break;
  659. }
  660. return nullptr;
  661. }
  662. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  663. if (!elem_type_can_be_constant(elem_type)) {
  664. return false;
  665. }
  666. if (elem->kind == Ast_FieldValue) {
  667. elem = elem->FieldValue.value;
  668. }
  669. TypeAndValue tav = type_and_value_of_expr(elem);
  670. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  671. return tav.value.kind != ExactValue_Invalid;
  672. }
  673. String lb_mangle_name(lbModule *m, Entity *e) {
  674. String name = e->token.string;
  675. AstPackage *pkg = e->pkg;
  676. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  677. String pkgn = pkg->name;
  678. GB_ASSERT(!rune_is_digit(pkgn[0]));
  679. if (pkgn == "llvm") {
  680. pkgn = str_lit("llvm$");
  681. }
  682. isize max_len = pkgn.len + 1 + name.len + 1;
  683. bool require_suffix_id = is_type_polymorphic(e->type, true);
  684. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  685. require_suffix_id = true;
  686. } else if (is_blank_ident(e->token)) {
  687. require_suffix_id = true;
  688. }if (e->flags & EntityFlag_NotExported) {
  689. require_suffix_id = true;
  690. }
  691. if (require_suffix_id) {
  692. max_len += 21;
  693. }
  694. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  695. isize new_name_len = gb_snprintf(
  696. new_name, max_len,
  697. "%.*s.%.*s", LIT(pkgn), LIT(name)
  698. );
  699. if (require_suffix_id) {
  700. char *str = new_name + new_name_len-1;
  701. isize len = max_len-new_name_len;
  702. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  703. new_name_len += extra-1;
  704. }
  705. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  706. return mangled_name;
  707. }
  708. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  709. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  710. // and as a result, the declaration does not have time to determine what it should be
  711. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  712. if (e->TypeName.ir_mangled_name.len != 0) {
  713. return e->TypeName.ir_mangled_name;
  714. }
  715. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  716. if (p == nullptr) {
  717. Entity *proc = nullptr;
  718. if (e->parent_proc_decl != nullptr) {
  719. proc = e->parent_proc_decl->entity;
  720. } else {
  721. Scope *scope = e->scope;
  722. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  723. scope = scope->parent;
  724. }
  725. GB_ASSERT(scope != nullptr);
  726. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  727. proc = scope->procedure_entity;
  728. }
  729. GB_ASSERT(proc->kind == Entity_Procedure);
  730. if (proc->code_gen_procedure != nullptr) {
  731. p = proc->code_gen_procedure;
  732. }
  733. }
  734. // NOTE(bill): Generate a new name
  735. // parent_proc.name-guid
  736. String ts_name = e->token.string;
  737. if (p != nullptr) {
  738. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  739. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  740. u32 guid = ++p->module->nested_type_name_guid;
  741. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  742. String name = make_string(cast(u8 *)name_text, name_len-1);
  743. e->TypeName.ir_mangled_name = name;
  744. return name;
  745. } else {
  746. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  747. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  748. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  749. static u32 guid = 0;
  750. guid += 1;
  751. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  752. String name = make_string(cast(u8 *)name_text, name_len-1);
  753. e->TypeName.ir_mangled_name = name;
  754. return name;
  755. }
  756. }
  757. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  758. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  759. return e->TypeName.ir_mangled_name;
  760. }
  761. GB_ASSERT(e != nullptr);
  762. if (e->pkg == nullptr) {
  763. return e->token.string;
  764. }
  765. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  766. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  767. }
  768. String name = {};
  769. bool no_name_mangle = false;
  770. if (e->kind == Entity_Variable) {
  771. bool is_foreign = e->Variable.is_foreign;
  772. bool is_export = e->Variable.is_export;
  773. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  774. if (e->Variable.link_name.len > 0) {
  775. return e->Variable.link_name;
  776. }
  777. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  778. return e->Procedure.link_name;
  779. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  780. no_name_mangle = true;
  781. }
  782. if (!no_name_mangle) {
  783. name = lb_mangle_name(m, e);
  784. }
  785. if (name.len == 0) {
  786. name = e->token.string;
  787. }
  788. if (e->kind == Entity_TypeName) {
  789. if ((e->scope->flags & ScopeFlag_File) == 0) {
  790. gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e);
  791. }
  792. e->TypeName.ir_mangled_name = name;
  793. } else if (e->kind == Entity_Procedure) {
  794. e->Procedure.link_name = name;
  795. }
  796. return name;
  797. }
  798. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  799. Type *original_type = type;
  800. LLVMContextRef ctx = m->ctx;
  801. i64 size = type_size_of(type); // Check size
  802. GB_ASSERT(type != t_invalid);
  803. switch (type->kind) {
  804. case Type_Basic:
  805. switch (type->Basic.kind) {
  806. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  807. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  808. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  809. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  810. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  811. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  812. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  813. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  814. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  815. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  816. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  817. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  818. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  819. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  820. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  821. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  822. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  823. // Basic_f16,
  824. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  825. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  826. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  827. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  828. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  829. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  830. // Basic_complex32,
  831. case Basic_complex64:
  832. {
  833. char const *name = "..complex64";
  834. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  835. if (type != nullptr) {
  836. return type;
  837. }
  838. type = LLVMStructCreateNamed(ctx, name);
  839. LLVMTypeRef fields[2] = {
  840. lb_type(m, t_f32),
  841. lb_type(m, t_f32),
  842. };
  843. LLVMStructSetBody(type, fields, 2, false);
  844. return type;
  845. }
  846. case Basic_complex128:
  847. {
  848. char const *name = "..complex128";
  849. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  850. if (type != nullptr) {
  851. return type;
  852. }
  853. type = LLVMStructCreateNamed(ctx, name);
  854. LLVMTypeRef fields[2] = {
  855. lb_type(m, t_f64),
  856. lb_type(m, t_f64),
  857. };
  858. LLVMStructSetBody(type, fields, 2, false);
  859. return type;
  860. }
  861. case Basic_quaternion128:
  862. {
  863. char const *name = "..quaternion128";
  864. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  865. if (type != nullptr) {
  866. return type;
  867. }
  868. type = LLVMStructCreateNamed(ctx, name);
  869. LLVMTypeRef fields[4] = {
  870. lb_type(m, t_f32),
  871. lb_type(m, t_f32),
  872. lb_type(m, t_f32),
  873. lb_type(m, t_f32),
  874. };
  875. LLVMStructSetBody(type, fields, 4, false);
  876. return type;
  877. }
  878. case Basic_quaternion256:
  879. {
  880. char const *name = "..quaternion256";
  881. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  882. if (type != nullptr) {
  883. return type;
  884. }
  885. type = LLVMStructCreateNamed(ctx, name);
  886. LLVMTypeRef fields[4] = {
  887. lb_type(m, t_f64),
  888. lb_type(m, t_f64),
  889. lb_type(m, t_f64),
  890. lb_type(m, t_f64),
  891. };
  892. LLVMStructSetBody(type, fields, 4, false);
  893. return type;
  894. }
  895. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  896. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  897. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  898. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  899. case Basic_string:
  900. {
  901. char const *name = "..string";
  902. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  903. if (type != nullptr) {
  904. return type;
  905. }
  906. type = LLVMStructCreateNamed(ctx, name);
  907. LLVMTypeRef fields[2] = {
  908. LLVMPointerType(lb_type(m, t_u8), 0),
  909. lb_type(m, t_int),
  910. };
  911. LLVMStructSetBody(type, fields, 2, false);
  912. return type;
  913. }
  914. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  915. case Basic_any:
  916. {
  917. char const *name = "..any";
  918. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  919. if (type != nullptr) {
  920. return type;
  921. }
  922. type = LLVMStructCreateNamed(ctx, name);
  923. LLVMTypeRef fields[2] = {
  924. lb_type(m, t_rawptr),
  925. lb_type(m, t_typeid),
  926. };
  927. LLVMStructSetBody(type, fields, 2, false);
  928. return type;
  929. }
  930. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  931. // Endian Specific Types
  932. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  933. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  934. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  935. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  936. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  937. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  938. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  939. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  940. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  941. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  942. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  943. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  944. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  945. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  946. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  947. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  948. // Untyped types
  949. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  950. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  951. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  952. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  953. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  954. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  955. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  956. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  957. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  958. }
  959. break;
  960. case Type_Named:
  961. {
  962. Type *base = base_type(type->Named.base);
  963. switch (base->kind) {
  964. case Type_Basic:
  965. return lb_type_internal(m, base);
  966. case Type_Named:
  967. case Type_Generic:
  968. case Type_BitFieldValue:
  969. GB_PANIC("INVALID TYPE");
  970. break;
  971. case Type_Opaque:
  972. return lb_type_internal(m, base->Opaque.elem);
  973. case Type_Pointer:
  974. case Type_Array:
  975. case Type_EnumeratedArray:
  976. case Type_Slice:
  977. case Type_DynamicArray:
  978. case Type_Map:
  979. case Type_Enum:
  980. case Type_BitSet:
  981. case Type_SimdVector:
  982. return lb_type_internal(m, base);
  983. // TODO(bill): Deal with this correctly. Can this be named?
  984. case Type_Proc:
  985. return lb_type_internal(m, base);
  986. case Type_Tuple:
  987. return lb_type_internal(m, base);
  988. }
  989. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  990. if (found) {
  991. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  992. if (kind == LLVMStructTypeKind) {
  993. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  994. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  995. if (llvm_type != nullptr) {
  996. return llvm_type;
  997. }
  998. llvm_type = LLVMStructCreateNamed(ctx, name);
  999. map_set(&m->types, hash_type(type), llvm_type);
  1000. lb_clone_struct_type(llvm_type, *found);
  1001. return llvm_type;
  1002. }
  1003. }
  1004. switch (base->kind) {
  1005. case Type_Struct:
  1006. case Type_Union:
  1007. case Type_BitField:
  1008. {
  1009. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1010. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1011. if (llvm_type != nullptr) {
  1012. return llvm_type;
  1013. }
  1014. llvm_type = LLVMStructCreateNamed(ctx, name);
  1015. map_set(&m->types, hash_type(type), llvm_type);
  1016. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1017. return llvm_type;
  1018. }
  1019. }
  1020. return lb_type_internal(m, base);
  1021. }
  1022. case Type_Pointer:
  1023. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1024. case Type_Opaque:
  1025. return lb_type(m, base_type(type));
  1026. case Type_Array:
  1027. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1028. case Type_EnumeratedArray:
  1029. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1030. case Type_Slice:
  1031. {
  1032. LLVMTypeRef fields[2] = {
  1033. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1034. lb_type(m, t_int), // len
  1035. };
  1036. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1037. }
  1038. break;
  1039. case Type_DynamicArray:
  1040. {
  1041. LLVMTypeRef fields[4] = {
  1042. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1043. lb_type(m, t_int), // len
  1044. lb_type(m, t_int), // cap
  1045. lb_type(m, t_allocator), // allocator
  1046. };
  1047. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1048. }
  1049. break;
  1050. case Type_Map:
  1051. return lb_type(m, type->Map.internal_type);
  1052. case Type_Struct:
  1053. {
  1054. if (type->Struct.is_raw_union) {
  1055. unsigned field_count = 2;
  1056. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1057. i64 alignment = type_align_of(type);
  1058. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1059. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1060. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1061. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1062. }
  1063. isize offset = 0;
  1064. if (type->Struct.custom_align > 0) {
  1065. offset = 1;
  1066. }
  1067. m->internal_type_level += 1;
  1068. defer (m->internal_type_level -= 1);
  1069. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1070. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1071. for_array(i, type->Struct.fields) {
  1072. Entity *field = type->Struct.fields[i];
  1073. fields[i+offset] = lb_type(m, field->type);
  1074. }
  1075. if (type->Struct.custom_align > 0) {
  1076. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1077. }
  1078. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1079. }
  1080. break;
  1081. case Type_Union:
  1082. if (type->Union.variants.count == 0) {
  1083. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1084. } else {
  1085. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1086. // LLVM takes the first element's alignment as the entire alignment (like C)
  1087. i64 align = type_align_of(type);
  1088. i64 size = type_size_of(type);
  1089. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1090. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1091. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1092. }
  1093. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1094. LLVMTypeRef fields[3] = {};
  1095. unsigned field_count = 1;
  1096. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1097. if (is_type_union_maybe_pointer(type)) {
  1098. field_count += 1;
  1099. fields[1] = lb_type(m, type->Union.variants[0]);
  1100. } else {
  1101. field_count += 2;
  1102. if (block_size == align) {
  1103. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1104. } else {
  1105. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1106. }
  1107. fields[2] = lb_type(m, union_tag_type(type));
  1108. }
  1109. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1110. }
  1111. break;
  1112. case Type_Enum:
  1113. return lb_type(m, base_enum_type(type));
  1114. case Type_Tuple:
  1115. if (type->Tuple.variables.count == 1) {
  1116. return lb_type(m, type->Tuple.variables[0]->type);
  1117. } else {
  1118. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1119. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1120. for_array(i, type->Tuple.variables) {
  1121. Entity *field = type->Tuple.variables[i];
  1122. LLVMTypeRef param_type = nullptr;
  1123. param_type = lb_type(m, field->type);
  1124. fields[i] = param_type;
  1125. }
  1126. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1127. }
  1128. case Type_Proc:
  1129. {
  1130. if (USE_LLVM_ABI) {
  1131. if (m->internal_type_level > 5) { // TODO HACK(bill): is this really enough?
  1132. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1133. } else {
  1134. unsigned param_count = 0;
  1135. if (type->Proc.calling_convention == ProcCC_Odin) {
  1136. param_count += 1;
  1137. }
  1138. if (type->Proc.param_count != 0) {
  1139. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1140. for_array(i, type->Proc.params->Tuple.variables) {
  1141. Entity *e = type->Proc.params->Tuple.variables[i];
  1142. if (e->kind != Entity_Variable) {
  1143. continue;
  1144. }
  1145. param_count += 1;
  1146. }
  1147. }
  1148. m->internal_type_level += 1;
  1149. defer (m->internal_type_level -= 1);
  1150. LLVMTypeRef ret = nullptr;
  1151. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1152. if (type->Proc.result_count != 0) {
  1153. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1154. ret = lb_type(m, single_ret);
  1155. if (ret != nullptr) {
  1156. if (is_type_boolean(single_ret) &&
  1157. is_calling_convention_none(type->Proc.calling_convention) &&
  1158. type_size_of(single_ret) <= 1) {
  1159. ret = LLVMInt1TypeInContext(m->ctx);
  1160. }
  1161. }
  1162. }
  1163. isize param_index = 0;
  1164. if (type->Proc.param_count != 0) {
  1165. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1166. for_array(i, type->Proc.params->Tuple.variables) {
  1167. Entity *e = type->Proc.params->Tuple.variables[i];
  1168. if (e->kind != Entity_Variable) {
  1169. continue;
  1170. }
  1171. Type *e_type = reduce_tuple_to_single_type(e->type);
  1172. LLVMTypeRef param_type = nullptr;
  1173. if (is_type_boolean(e_type) &&
  1174. type_size_of(e_type) <= 1) {
  1175. param_type = LLVMInt1TypeInContext(m->ctx);
  1176. } else {
  1177. param_type = lb_type(m, e_type);
  1178. }
  1179. params[param_index++] = param_type;
  1180. }
  1181. }
  1182. if (param_index < param_count) {
  1183. params[param_index++] = lb_type(m, t_context_ptr);
  1184. }
  1185. GB_ASSERT(param_index == param_count);
  1186. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1187. map_set(&m->function_type_map, hash_type(type), ft);
  1188. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1189. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1190. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1191. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1192. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1193. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1194. // 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));
  1195. return new_abi_fn_ptr_type;
  1196. }
  1197. } else {
  1198. LLVMTypeRef old_abi_fn_type = nullptr;
  1199. set_procedure_abi_types(type);
  1200. LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1201. if (type->Proc.return_by_pointer) {
  1202. // Void
  1203. } else if (type->Proc.abi_compat_result_type != nullptr) {
  1204. return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1205. }
  1206. isize extra_param_count = 0;
  1207. if (type->Proc.return_by_pointer) {
  1208. extra_param_count += 1;
  1209. }
  1210. if (type->Proc.calling_convention == ProcCC_Odin) {
  1211. extra_param_count += 1;
  1212. }
  1213. isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1214. auto param_types = array_make<LLVMTypeRef>(temporary_allocator(), 0, param_count);
  1215. if (type->Proc.return_by_pointer) {
  1216. array_add(&param_types, LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0));
  1217. }
  1218. for_array(i, type->Proc.abi_compat_params) {
  1219. Type *param = type->Proc.abi_compat_params[i];
  1220. if (param == nullptr) {
  1221. continue;
  1222. }
  1223. if (type->Proc.params->Tuple.variables[i]->flags & EntityFlag_CVarArg) {
  1224. GB_ASSERT(i+1 == type->Proc.abi_compat_params.count);
  1225. break;
  1226. }
  1227. if (is_type_tuple(param)) {
  1228. param = base_type(param);
  1229. for_array(j, param->Tuple.variables) {
  1230. Entity *v = param->Tuple.variables[j];
  1231. if (v->kind != Entity_Variable) {
  1232. // Sanity check
  1233. continue;
  1234. }
  1235. LLVMTypeRef t = lb_type(m, v->type);
  1236. array_add(&param_types, t);
  1237. }
  1238. } else {
  1239. array_add(&param_types, lb_type(m, param));
  1240. }
  1241. }
  1242. if (type->Proc.calling_convention == ProcCC_Odin) {
  1243. array_add(&param_types, lb_type(m, t_context_ptr));
  1244. }
  1245. old_abi_fn_type = LLVMFunctionType(return_type, param_types.data, cast(unsigned)param_types.count, type->Proc.c_vararg);
  1246. return LLVMPointerType(old_abi_fn_type, 0);
  1247. }
  1248. }
  1249. break;
  1250. case Type_BitFieldValue:
  1251. return LLVMIntTypeInContext(m->ctx, type->BitFieldValue.bits);
  1252. case Type_BitField:
  1253. {
  1254. LLVMTypeRef internal_type = nullptr;
  1255. {
  1256. GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1257. unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1258. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1259. for_array(i, type->BitField.sizes) {
  1260. u32 size = type->BitField.sizes[i];
  1261. fields[i] = LLVMIntTypeInContext(m->ctx, size);
  1262. }
  1263. internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1264. }
  1265. unsigned field_count = 2;
  1266. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1267. i64 alignment = 1;
  1268. if (type->BitField.custom_align > 0) {
  1269. alignment = type->BitField.custom_align;
  1270. }
  1271. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1272. fields[1] = internal_type;
  1273. return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1274. }
  1275. break;
  1276. case Type_BitSet:
  1277. {
  1278. Type *ut = bit_set_to_int(type);
  1279. return lb_type(m, ut);
  1280. }
  1281. case Type_SimdVector:
  1282. if (type->SimdVector.is_x86_mmx) {
  1283. return LLVMX86MMXTypeInContext(ctx);
  1284. }
  1285. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1286. case Type_RelativePointer:
  1287. return lb_type_internal(m, type->RelativePointer.base_integer);
  1288. case Type_RelativeSlice:
  1289. {
  1290. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1291. unsigned field_count = 2;
  1292. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1293. fields[0] = base_integer;
  1294. fields[1] = base_integer;
  1295. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1296. }
  1297. }
  1298. GB_PANIC("Invalid type %s", type_to_string(type));
  1299. return LLVMInt32TypeInContext(ctx);
  1300. }
  1301. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1302. type = default_type(type);
  1303. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1304. if (found) {
  1305. return *found;
  1306. }
  1307. LLVMTypeRef llvm_type = nullptr;
  1308. m->internal_type_level += 1;
  1309. llvm_type = lb_type_internal(m, type);
  1310. m->internal_type_level -= 1;
  1311. if (USE_LLVM_ABI && m->internal_type_level == 0) {
  1312. map_set(&m->types, hash_type(type), llvm_type);
  1313. if (is_type_named(type)) {
  1314. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1315. }
  1316. }
  1317. return llvm_type;
  1318. }
  1319. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1320. Type *original_type = type;
  1321. LLVMContextRef ctx = m->ctx;
  1322. i64 size = type_size_of(type); // Check size
  1323. GB_ASSERT(type != t_invalid);
  1324. switch (type->kind) {
  1325. case Type_Basic:
  1326. switch (type->Basic.kind) {
  1327. case Basic_llvm_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "llvm bool", 9, 1, 0, LLVMDIFlagZero);
  1328. case Basic_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "bool", 4, 8, 0, LLVMDIFlagZero);
  1329. case Basic_b8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b8", 2, 8, 0, LLVMDIFlagZero);
  1330. case Basic_b16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b16", 3, 16, 0, LLVMDIFlagZero);
  1331. case Basic_b32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b32", 3, 32, 0, LLVMDIFlagZero);
  1332. case Basic_b64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b64", 3, 64, 0, LLVMDIFlagZero);
  1333. case Basic_i8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i8", 2, 8, 0, LLVMDIFlagZero);
  1334. case Basic_u8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u8", 2, 8, 0, LLVMDIFlagZero);
  1335. case Basic_i16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16", 3, 16, 0, LLVMDIFlagZero);
  1336. case Basic_u16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16", 3, 16, 0, LLVMDIFlagZero);
  1337. case Basic_i32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32", 3, 32, 0, LLVMDIFlagZero);
  1338. case Basic_u32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32", 3, 32, 0, LLVMDIFlagZero);
  1339. case Basic_i64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64", 3, 64, 0, LLVMDIFlagZero);
  1340. case Basic_u64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64", 3, 64, 0, LLVMDIFlagZero);
  1341. case Basic_i128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128", 4, 128, 0, LLVMDIFlagZero);
  1342. case Basic_u128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128", 4, 128, 0, LLVMDIFlagZero);
  1343. case Basic_rune: return LLVMDIBuilderCreateBasicType(m->debug_builder, "rune", 4, 32, 0, LLVMDIFlagZero);
  1344. // Basic_f16,
  1345. case Basic_f32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32", 3, 32, 0, LLVMDIFlagZero);
  1346. case Basic_f64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64", 3, 64, 0, LLVMDIFlagZero);
  1347. // Basic_complex32,
  1348. case Basic_complex64:
  1349. {
  1350. return nullptr;
  1351. // char const *name = "..complex64";
  1352. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1353. // if (type != nullptr) {
  1354. // return type;
  1355. // }
  1356. // type = LLVMStructCreateNamed(ctx, name);
  1357. // LLVMTypeRef fields[2] = {
  1358. // lb_type(m, t_f32),
  1359. // lb_type(m, t_f32),
  1360. // };
  1361. // LLVMStructSetBody(type, fields, 2, false);
  1362. // return type;
  1363. }
  1364. case Basic_complex128:
  1365. {
  1366. return nullptr;
  1367. // char const *name = "..complex128";
  1368. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1369. // if (type != nullptr) {
  1370. // return type;
  1371. // }
  1372. // type = LLVMStructCreateNamed(ctx, name);
  1373. // LLVMTypeRef fields[2] = {
  1374. // lb_type(m, t_f64),
  1375. // lb_type(m, t_f64),
  1376. // };
  1377. // LLVMStructSetBody(type, fields, 2, false);
  1378. // return type;
  1379. }
  1380. case Basic_quaternion128:
  1381. {
  1382. return nullptr;
  1383. // char const *name = "..quaternion128";
  1384. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1385. // if (type != nullptr) {
  1386. // return type;
  1387. // }
  1388. // type = LLVMStructCreateNamed(ctx, name);
  1389. // LLVMTypeRef fields[4] = {
  1390. // lb_type(m, t_f32),
  1391. // lb_type(m, t_f32),
  1392. // lb_type(m, t_f32),
  1393. // lb_type(m, t_f32),
  1394. // };
  1395. // LLVMStructSetBody(type, fields, 4, false);
  1396. // return type;
  1397. }
  1398. case Basic_quaternion256:
  1399. {
  1400. return nullptr;
  1401. // char const *name = "..quaternion256";
  1402. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1403. // if (type != nullptr) {
  1404. // return type;
  1405. // }
  1406. // type = LLVMStructCreateNamed(ctx, name);
  1407. // LLVMTypeRef fields[4] = {
  1408. // lb_type(m, t_f64),
  1409. // lb_type(m, t_f64),
  1410. // lb_type(m, t_f64),
  1411. // lb_type(m, t_f64),
  1412. // };
  1413. // LLVMStructSetBody(type, fields, 4, false);
  1414. // return type;
  1415. }
  1416. case Basic_int: return LLVMDIBuilderCreateBasicType(m->debug_builder, "int", 3, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1417. case Basic_uint: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uint", 4, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1418. case Basic_uintptr: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uintptr", 7, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1419. case Basic_rawptr:
  1420. return nullptr;
  1421. // return LLVMPointerType(LLVMInt8Type(), 0);
  1422. case Basic_string:
  1423. {
  1424. return nullptr;
  1425. // char const *name = "..string";
  1426. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1427. // if (type != nullptr) {
  1428. // return type;
  1429. // }
  1430. // type = LLVMStructCreateNamed(ctx, name);
  1431. // LLVMTypeRef fields[2] = {
  1432. // LLVMPointerType(lb_type(m, t_u8), 0),
  1433. // lb_type(m, t_int),
  1434. // };
  1435. // LLVMStructSetBody(type, fields, 2, false);
  1436. // return type;
  1437. }
  1438. case Basic_cstring:
  1439. return nullptr;
  1440. // return LLVMPointerType(LLVMInt8Type(), 0);
  1441. case Basic_any:
  1442. {
  1443. return nullptr;
  1444. // char const *name = "..any";
  1445. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1446. // if (type != nullptr) {
  1447. // return type;
  1448. // }
  1449. // type = LLVMStructCreateNamed(ctx, name);
  1450. // LLVMTypeRef fields[2] = {
  1451. // lb_type(m, t_rawptr),
  1452. // lb_type(m, t_typeid),
  1453. // };
  1454. // LLVMStructSetBody(type, fields, 2, false);
  1455. // return type;
  1456. }
  1457. case Basic_typeid: return LLVMDIBuilderCreateBasicType(m->debug_builder, "typeid", 6, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1458. // Endian Specific Types
  1459. case Basic_i16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1460. case Basic_u16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1461. case Basic_i32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1462. case Basic_u32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1463. case Basic_i64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1464. case Basic_u64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1465. case Basic_i128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1466. case Basic_u128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1467. case Basic_i16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1468. case Basic_u16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1469. case Basic_i32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1470. case Basic_u32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1471. case Basic_i64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1472. case Basic_u64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1473. case Basic_i128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1474. case Basic_u128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1475. // Untyped types
  1476. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1477. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1478. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1479. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1480. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1481. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1482. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1483. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1484. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1485. }
  1486. break;
  1487. case Type_Named:
  1488. {
  1489. return nullptr;
  1490. // Type *base = base_type(type->Named.base);
  1491. // switch (base->kind) {
  1492. // case Type_Basic:
  1493. // return lb_type(m, base);
  1494. // case Type_Named:
  1495. // case Type_Generic:
  1496. // case Type_BitFieldValue:
  1497. // GB_PANIC("INVALID TYPE");
  1498. // break;
  1499. // case Type_Opaque:
  1500. // return lb_type(m, base->Opaque.elem);
  1501. // case Type_Pointer:
  1502. // case Type_Array:
  1503. // case Type_EnumeratedArray:
  1504. // case Type_Slice:
  1505. // case Type_DynamicArray:
  1506. // case Type_Map:
  1507. // case Type_Enum:
  1508. // case Type_BitSet:
  1509. // case Type_SimdVector:
  1510. // return lb_type(m, base);
  1511. // // TODO(bill): Deal with this correctly. Can this be named?
  1512. // case Type_Proc:
  1513. // return lb_type(m, base);
  1514. // case Type_Tuple:
  1515. // return lb_type(m, base);
  1516. // }
  1517. // LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1518. // if (found) {
  1519. // LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1520. // if (kind == LLVMStructTypeKind) {
  1521. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1522. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1523. // if (llvm_type != nullptr) {
  1524. // return llvm_type;
  1525. // }
  1526. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1527. // map_set(&m->types, hash_type(type), llvm_type);
  1528. // lb_clone_struct_type(llvm_type, *found);
  1529. // return llvm_type;
  1530. // }
  1531. // }
  1532. // switch (base->kind) {
  1533. // case Type_Struct:
  1534. // case Type_Union:
  1535. // case Type_BitField:
  1536. // {
  1537. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1538. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1539. // if (llvm_type != nullptr) {
  1540. // return llvm_type;
  1541. // }
  1542. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1543. // map_set(&m->types, hash_type(type), llvm_type);
  1544. // lb_clone_struct_type(llvm_type, lb_type(m, base));
  1545. // return llvm_type;
  1546. // }
  1547. // }
  1548. // return lb_type(m, base);
  1549. }
  1550. case Type_Pointer:
  1551. return nullptr;
  1552. // return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1553. case Type_Opaque:
  1554. return nullptr;
  1555. // return lb_type(m, base_type(type));
  1556. case Type_Array:
  1557. return nullptr;
  1558. // return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1559. case Type_EnumeratedArray:
  1560. return nullptr;
  1561. // return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1562. case Type_Slice:
  1563. {
  1564. return nullptr;
  1565. // LLVMTypeRef fields[2] = {
  1566. // LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1567. // lb_type(m, t_int), // len
  1568. // };
  1569. // return LLVMStructTypeInContext(ctx, fields, 2, false);
  1570. }
  1571. break;
  1572. case Type_DynamicArray:
  1573. {
  1574. return nullptr;
  1575. // LLVMTypeRef fields[4] = {
  1576. // LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1577. // lb_type(m, t_int), // len
  1578. // lb_type(m, t_int), // cap
  1579. // lb_type(m, t_allocator), // allocator
  1580. // };
  1581. // return LLVMStructTypeInContext(ctx, fields, 4, false);
  1582. }
  1583. break;
  1584. case Type_Map:
  1585. return nullptr;
  1586. // return lb_type(m, type->Map.internal_type);
  1587. case Type_Struct:
  1588. {
  1589. return nullptr;
  1590. // if (type->Struct.is_raw_union) {
  1591. // unsigned field_count = 2;
  1592. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1593. // i64 alignment = type_align_of(type);
  1594. // unsigned size_of_union = cast(unsigned)type_size_of(type);
  1595. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1596. // fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1597. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1598. // }
  1599. // isize offset = 0;
  1600. // if (type->Struct.custom_align > 0) {
  1601. // offset = 1;
  1602. // }
  1603. // unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1604. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1605. // GB_ASSERT(fields != nullptr);
  1606. // defer (gb_free(heap_allocator(), fields));
  1607. // for_array(i, type->Struct.fields) {
  1608. // Entity *field = type->Struct.fields[i];
  1609. // fields[i+offset] = lb_type(m, field->type);
  1610. // }
  1611. // if (type->Struct.custom_align > 0) {
  1612. // fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1613. // }
  1614. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1615. }
  1616. break;
  1617. case Type_Union:
  1618. return nullptr;
  1619. // if (type->Union.variants.count == 0) {
  1620. // return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1621. // } else {
  1622. // // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1623. // // LLVM takes the first element's alignment as the entire alignment (like C)
  1624. // i64 align = type_align_of(type);
  1625. // i64 size = type_size_of(type);
  1626. // if (is_type_union_maybe_pointer_original_alignment(type)) {
  1627. // LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1628. // return LLVMStructTypeInContext(ctx, fields, 1, false);
  1629. // }
  1630. // unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1631. // LLVMTypeRef fields[3] = {};
  1632. // unsigned field_count = 1;
  1633. // fields[0] = lb_alignment_prefix_type_hack(m, align);
  1634. // if (is_type_union_maybe_pointer(type)) {
  1635. // field_count += 1;
  1636. // fields[1] = lb_type(m, type->Union.variants[0]);
  1637. // } else {
  1638. // field_count += 2;
  1639. // if (block_size == align) {
  1640. // fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1641. // } else {
  1642. // fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1643. // }
  1644. // fields[2] = lb_type(m, union_tag_type(type));
  1645. // }
  1646. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1647. // }
  1648. // break;
  1649. case Type_Enum:
  1650. return nullptr;
  1651. // return lb_type(m, base_enum_type(type));
  1652. case Type_Tuple:
  1653. return nullptr;
  1654. // if (type->Tuple.variables.count == 1) {
  1655. // return lb_type(m, type->Tuple.variables[0]->type);
  1656. // } else {
  1657. // unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1658. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1659. // defer (gb_free(heap_allocator(), fields));
  1660. // for_array(i, type->Tuple.variables) {
  1661. // Entity *field = type->Tuple.variables[i];
  1662. // fields[i] = lb_type(m, field->type);
  1663. // }
  1664. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1665. // }
  1666. case Type_Proc:
  1667. {
  1668. return nullptr;
  1669. // set_procedure_abi_types(type);
  1670. // LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1671. // isize offset = 0;
  1672. // if (type->Proc.return_by_pointer) {
  1673. // offset = 1;
  1674. // } else if (type->Proc.abi_compat_result_type != nullptr) {
  1675. // return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1676. // }
  1677. // isize extra_param_count = offset;
  1678. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1679. // extra_param_count += 1;
  1680. // }
  1681. // isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1682. // LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1683. // defer (gb_free(heap_allocator(), param_types));
  1684. // isize param_index = offset;
  1685. // for_array(i, type->Proc.abi_compat_params) {
  1686. // Type *param = type->Proc.abi_compat_params[i];
  1687. // if (param == nullptr) {
  1688. // continue;
  1689. // }
  1690. // param_types[param_index++] = lb_type(m, param);
  1691. // }
  1692. // if (type->Proc.return_by_pointer) {
  1693. // param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  1694. // }
  1695. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1696. // param_types[param_index++] = lb_type(m, t_context_ptr);
  1697. // }
  1698. // LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  1699. // return LLVMPointerType(t, 0);
  1700. }
  1701. break;
  1702. case Type_BitFieldValue:
  1703. return nullptr;
  1704. // return LLVMIntTypeInContext(m->ctx, type->BitFieldValue.bits);
  1705. case Type_BitField:
  1706. {
  1707. return nullptr;
  1708. // LLVMTypeRef internal_type = nullptr;
  1709. // {
  1710. // GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count);
  1711. // unsigned field_count = cast(unsigned)type->BitField.fields.count;
  1712. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1713. // defer (gb_free(heap_allocator(), fields));
  1714. // for_array(i, type->BitField.sizes) {
  1715. // u32 size = type->BitField.sizes[i];
  1716. // fields[i] = LLVMIntTypeInContext(m->ctx, size);
  1717. // }
  1718. // internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true);
  1719. // }
  1720. // unsigned field_count = 2;
  1721. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1722. // i64 alignment = 1;
  1723. // if (type->BitField.custom_align > 0) {
  1724. // alignment = type->BitField.custom_align;
  1725. // }
  1726. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1727. // fields[1] = internal_type;
  1728. // return LLVMStructTypeInContext(ctx, fields, field_count, true);
  1729. }
  1730. break;
  1731. case Type_BitSet:
  1732. return nullptr;
  1733. // return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)type_size_of(type));
  1734. case Type_SimdVector:
  1735. return nullptr;
  1736. // if (type->SimdVector.is_x86_mmx) {
  1737. // return LLVMX86MMXTypeInContext(ctx);
  1738. // }
  1739. // return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1740. }
  1741. GB_PANIC("Invalid type %s", type_to_string(type));
  1742. return nullptr;
  1743. }
  1744. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1745. LLVMTypeRef t = lb_type(m, type);
  1746. LLVMMetadataRef *found = map_get(&m->debug_values, hash_pointer(t));
  1747. if (found != nullptr) {
  1748. return *found;
  1749. }
  1750. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1751. map_set(&m->debug_values, hash_pointer(t), dt);
  1752. return dt;
  1753. }
  1754. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1755. if (e != nullptr) {
  1756. map_set(&m->values, hash_entity(e), val);
  1757. }
  1758. }
  1759. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1760. if (name.len > 0) {
  1761. string_map_set(&m->members, name, val);
  1762. }
  1763. }
  1764. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1765. string_map_set(&m->members, key, val);
  1766. }
  1767. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1768. if (p->entity != nullptr) {
  1769. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1770. }
  1771. string_map_set(&m->procedures, p->name, p);
  1772. }
  1773. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1774. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1775. LLVMValueRef values[2] = {
  1776. str_elem.value,
  1777. str_len.value,
  1778. };
  1779. lbValue res = {};
  1780. res.type = t_string;
  1781. res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values));
  1782. return res;
  1783. } else {
  1784. lbAddr res = lb_add_local_generated(p, t_string, false);
  1785. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1786. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1787. return lb_addr_load(p, res);
  1788. }
  1789. }
  1790. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1791. unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name));
  1792. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1793. return LLVMCreateEnumAttribute(ctx, kind, value);
  1794. }
  1795. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1796. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1797. GB_ASSERT(attr != nullptr);
  1798. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1799. }
  1800. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1801. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  1802. }
  1803. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  1804. GB_ASSERT(entity != nullptr);
  1805. String link_name = lb_get_entity_name(m, entity);
  1806. {
  1807. StringHashKey key = string_hash_string(link_name);
  1808. lbValue *found = string_map_get(&m->members, key);
  1809. if (found) {
  1810. lb_add_entity(m, entity, *found);
  1811. lbProcedure **p_found = string_map_get(&m->procedures, key);
  1812. GB_ASSERT(p_found != nullptr);
  1813. return *p_found;
  1814. }
  1815. }
  1816. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1817. p->module = m;
  1818. entity->code_gen_module = m;
  1819. entity->code_gen_procedure = p;
  1820. p->entity = entity;
  1821. p->name = link_name;
  1822. DeclInfo *decl = entity->decl_info;
  1823. ast_node(pl, ProcLit, decl->proc_lit);
  1824. Type *pt = base_type(entity->type);
  1825. GB_ASSERT(pt->kind == Type_Proc);
  1826. set_procedure_abi_types(entity->type);
  1827. p->type = entity->type;
  1828. p->type_expr = decl->type_expr;
  1829. p->body = pl->body;
  1830. p->tags = pt->Proc.tags;
  1831. p->inlining = ProcInlining_none;
  1832. p->is_foreign = entity->Procedure.is_foreign;
  1833. p->is_export = entity->Procedure.is_export;
  1834. p->is_entry_point = false;
  1835. gbAllocator a = heap_allocator();
  1836. p->children.allocator = a;
  1837. p->params.allocator = a;
  1838. p->defer_stmts.allocator = a;
  1839. p->blocks.allocator = a;
  1840. p->branch_blocks.allocator = a;
  1841. p->context_stack.allocator = a;
  1842. if (p->is_foreign) {
  1843. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1844. }
  1845. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1846. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1847. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1848. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1849. lbFunctionType **ft_found = map_get(&m->function_type_map, hash_type(p->type));
  1850. if (USE_LLVM_ABI && ft_found) {
  1851. lbFunctionType *abi_ft = *ft_found;
  1852. p->abi_function_type = abi_ft;
  1853. lb_add_function_type_attributes(p->value, abi_ft, abi_ft->calling_convention);
  1854. } else {
  1855. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1856. // TODO(bill): Clean up this logic
  1857. if (build_context.metrics.os != TargetOs_js) {
  1858. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1859. }
  1860. LLVMSetFunctionCallConv(p->value, cc_kind);
  1861. }
  1862. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1863. // // TODO(bill): Clean up this logic
  1864. // if (build_context.metrics.os != TargetOs_js) {
  1865. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1866. // }
  1867. // LLVMSetFunctionCallConv(p->value, cc_kind);
  1868. lbValue proc_value = {p->value, p->type};
  1869. lb_add_entity(m, entity, proc_value);
  1870. lb_add_member(m, p->name, proc_value);
  1871. lb_add_procedure_value(m, p);
  1872. if (p->is_export) {
  1873. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  1874. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  1875. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  1876. if (build_context.metrics.os == TargetOs_js) {
  1877. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  1878. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  1879. }
  1880. }
  1881. if (p->is_foreign) {
  1882. if (build_context.metrics.os == TargetOs_js) {
  1883. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  1884. char const *module_name = "env";
  1885. if (entity->Procedure.foreign_library != nullptr) {
  1886. Entity *foreign_library = entity->Procedure.foreign_library;
  1887. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1888. if (foreign_library->LibraryName.paths.count > 0) {
  1889. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  1890. }
  1891. }
  1892. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  1893. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  1894. }
  1895. }
  1896. // NOTE(bill): offset==0 is the return value
  1897. isize offset = 1;
  1898. if (pt->Proc.return_by_pointer) {
  1899. if (!USE_LLVM_ABI) {
  1900. lb_add_proc_attribute_at_index(p, 1, "sret");
  1901. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1902. }
  1903. offset = 2;
  1904. }
  1905. isize parameter_index = 0;
  1906. if (pt->Proc.param_count) {
  1907. TypeTuple *params = &pt->Proc.params->Tuple;
  1908. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1909. Entity *e = params->variables[i];
  1910. Type *original_type = e->type;
  1911. Type *abi_type = pt->Proc.abi_compat_params[i];
  1912. if (e->kind != Entity_Variable) continue;
  1913. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1914. continue;
  1915. }
  1916. if (is_type_tuple(abi_type)) {
  1917. for_array(j, abi_type->Tuple.variables) {
  1918. Type *tft = abi_type->Tuple.variables[j]->type;
  1919. if (e->flags&EntityFlag_NoAlias) {
  1920. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1921. }
  1922. }
  1923. parameter_index += abi_type->Tuple.variables.count;
  1924. } else {
  1925. if (e->flags&EntityFlag_NoAlias) {
  1926. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1927. }
  1928. parameter_index += 1;
  1929. }
  1930. }
  1931. }
  1932. if (!USE_LLVM_ABI && pt->Proc.calling_convention == ProcCC_Odin) {
  1933. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1934. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1935. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1936. }
  1937. { // Debug Information
  1938. unsigned line = cast(unsigned)entity->token.pos.line;
  1939. LLVMMetadataRef file = nullptr;
  1940. if (entity->file != nullptr) {
  1941. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1942. }
  1943. LLVMMetadataRef scope = nullptr;
  1944. LLVMMetadataRef type = nullptr;
  1945. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1946. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1947. cast(char const *)entity->token.string.text, entity->token.string.len,
  1948. cast(char const *)p->name.text, p->name.len,
  1949. file, line, type,
  1950. true, p->body == nullptr,
  1951. line, LLVMDIFlagZero, false
  1952. );
  1953. GB_ASSERT(res != nullptr);
  1954. map_set(&m->debug_values, hash_pointer(p), res);
  1955. }
  1956. return p;
  1957. }
  1958. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1959. {
  1960. lbValue *found = string_map_get(&m->members, link_name);
  1961. GB_ASSERT(found == nullptr);
  1962. }
  1963. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1964. p->module = m;
  1965. p->name = link_name;
  1966. p->type = type;
  1967. p->type_expr = nullptr;
  1968. p->body = nullptr;
  1969. p->tags = 0;
  1970. p->inlining = ProcInlining_none;
  1971. p->is_foreign = false;
  1972. p->is_export = false;
  1973. p->is_entry_point = false;
  1974. gbAllocator a = permanent_allocator();
  1975. p->children.allocator = a;
  1976. p->params.allocator = a;
  1977. p->defer_stmts.allocator = a;
  1978. p->blocks.allocator = a;
  1979. p->branch_blocks.allocator = a;
  1980. p->context_stack.allocator = a;
  1981. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1982. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1983. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1984. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1985. Type *pt = p->type;
  1986. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1987. // TODO(bill): Clean up this logic
  1988. if (build_context.metrics.os != TargetOs_js) {
  1989. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1990. }
  1991. LLVMSetFunctionCallConv(p->value, cc_kind);
  1992. lbValue proc_value = {p->value, p->type};
  1993. lb_add_member(m, p->name, proc_value);
  1994. lb_add_procedure_value(m, p);
  1995. // NOTE(bill): offset==0 is the return value
  1996. isize offset = 1;
  1997. if (pt->Proc.return_by_pointer) {
  1998. lb_add_proc_attribute_at_index(p, 1, "sret");
  1999. lb_add_proc_attribute_at_index(p, 1, "noalias");
  2000. offset = 2;
  2001. }
  2002. isize parameter_index = 0;
  2003. if (!USE_LLVM_ABI && pt->Proc.param_count) {
  2004. TypeTuple *params = &pt->Proc.params->Tuple;
  2005. for (isize i = 0; i < pt->Proc.param_count; i++) {
  2006. Entity *e = params->variables[i];
  2007. Type *original_type = e->type;
  2008. Type *abi_type = pt->Proc.abi_compat_params[i];
  2009. if (e->kind != Entity_Variable) continue;
  2010. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  2011. continue;
  2012. }
  2013. if (is_type_tuple(abi_type)) {
  2014. for_array(j, abi_type->Tuple.variables) {
  2015. Type *tft = abi_type->Tuple.variables[j]->type;
  2016. if (e->flags&EntityFlag_NoAlias) {
  2017. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  2018. }
  2019. }
  2020. parameter_index += abi_type->Tuple.variables.count;
  2021. } else {
  2022. if (e->flags&EntityFlag_NoAlias) {
  2023. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2024. }
  2025. parameter_index += 1;
  2026. }
  2027. }
  2028. }
  2029. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2030. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  2031. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  2032. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  2033. }
  2034. return p;
  2035. }
  2036. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  2037. lbParamPasskind kind = lbParamPass_Value;
  2038. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  2039. if (is_type_pointer(abi_type)) {
  2040. GB_ASSERT(e->kind == Entity_Variable);
  2041. Type *av = core_type(type_deref(abi_type));
  2042. if (are_types_identical(av, core_type(e->type))) {
  2043. kind = lbParamPass_Pointer;
  2044. if (e->flags&EntityFlag_Value) {
  2045. kind = lbParamPass_ConstRef;
  2046. }
  2047. } else {
  2048. kind = lbParamPass_BitCast;
  2049. }
  2050. } else if (is_type_integer(abi_type)) {
  2051. kind = lbParamPass_Integer;
  2052. } else if (abi_type == t_llvm_bool) {
  2053. kind = lbParamPass_Value;
  2054. } else if (is_type_boolean(abi_type)) {
  2055. kind = lbParamPass_Integer;
  2056. } else if (is_type_simd_vector(abi_type)) {
  2057. kind = lbParamPass_BitCast;
  2058. } else if (is_type_float(abi_type)) {
  2059. kind = lbParamPass_BitCast;
  2060. } else if (is_type_tuple(abi_type)) {
  2061. kind = lbParamPass_Tuple;
  2062. } else if (is_type_proc(abi_type)) {
  2063. kind = lbParamPass_Value;
  2064. } else {
  2065. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  2066. }
  2067. }
  2068. if (kind_) *kind_ = kind;
  2069. lbValue res = {};
  2070. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  2071. res.type = abi_type;
  2072. return res;
  2073. }
  2074. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  2075. lbParamPasskind kind = lbParamPass_Value;
  2076. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  2077. array_add(&p->params, v);
  2078. lbValue res = {};
  2079. switch (kind) {
  2080. case lbParamPass_Value: {
  2081. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2082. lbValue x = v;
  2083. if (abi_type == t_llvm_bool) {
  2084. x = lb_emit_conv(p, x, t_bool);
  2085. }
  2086. lb_addr_store(p, l, x);
  2087. return x;
  2088. }
  2089. case lbParamPass_Pointer:
  2090. lb_add_entity(p->module, e, v);
  2091. return lb_emit_load(p, v);
  2092. case lbParamPass_Integer: {
  2093. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2094. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  2095. lb_emit_store(p, iptr, v);
  2096. return lb_addr_load(p, l);
  2097. }
  2098. case lbParamPass_ConstRef:
  2099. lb_add_entity(p->module, e, v);
  2100. return lb_emit_load(p, v);
  2101. case lbParamPass_BitCast: {
  2102. lbAddr l = lb_add_local(p, e->type, e, false, index);
  2103. lbValue x = lb_emit_transmute(p, v, e->type);
  2104. lb_addr_store(p, l, x);
  2105. return x;
  2106. }
  2107. case lbParamPass_Tuple: {
  2108. lbAddr l = lb_add_local(p, e->type, e, true, index);
  2109. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  2110. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  2111. if (abi_type->Tuple.variables.count > 0) {
  2112. array_pop(&p->params);
  2113. }
  2114. for_array(i, abi_type->Tuple.variables) {
  2115. Type *t = abi_type->Tuple.variables[i]->type;
  2116. GB_ASSERT(!is_type_tuple(t));
  2117. lbParamPasskind elem_kind = lbParamPass_Value;
  2118. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  2119. array_add(&p->params, elem);
  2120. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2121. lb_emit_store(p, dst, elem);
  2122. }
  2123. return lb_addr_load(p, l);
  2124. }
  2125. }
  2126. GB_PANIC("Unreachable");
  2127. return {};
  2128. }
  2129. void lb_start_block(lbProcedure *p, lbBlock *b) {
  2130. GB_ASSERT(b != nullptr);
  2131. if (!b->appended) {
  2132. b->appended = true;
  2133. LLVMAppendExistingBasicBlock(p->value, b->block);
  2134. }
  2135. LLVMPositionBuilderAtEnd(p->builder, b->block);
  2136. p->curr_block = b;
  2137. }
  2138. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2139. LLVMContextRef ctx = p->module->ctx;
  2140. LLVMTypeRef src_type = LLVMTypeOf(val);
  2141. if (src_type == dst_type) {
  2142. return val;
  2143. }
  2144. i64 src_size = lb_sizeof(src_type);
  2145. i64 dst_size = lb_sizeof(dst_type);
  2146. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2147. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2148. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2149. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2150. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2151. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2152. }
  2153. if (src_size != dst_size && (lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2154. // Okay
  2155. } else {
  2156. GB_ASSERT_MSG(src_size == dst_size, "%s == %s", LLVMPrintTypeToString(src_type), LLVMPrintTypeToString(dst_type));
  2157. }
  2158. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2159. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2160. if (src_kind == dst_kind) {
  2161. if (src_kind == LLVMPointerTypeKind) {
  2162. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2163. } else if (src_kind != LLVMStructTypeKind) {
  2164. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2165. }
  2166. } else {
  2167. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2168. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2169. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2170. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2171. }
  2172. }
  2173. if (LLVMIsALoadInst(val)) {
  2174. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2175. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2176. return LLVMBuildLoad(p->builder, val_ptr, "");
  2177. } else {
  2178. GB_ASSERT(p->decl_block != p->curr_block);
  2179. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2180. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2181. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2182. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2183. max_align = gb_max(max_align, 4);
  2184. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2185. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2186. LLVMBuildStore(p->builder, val, nptr);
  2187. return LLVMBuildLoad(p->builder, ptr, "");
  2188. }
  2189. }
  2190. void lb_begin_procedure_body(lbProcedure *p) {
  2191. DeclInfo *decl = decl_info_of_entity(p->entity);
  2192. if (decl != nullptr) {
  2193. for_array(i, decl->labels) {
  2194. BlockLabel bl = decl->labels[i];
  2195. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2196. array_add(&p->branch_blocks, bb);
  2197. }
  2198. }
  2199. if (p->tags != 0) {
  2200. u64 in = p->tags;
  2201. u64 out = p->module->state_flags;
  2202. if (in & ProcTag_bounds_check) {
  2203. out |= StateFlag_bounds_check;
  2204. out &= ~StateFlag_no_bounds_check;
  2205. } else if (in & ProcTag_no_bounds_check) {
  2206. out |= StateFlag_no_bounds_check;
  2207. out &= ~StateFlag_bounds_check;
  2208. }
  2209. p->module->state_flags = out;
  2210. }
  2211. p->builder = LLVMCreateBuilder();
  2212. p->decl_block = lb_create_block(p, "decls", true);
  2213. p->entry_block = lb_create_block(p, "entry", true);
  2214. lb_start_block(p, p->entry_block);
  2215. GB_ASSERT(p->type != nullptr);
  2216. if (p->abi_function_type) {
  2217. lbFunctionType *ft = p->abi_function_type;
  2218. unsigned param_offset = 0;
  2219. lbValue return_ptr_value = {};
  2220. if (ft->ret.kind == lbArg_Indirect) {
  2221. // NOTE(bill): this must be parameter 0
  2222. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2223. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2224. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2225. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2226. return_ptr_value.type = ptr_type;
  2227. p->return_ptr = lb_addr(return_ptr_value);
  2228. lb_add_entity(p->module, e, return_ptr_value);
  2229. param_offset += 1;
  2230. }
  2231. if (p->type->Proc.params != nullptr) {
  2232. TypeTuple *params = &p->type->Proc.params->Tuple;
  2233. unsigned param_index = 0;
  2234. for_array(i, params->variables) {
  2235. Entity *e = params->variables[i];
  2236. if (e->kind != Entity_Variable) {
  2237. continue;
  2238. }
  2239. lbArgType *arg_type = &ft->args[param_index];
  2240. if (arg_type->kind == lbArg_Ignore) {
  2241. continue;
  2242. } else if (arg_type->kind == lbArg_Direct) {
  2243. lbParamPasskind kind = lbParamPass_Value;
  2244. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2245. if (param_type != arg_type->type) {
  2246. kind = lbParamPass_BitCast;
  2247. }
  2248. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2249. value = OdinLLVMBuildTransmute(p, value, param_type);
  2250. lbValue param = {};
  2251. param.value = value;
  2252. param.type = e->type;
  2253. array_add(&p->params, param);
  2254. if (e->token.string.len != 0) {
  2255. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2256. lb_addr_store(p, l, param);
  2257. }
  2258. param_index += 1;
  2259. } else if (arg_type->kind == lbArg_Indirect) {
  2260. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2261. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2262. lbValue param = {};
  2263. param.value = value;
  2264. param.type = e->type;
  2265. array_add(&p->params, param);
  2266. lbValue ptr = {};
  2267. ptr.value = value_ptr;
  2268. ptr.type = alloc_type_pointer(e->type);
  2269. lb_add_entity(p->module, e, ptr);
  2270. param_index += 1;
  2271. }
  2272. }
  2273. }
  2274. if (p->type->Proc.has_named_results) {
  2275. GB_ASSERT(p->type->Proc.result_count > 0);
  2276. TypeTuple *results = &p->type->Proc.results->Tuple;
  2277. for_array(i, results->variables) {
  2278. Entity *e = results->variables[i];
  2279. GB_ASSERT(e->kind == Entity_Variable);
  2280. if (e->token.string != "") {
  2281. GB_ASSERT(!is_blank_ident(e->token));
  2282. lbAddr res = {};
  2283. if (return_ptr_value.value) {
  2284. lbValue ptr = return_ptr_value;
  2285. if (results->variables.count != 1) {
  2286. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2287. }
  2288. res = lb_addr(ptr);
  2289. lb_add_entity(p->module, e, ptr);
  2290. } else {
  2291. res = lb_add_local(p, e->type, e);
  2292. }
  2293. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2294. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2295. lb_addr_store(p, res, c);
  2296. }
  2297. }
  2298. }
  2299. }
  2300. } else {
  2301. i32 parameter_index = 0;
  2302. lbValue return_ptr_value = {};
  2303. if (p->type->Proc.return_by_pointer) {
  2304. // NOTE(bill): this must be parameter 0
  2305. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2306. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2307. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2308. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2309. return_ptr_value.type = ptr_type;
  2310. p->return_ptr = lb_addr(return_ptr_value);
  2311. lb_add_entity(p->module, e, return_ptr_value);
  2312. parameter_index += 1;
  2313. }
  2314. if (p->type->Proc.params != nullptr) {
  2315. TypeTuple *params = &p->type->Proc.params->Tuple;
  2316. auto abi_types = p->type->Proc.abi_compat_params;
  2317. for_array(i, params->variables) {
  2318. Entity *e = params->variables[i];
  2319. if (e->kind != Entity_Variable) {
  2320. continue;
  2321. }
  2322. Type *abi_type = e->type;
  2323. if (abi_types.count > 0) {
  2324. abi_type = abi_types[i];
  2325. }
  2326. if (e->token.string != "") {
  2327. lb_add_param(p, e, nullptr, abi_type, parameter_index);
  2328. }
  2329. if (is_type_tuple(abi_type)) {
  2330. parameter_index += cast(i32)abi_type->Tuple.variables.count;
  2331. } else {
  2332. parameter_index += 1;
  2333. }
  2334. }
  2335. }
  2336. if (p->type->Proc.has_named_results) {
  2337. GB_ASSERT(p->type->Proc.result_count > 0);
  2338. TypeTuple *results = &p->type->Proc.results->Tuple;
  2339. for_array(i, results->variables) {
  2340. Entity *e = results->variables[i];
  2341. GB_ASSERT(e->kind == Entity_Variable);
  2342. if (e->token.string != "") {
  2343. GB_ASSERT(!is_blank_ident(e->token));
  2344. lbAddr res = {};
  2345. if (p->type->Proc.return_by_pointer) {
  2346. lbValue ptr = return_ptr_value;
  2347. if (results->variables.count != 1) {
  2348. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2349. }
  2350. res = lb_addr(ptr);
  2351. lb_add_entity(p->module, e, ptr);
  2352. } else {
  2353. res = lb_add_local(p, e->type, e);
  2354. }
  2355. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2356. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2357. lb_addr_store(p, res, c);
  2358. }
  2359. }
  2360. }
  2361. }
  2362. }
  2363. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2364. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  2365. e->flags |= EntityFlag_NoAlias;
  2366. lbValue param = {};
  2367. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  2368. param.type = e->type;
  2369. lb_add_entity(p->module, e, param);
  2370. lbAddr ctx_addr = {};
  2371. ctx_addr.kind = lbAddr_Context;
  2372. ctx_addr.addr = param;
  2373. lbContextData ctx = {ctx_addr, p->scope_index};
  2374. array_add(&p->context_stack, ctx);
  2375. }
  2376. lb_start_block(p, p->entry_block);
  2377. }
  2378. void lb_end_procedure_body(lbProcedure *p) {
  2379. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2380. LLVMBuildBr(p->builder, p->entry_block->block);
  2381. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2382. if (p->type->Proc.result_count == 0) {
  2383. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2384. if (!lb_is_instr_terminating(instr)) {
  2385. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2386. LLVMBuildRetVoid(p->builder);
  2387. }
  2388. } else {
  2389. if (p->curr_block->preds.count == 0) {
  2390. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2391. if (instr == nullptr) {
  2392. // NOTE(bill): Remove dead trailing block
  2393. LLVMDeleteBasicBlock(p->curr_block->block);
  2394. }
  2395. }
  2396. }
  2397. p->curr_block = nullptr;
  2398. p->module->state_flags = 0;
  2399. }
  2400. void lb_end_procedure(lbProcedure *p) {
  2401. LLVMDisposeBuilder(p->builder);
  2402. }
  2403. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2404. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2405. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2406. array_add(&from->succs, to);
  2407. array_add(&to->preds, from);
  2408. }
  2409. }
  2410. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2411. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2412. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2413. b->appended = false;
  2414. if (append) {
  2415. b->appended = true;
  2416. LLVMAppendExistingBasicBlock(p->value, b->block);
  2417. }
  2418. b->scope = p->curr_scope;
  2419. b->scope_index = p->scope_index;
  2420. b->preds.allocator = heap_allocator();
  2421. b->succs.allocator = heap_allocator();
  2422. array_add(&p->blocks, b);
  2423. return b;
  2424. }
  2425. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2426. if (p->curr_block == nullptr) {
  2427. return;
  2428. }
  2429. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2430. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2431. return;
  2432. }
  2433. lb_add_edge(p->curr_block, target_block);
  2434. LLVMBuildBr(p->builder, target_block->block);
  2435. p->curr_block = nullptr;
  2436. }
  2437. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2438. lbBlock *b = p->curr_block;
  2439. if (b == nullptr) {
  2440. return;
  2441. }
  2442. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2443. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2444. return;
  2445. }
  2446. lb_add_edge(b, true_block);
  2447. lb_add_edge(b, false_block);
  2448. LLVMValueRef cv = cond.value;
  2449. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2450. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2451. }
  2452. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2453. GB_ASSERT(cond != nullptr);
  2454. GB_ASSERT(true_block != nullptr);
  2455. GB_ASSERT(false_block != nullptr);
  2456. switch (cond->kind) {
  2457. case_ast_node(pe, ParenExpr, cond);
  2458. return lb_build_cond(p, pe->expr, true_block, false_block);
  2459. case_end;
  2460. case_ast_node(ue, UnaryExpr, cond);
  2461. if (ue->op.kind == Token_Not) {
  2462. return lb_build_cond(p, ue->expr, false_block, true_block);
  2463. }
  2464. case_end;
  2465. case_ast_node(be, BinaryExpr, cond);
  2466. if (be->op.kind == Token_CmpAnd) {
  2467. lbBlock *block = lb_create_block(p, "cmp.and");
  2468. lb_build_cond(p, be->left, block, false_block);
  2469. lb_start_block(p, block);
  2470. return lb_build_cond(p, be->right, true_block, false_block);
  2471. } else if (be->op.kind == Token_CmpOr) {
  2472. lbBlock *block = lb_create_block(p, "cmp.or");
  2473. lb_build_cond(p, be->left, true_block, block);
  2474. lb_start_block(p, block);
  2475. return lb_build_cond(p, be->right, true_block, false_block);
  2476. }
  2477. case_end;
  2478. }
  2479. lbValue v = lb_build_expr(p, cond);
  2480. // v = lb_emit_conv(p, v, t_bool);
  2481. v = lb_emit_conv(p, v, t_llvm_bool);
  2482. lb_emit_if(p, v, true_block, false_block);
  2483. return v;
  2484. }
  2485. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2486. GB_ASSERT(p->decl_block != p->curr_block);
  2487. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2488. char const *name = "";
  2489. if (e != nullptr) {
  2490. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2491. }
  2492. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2493. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2494. LLVMSetAlignment(ptr, 16); // TODO(bill): Make this configurable
  2495. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2496. if (zero_init) {
  2497. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2498. }
  2499. lbValue val = {};
  2500. val.value = ptr;
  2501. val.type = alloc_type_pointer(type);
  2502. if (e != nullptr) {
  2503. lb_add_entity(p->module, e, val);
  2504. }
  2505. return lb_addr(val);
  2506. }
  2507. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2508. return lb_add_local(p, type, nullptr, zero_init);
  2509. }
  2510. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2511. GB_ASSERT(pd->body != nullptr);
  2512. lbModule *m = p->module;
  2513. auto *min_dep_set = &m->info->minimum_dependency_set;
  2514. if (ptr_set_exists(min_dep_set, e) == false) {
  2515. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2516. return;
  2517. }
  2518. // NOTE(bill): Generate a new name
  2519. // parent.name-guid
  2520. String original_name = e->token.string;
  2521. String pd_name = original_name;
  2522. if (e->Procedure.link_name.len > 0) {
  2523. pd_name = e->Procedure.link_name;
  2524. }
  2525. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2526. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2527. i32 guid = cast(i32)p->children.count;
  2528. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2529. String name = make_string(cast(u8 *)name_text, name_len-1);
  2530. set_procedure_abi_types(e->type);
  2531. e->Procedure.link_name = name;
  2532. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2533. e->code_gen_procedure = nested_proc;
  2534. lbValue value = {};
  2535. value.value = nested_proc->value;
  2536. value.type = nested_proc->type;
  2537. lb_add_entity(m, e, value);
  2538. array_add(&p->children, nested_proc);
  2539. array_add(&m->procedures_to_generate, nested_proc);
  2540. }
  2541. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2542. if (e == nullptr) {
  2543. return;
  2544. }
  2545. GB_ASSERT(e->kind == Entity_LibraryName);
  2546. GB_ASSERT(e->flags & EntityFlag_Used);
  2547. for_array(i, e->LibraryName.paths) {
  2548. String library_path = e->LibraryName.paths[i];
  2549. if (library_path.len == 0) {
  2550. continue;
  2551. }
  2552. bool ok = true;
  2553. for_array(path_index, m->foreign_library_paths) {
  2554. String path = m->foreign_library_paths[path_index];
  2555. #if defined(GB_SYSTEM_WINDOWS)
  2556. if (str_eq_ignore_case(path, library_path)) {
  2557. #else
  2558. if (str_eq(path, library_path)) {
  2559. #endif
  2560. ok = false;
  2561. break;
  2562. }
  2563. }
  2564. if (ok) {
  2565. array_add(&m->foreign_library_paths, library_path);
  2566. }
  2567. }
  2568. }
  2569. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2570. if (vd == nullptr || vd->is_mutable) {
  2571. return;
  2572. }
  2573. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2574. static i32 global_guid = 0;
  2575. for_array(i, vd->names) {
  2576. Ast *ident = vd->names[i];
  2577. GB_ASSERT(ident->kind == Ast_Ident);
  2578. Entity *e = entity_of_node(ident);
  2579. GB_ASSERT(e != nullptr);
  2580. if (e->kind != Entity_TypeName) {
  2581. continue;
  2582. }
  2583. bool polymorphic_struct = false;
  2584. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2585. Type *bt = base_type(e->type);
  2586. if (bt->kind == Type_Struct) {
  2587. polymorphic_struct = bt->Struct.is_polymorphic;
  2588. }
  2589. }
  2590. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2591. continue;
  2592. }
  2593. if (e->TypeName.ir_mangled_name.len != 0) {
  2594. // NOTE(bill): Already set
  2595. continue;
  2596. }
  2597. lb_set_nested_type_name_ir_mangled_name(e, p);
  2598. }
  2599. for_array(i, vd->names) {
  2600. Ast *ident = vd->names[i];
  2601. GB_ASSERT(ident->kind == Ast_Ident);
  2602. Entity *e = entity_of_node(ident);
  2603. GB_ASSERT(e != nullptr);
  2604. if (e->kind != Entity_Procedure) {
  2605. continue;
  2606. }
  2607. CheckerInfo *info = p->module->info;
  2608. DeclInfo *decl = decl_info_of_entity(e);
  2609. ast_node(pl, ProcLit, decl->proc_lit);
  2610. if (pl->body != nullptr) {
  2611. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2612. if (found) {
  2613. auto procs = *found;
  2614. for_array(i, procs) {
  2615. Entity *e = procs[i];
  2616. if (!ptr_set_exists(min_dep_set, e)) {
  2617. continue;
  2618. }
  2619. DeclInfo *d = decl_info_of_entity(e);
  2620. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2621. }
  2622. } else {
  2623. lb_build_nested_proc(p, pl, e);
  2624. }
  2625. } else {
  2626. // FFI - Foreign function interace
  2627. String original_name = e->token.string;
  2628. String name = original_name;
  2629. if (e->Procedure.is_foreign) {
  2630. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2631. }
  2632. if (e->Procedure.link_name.len > 0) {
  2633. name = e->Procedure.link_name;
  2634. }
  2635. lbValue *prev_value = string_map_get(&p->module->members, name);
  2636. if (prev_value != nullptr) {
  2637. // NOTE(bill): Don't do mutliple declarations in the IR
  2638. return;
  2639. }
  2640. set_procedure_abi_types(e->type);
  2641. e->Procedure.link_name = name;
  2642. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2643. lbValue value = {};
  2644. value.value = nested_proc->value;
  2645. value.type = nested_proc->type;
  2646. array_add(&p->module->procedures_to_generate, nested_proc);
  2647. if (p != nullptr) {
  2648. array_add(&p->children, nested_proc);
  2649. } else {
  2650. string_map_set(&p->module->members, name, value);
  2651. }
  2652. }
  2653. }
  2654. }
  2655. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  2656. for_array(i, stmts) {
  2657. Ast *stmt = stmts[i];
  2658. switch (stmt->kind) {
  2659. case_ast_node(vd, ValueDecl, stmt);
  2660. lb_build_constant_value_decl(p, vd);
  2661. case_end;
  2662. case_ast_node(fb, ForeignBlockDecl, stmt);
  2663. ast_node(block, BlockStmt, fb->body);
  2664. lb_build_stmt_list(p, block->stmts);
  2665. case_end;
  2666. }
  2667. }
  2668. for_array(i, stmts) {
  2669. lb_build_stmt(p, stmts[i]);
  2670. }
  2671. }
  2672. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2673. GB_ASSERT(ident->kind == Ast_Ident);
  2674. Entity *e = entity_of_node(ident);
  2675. GB_ASSERT(e->kind == Entity_Label);
  2676. for_array(i, p->branch_blocks) {
  2677. lbBranchBlocks *b = &p->branch_blocks[i];
  2678. if (b->label == e->Label.node) {
  2679. return *b;
  2680. }
  2681. }
  2682. GB_PANIC("Unreachable");
  2683. lbBranchBlocks empty = {};
  2684. return empty;
  2685. }
  2686. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2687. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  2688. tl->prev = p->target_list;
  2689. tl->break_ = break_;
  2690. tl->continue_ = continue_;
  2691. tl->fallthrough_ = fallthrough_;
  2692. p->target_list = tl;
  2693. if (label != nullptr) { // Set label blocks
  2694. GB_ASSERT(label->kind == Ast_Label);
  2695. for_array(i, p->branch_blocks) {
  2696. lbBranchBlocks *b = &p->branch_blocks[i];
  2697. GB_ASSERT(b->label != nullptr && label != nullptr);
  2698. GB_ASSERT(b->label->kind == Ast_Label);
  2699. if (b->label == label) {
  2700. b->break_ = break_;
  2701. b->continue_ = continue_;
  2702. return tl;
  2703. }
  2704. }
  2705. GB_PANIC("Unreachable");
  2706. }
  2707. return tl;
  2708. }
  2709. void lb_pop_target_list(lbProcedure *p) {
  2710. p->target_list = p->target_list->prev;
  2711. }
  2712. void lb_open_scope(lbProcedure *p) {
  2713. p->scope_index += 1;
  2714. }
  2715. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2716. lb_emit_defer_stmts(p, kind, block);
  2717. GB_ASSERT(p->scope_index > 0);
  2718. // NOTE(bill): Remove `context`s made in that scope
  2719. while (p->context_stack.count > 0) {
  2720. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2721. if (ctx->scope_index >= p->scope_index) {
  2722. array_pop(&p->context_stack);
  2723. } else {
  2724. break;
  2725. }
  2726. }
  2727. p->scope_index -= 1;
  2728. }
  2729. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2730. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2731. GB_ASSERT(is_type_boolean(tv.type));
  2732. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2733. if (tv.value.value_bool) {
  2734. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  2735. } else if (ws->else_stmt) {
  2736. switch (ws->else_stmt->kind) {
  2737. case Ast_BlockStmt:
  2738. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  2739. break;
  2740. case Ast_WhenStmt:
  2741. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  2742. break;
  2743. default:
  2744. GB_PANIC("Invalid 'else' statement in 'when' statement");
  2745. break;
  2746. }
  2747. }
  2748. }
  2749. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  2750. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2751. lbModule *m = p->module;
  2752. lbValue count = {};
  2753. Type *expr_type = base_type(type_deref(expr.type));
  2754. switch (expr_type->kind) {
  2755. case Type_Array:
  2756. count = lb_const_int(m, t_int, expr_type->Array.count);
  2757. break;
  2758. }
  2759. lbValue val = {};
  2760. lbValue idx = {};
  2761. lbBlock *loop = nullptr;
  2762. lbBlock *done = nullptr;
  2763. lbBlock *body = nullptr;
  2764. lbAddr index = lb_add_local_generated(p, t_int, false);
  2765. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  2766. loop = lb_create_block(p, "for.index.loop");
  2767. lb_emit_jump(p, loop);
  2768. lb_start_block(p, loop);
  2769. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  2770. lb_addr_store(p, index, incr);
  2771. body = lb_create_block(p, "for.index.body");
  2772. done = lb_create_block(p, "for.index.done");
  2773. if (count.value == nullptr) {
  2774. GB_ASSERT(count_ptr.value != nullptr);
  2775. count = lb_emit_load(p, count_ptr);
  2776. }
  2777. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  2778. lb_emit_if(p, cond, body, done);
  2779. lb_start_block(p, body);
  2780. idx = lb_addr_load(p, index);
  2781. switch (expr_type->kind) {
  2782. case Type_Array: {
  2783. if (val_type != nullptr) {
  2784. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2785. }
  2786. break;
  2787. }
  2788. case Type_EnumeratedArray: {
  2789. if (val_type != nullptr) {
  2790. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2791. // NOTE(bill): Override the idx value for the enumeration
  2792. Type *index_type = expr_type->EnumeratedArray.index;
  2793. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  2794. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  2795. }
  2796. }
  2797. break;
  2798. }
  2799. case Type_Slice: {
  2800. if (val_type != nullptr) {
  2801. lbValue elem = lb_slice_elem(p, expr);
  2802. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2803. }
  2804. break;
  2805. }
  2806. case Type_DynamicArray: {
  2807. if (val_type != nullptr) {
  2808. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  2809. elem = lb_emit_load(p, elem);
  2810. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2811. }
  2812. break;
  2813. }
  2814. case Type_Map: {
  2815. lbValue entries = lb_map_entries_ptr(p, expr);
  2816. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  2817. elem = lb_emit_load(p, elem);
  2818. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  2819. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  2820. lbValue key_raw = lb_emit_struct_ep(p, entry, 0);
  2821. key_raw = lb_emit_struct_ep(p, key_raw, 1);
  2822. lbValue key = lb_emit_conv(p, key_raw, alloc_type_pointer(expr_type->Map.key));
  2823. idx = lb_emit_load(p, key);
  2824. break;
  2825. }
  2826. default:
  2827. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  2828. break;
  2829. }
  2830. if (val_) *val_ = val;
  2831. if (idx_) *idx_ = idx;
  2832. if (loop_) *loop_ = loop;
  2833. if (done_) *done_ = done;
  2834. }
  2835. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  2836. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2837. lbModule *m = p->module;
  2838. lbValue count = lb_const_int(m, t_int, 0);
  2839. Type *expr_type = base_type(expr.type);
  2840. switch (expr_type->kind) {
  2841. case Type_Basic:
  2842. count = lb_string_len(p, expr);
  2843. break;
  2844. default:
  2845. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  2846. break;
  2847. }
  2848. lbValue val = {};
  2849. lbValue idx = {};
  2850. lbBlock *loop = nullptr;
  2851. lbBlock *done = nullptr;
  2852. lbBlock *body = nullptr;
  2853. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2854. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2855. loop = lb_create_block(p, "for.string.loop");
  2856. lb_emit_jump(p, loop);
  2857. lb_start_block(p, loop);
  2858. body = lb_create_block(p, "for.string.body");
  2859. done = lb_create_block(p, "for.string.done");
  2860. lbValue offset = lb_addr_load(p, offset_);
  2861. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  2862. lb_emit_if(p, cond, body, done);
  2863. lb_start_block(p, body);
  2864. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  2865. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  2866. auto args = array_make<lbValue>(permanent_allocator(), 1);
  2867. args[0] = lb_emit_string(p, str_elem, str_len);
  2868. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  2869. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  2870. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  2871. idx = offset;
  2872. if (val_type != nullptr) {
  2873. val = lb_emit_struct_ev(p, rune_and_len, 0);
  2874. }
  2875. if (val_) *val_ = val;
  2876. if (idx_) *idx_ = idx;
  2877. if (loop_) *loop_ = loop;
  2878. if (done_) *done_ = done;
  2879. }
  2880. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  2881. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2882. lbModule *m = p->module;
  2883. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  2884. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  2885. lbValue lower = lb_build_expr(p, node->left);
  2886. lbValue upper = {};
  2887. lbValue val = {};
  2888. lbValue idx = {};
  2889. lbBlock *loop = nullptr;
  2890. lbBlock *done = nullptr;
  2891. lbBlock *body = nullptr;
  2892. if (val_type == nullptr) {
  2893. val_type = lower.type;
  2894. }
  2895. lbAddr value = lb_add_local_generated(p, val_type, false);
  2896. lb_addr_store(p, value, lower);
  2897. lbAddr index = lb_add_local_generated(p, t_int, false);
  2898. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  2899. loop = lb_create_block(p, "for.interval.loop");
  2900. lb_emit_jump(p, loop);
  2901. lb_start_block(p, loop);
  2902. body = lb_create_block(p, "for.interval.body");
  2903. done = lb_create_block(p, "for.interval.done");
  2904. TokenKind op = Token_Lt;
  2905. switch (node->op.kind) {
  2906. case Token_Ellipsis: op = Token_LtEq; break;
  2907. case Token_RangeHalf: op = Token_Lt; break;
  2908. default: GB_PANIC("Invalid interval operator"); break;
  2909. }
  2910. upper = lb_build_expr(p, node->right);
  2911. lbValue curr_value = lb_addr_load(p, value);
  2912. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  2913. lb_emit_if(p, cond, body, done);
  2914. lb_start_block(p, body);
  2915. val = lb_addr_load(p, value);
  2916. idx = lb_addr_load(p, index);
  2917. lb_emit_increment(p, value.addr);
  2918. lb_emit_increment(p, index.addr);
  2919. if (val_) *val_ = val;
  2920. if (idx_) *idx_ = idx;
  2921. if (loop_) *loop_ = loop;
  2922. if (done_) *done_ = done;
  2923. }
  2924. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2925. lbModule *m = p->module;
  2926. Type *t = enum_type;
  2927. GB_ASSERT(is_type_enum(t));
  2928. Type *enum_ptr = alloc_type_pointer(t);
  2929. t = base_type(t);
  2930. Type *core_elem = core_type(t);
  2931. GB_ASSERT(t->kind == Type_Enum);
  2932. i64 enum_count = t->Enum.fields.count;
  2933. lbValue max_count = lb_const_int(m, t_int, enum_count);
  2934. lbValue ti = lb_type_info(m, t);
  2935. lbValue variant = lb_emit_struct_ep(p, ti, 3);
  2936. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  2937. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  2938. lbValue values_data = lb_slice_elem(p, values);
  2939. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2940. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2941. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  2942. lb_emit_jump(p, loop);
  2943. lb_start_block(p, loop);
  2944. lbBlock *body = lb_create_block(p, "for.enum.body");
  2945. lbBlock *done = lb_create_block(p, "for.enum.done");
  2946. lbValue offset = lb_addr_load(p, offset_);
  2947. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  2948. lb_emit_if(p, cond, body, done);
  2949. lb_start_block(p, body);
  2950. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  2951. lb_emit_increment(p, offset_.addr);
  2952. lbValue val = {};
  2953. if (val_type != nullptr) {
  2954. GB_ASSERT(are_types_identical(enum_type, val_type));
  2955. if (is_type_integer(core_elem)) {
  2956. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  2957. val = lb_emit_conv(p, i, t);
  2958. } else {
  2959. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  2960. }
  2961. }
  2962. if (val_) *val_ = val;
  2963. if (idx_) *idx_ = offset;
  2964. if (loop_) *loop_ = loop;
  2965. if (done_) *done_ = done;
  2966. }
  2967. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  2968. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  2969. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  2970. lb_emit_jump(p, loop);
  2971. lb_start_block(p, loop);
  2972. lbBlock *body = lb_create_block(p, "for.tuple.body");
  2973. lbBlock *done = lb_create_block(p, "for.tuple.done");
  2974. lbValue tuple_value = lb_build_expr(p, expr);
  2975. Type *tuple = tuple_value.type;
  2976. GB_ASSERT(tuple->kind == Type_Tuple);
  2977. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  2978. i32 cond_index = tuple_count-1;
  2979. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  2980. lb_emit_if(p, cond, body, done);
  2981. lb_start_block(p, body);
  2982. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  2983. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  2984. if (loop_) *loop_ = loop;
  2985. if (done_) *done_ = done;
  2986. }
  2987. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  2988. lb_open_scope(p);
  2989. Type *val0_type = nullptr;
  2990. Type *val1_type = nullptr;
  2991. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2992. val0_type = type_of_expr(rs->val0);
  2993. }
  2994. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2995. val1_type = type_of_expr(rs->val1);
  2996. }
  2997. if (val0_type != nullptr) {
  2998. Entity *e = entity_of_node(rs->val0);
  2999. lb_add_local(p, e->type, e, true);
  3000. }
  3001. if (val1_type != nullptr) {
  3002. Entity *e = entity_of_node(rs->val1);
  3003. lb_add_local(p, e->type, e, true);
  3004. }
  3005. lbValue val = {};
  3006. lbValue key = {};
  3007. lbBlock *loop = nullptr;
  3008. lbBlock *done = nullptr;
  3009. Ast *expr = unparen_expr(rs->expr);
  3010. bool is_map = false;
  3011. TypeAndValue tav = type_and_value_of_expr(expr);
  3012. if (is_ast_range(expr)) {
  3013. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  3014. } else if (tav.mode == Addressing_Type) {
  3015. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  3016. } else {
  3017. Type *expr_type = type_of_expr(expr);
  3018. Type *et = base_type(type_deref(expr_type));
  3019. switch (et->kind) {
  3020. case Type_Map: {
  3021. is_map = true;
  3022. lbValue map = lb_build_addr_ptr(p, expr);
  3023. if (is_type_pointer(type_deref(map.type))) {
  3024. map = lb_emit_load(p, map);
  3025. }
  3026. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  3027. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  3028. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  3029. break;
  3030. }
  3031. case Type_Array: {
  3032. lbValue array = lb_build_addr_ptr(p, expr);
  3033. if (is_type_pointer(type_deref(array.type))) {
  3034. array = lb_emit_load(p, array);
  3035. }
  3036. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3037. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  3038. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3039. break;
  3040. }
  3041. case Type_EnumeratedArray: {
  3042. lbValue array = lb_build_addr_ptr(p, expr);
  3043. if (is_type_pointer(type_deref(array.type))) {
  3044. array = lb_emit_load(p, array);
  3045. }
  3046. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  3047. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  3048. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  3049. break;
  3050. }
  3051. case Type_DynamicArray: {
  3052. lbValue count_ptr = {};
  3053. lbValue array = lb_build_addr_ptr(p, expr);
  3054. if (is_type_pointer(type_deref(array.type))) {
  3055. array = lb_emit_load(p, array);
  3056. }
  3057. count_ptr = lb_emit_struct_ep(p, array, 1);
  3058. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  3059. break;
  3060. }
  3061. case Type_Slice: {
  3062. lbValue count_ptr = {};
  3063. lbValue slice = lb_build_expr(p, expr);
  3064. if (is_type_pointer(slice.type)) {
  3065. count_ptr = lb_emit_struct_ep(p, slice, 1);
  3066. slice = lb_emit_load(p, slice);
  3067. } else {
  3068. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  3069. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  3070. }
  3071. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  3072. break;
  3073. }
  3074. case Type_Basic: {
  3075. lbValue string = lb_build_expr(p, expr);
  3076. if (is_type_pointer(string.type)) {
  3077. string = lb_emit_load(p, string);
  3078. }
  3079. if (is_type_untyped(expr_type)) {
  3080. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  3081. lb_addr_store(p, s, string);
  3082. string = lb_addr_load(p, s);
  3083. }
  3084. Type *t = base_type(string.type);
  3085. GB_ASSERT(!is_type_cstring(t));
  3086. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  3087. break;
  3088. }
  3089. case Type_Tuple:
  3090. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  3091. break;
  3092. default:
  3093. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  3094. break;
  3095. }
  3096. }
  3097. if (is_map) {
  3098. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  3099. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  3100. } else {
  3101. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  3102. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  3103. }
  3104. lb_push_target_list(p, rs->label, done, loop, nullptr);
  3105. lb_build_stmt(p, rs->body);
  3106. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3107. lb_pop_target_list(p);
  3108. lb_emit_jump(p, loop);
  3109. lb_start_block(p, done);
  3110. }
  3111. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  3112. lbModule *m = p->module;
  3113. lb_open_scope(p); // Open scope here
  3114. Type *val0_type = nullptr;
  3115. Type *val1_type = nullptr;
  3116. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  3117. val0_type = type_of_expr(rs->val0);
  3118. }
  3119. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  3120. val1_type = type_of_expr(rs->val1);
  3121. }
  3122. if (val0_type != nullptr) {
  3123. Entity *e = entity_of_node(rs->val0);
  3124. lb_add_local(p, e->type, e, true);
  3125. }
  3126. if (val1_type != nullptr) {
  3127. Entity *e = entity_of_node(rs->val1);
  3128. lb_add_local(p, e->type, e, true);
  3129. }
  3130. lbValue val = {};
  3131. lbValue key = {};
  3132. lbBlock *loop = nullptr;
  3133. lbBlock *done = nullptr;
  3134. Ast *expr = unparen_expr(rs->expr);
  3135. TypeAndValue tav = type_and_value_of_expr(expr);
  3136. if (is_ast_range(expr)) {
  3137. lbAddr val0_addr = {};
  3138. lbAddr val1_addr = {};
  3139. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3140. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3141. TokenKind op = expr->BinaryExpr.op.kind;
  3142. Ast *start_expr = expr->BinaryExpr.left;
  3143. Ast *end_expr = expr->BinaryExpr.right;
  3144. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  3145. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  3146. ExactValue start = start_expr->tav.value;
  3147. ExactValue end = end_expr->tav.value;
  3148. if (op == Token_Ellipsis) { // .. [start, end]
  3149. ExactValue index = exact_value_i64(0);
  3150. for (ExactValue val = start;
  3151. compare_exact_values(Token_LtEq, val, end);
  3152. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3153. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3154. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3155. lb_build_stmt(p, rs->body);
  3156. }
  3157. } else if (op == Token_RangeHalf) { // ..< [start, end)
  3158. ExactValue index = exact_value_i64(0);
  3159. for (ExactValue val = start;
  3160. compare_exact_values(Token_Lt, val, end);
  3161. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  3162. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  3163. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  3164. lb_build_stmt(p, rs->body);
  3165. }
  3166. }
  3167. } else if (tav.mode == Addressing_Type) {
  3168. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  3169. Type *et = type_deref(tav.type);
  3170. Type *bet = base_type(et);
  3171. lbAddr val0_addr = {};
  3172. lbAddr val1_addr = {};
  3173. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3174. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3175. for_array(i, bet->Enum.fields) {
  3176. Entity *field = bet->Enum.fields[i];
  3177. GB_ASSERT(field->kind == Entity_Constant);
  3178. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  3179. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3180. lb_build_stmt(p, rs->body);
  3181. }
  3182. } else {
  3183. lbAddr val0_addr = {};
  3184. lbAddr val1_addr = {};
  3185. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  3186. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  3187. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  3188. Type *t = base_type(expr->tav.type);
  3189. switch (t->kind) {
  3190. case Type_Basic:
  3191. GB_ASSERT(is_type_string(t));
  3192. {
  3193. ExactValue value = expr->tav.value;
  3194. GB_ASSERT(value.kind == ExactValue_String);
  3195. String str = value.value_string;
  3196. Rune codepoint = 0;
  3197. isize offset = 0;
  3198. do {
  3199. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  3200. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  3201. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  3202. lb_build_stmt(p, rs->body);
  3203. offset += width;
  3204. } while (offset < str.len);
  3205. }
  3206. break;
  3207. case Type_Array:
  3208. if (t->Array.count > 0) {
  3209. lbValue val = lb_build_expr(p, expr);
  3210. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3211. for (i64 i = 0; i < t->Array.count; i++) {
  3212. if (val0_type) {
  3213. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3214. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3215. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3216. }
  3217. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  3218. lb_build_stmt(p, rs->body);
  3219. }
  3220. }
  3221. break;
  3222. case Type_EnumeratedArray:
  3223. if (t->EnumeratedArray.count > 0) {
  3224. lbValue val = lb_build_expr(p, expr);
  3225. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  3226. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3227. if (val0_type) {
  3228. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3229. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3230. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3231. }
  3232. if (val1_type) {
  3233. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3234. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3235. }
  3236. lb_build_stmt(p, rs->body);
  3237. }
  3238. }
  3239. break;
  3240. default:
  3241. GB_PANIC("Invalid inline for type");
  3242. break;
  3243. }
  3244. }
  3245. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3246. }
  3247. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  3248. if (ss->init != nullptr) {
  3249. lb_build_stmt(p, ss->init);
  3250. }
  3251. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3252. if (ss->tag != nullptr) {
  3253. tag = lb_build_expr(p, ss->tag);
  3254. }
  3255. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3256. ast_node(body, BlockStmt, ss->body);
  3257. Slice<Ast *> default_stmts = {};
  3258. lbBlock *default_fall = nullptr;
  3259. lbBlock *default_block = nullptr;
  3260. lbBlock *fall = nullptr;
  3261. isize case_count = body->stmts.count;
  3262. for_array(i, body->stmts) {
  3263. Ast *clause = body->stmts[i];
  3264. ast_node(cc, CaseClause, clause);
  3265. lbBlock *body = fall;
  3266. if (body == nullptr) {
  3267. body = lb_create_block(p, "switch.case.body");
  3268. }
  3269. fall = done;
  3270. if (i+1 < case_count) {
  3271. fall = lb_create_block(p, "switch.fall.body");
  3272. }
  3273. if (cc->list.count == 0) {
  3274. // default case
  3275. default_stmts = cc->stmts;
  3276. default_fall = fall;
  3277. default_block = body;
  3278. continue;
  3279. }
  3280. lbBlock *next_cond = nullptr;
  3281. for_array(j, cc->list) {
  3282. Ast *expr = unparen_expr(cc->list[j]);
  3283. next_cond = lb_create_block(p, "switch.case.next");
  3284. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3285. if (is_ast_range(expr)) {
  3286. ast_node(ie, BinaryExpr, expr);
  3287. TokenKind op = Token_Invalid;
  3288. switch (ie->op.kind) {
  3289. case Token_Ellipsis: op = Token_LtEq; break;
  3290. case Token_RangeHalf: op = Token_Lt; break;
  3291. default: GB_PANIC("Invalid interval operator"); break;
  3292. }
  3293. lbValue lhs = lb_build_expr(p, ie->left);
  3294. lbValue rhs = lb_build_expr(p, ie->right);
  3295. // TODO(bill): do short circuit here
  3296. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3297. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3298. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3299. } else {
  3300. if (expr->tav.mode == Addressing_Type) {
  3301. GB_ASSERT(is_type_typeid(tag.type));
  3302. lbValue e = lb_typeid(p->module, expr->tav.type);
  3303. e = lb_emit_conv(p, e, tag.type);
  3304. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3305. } else {
  3306. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3307. }
  3308. }
  3309. lb_emit_if(p, cond, body, next_cond);
  3310. lb_start_block(p, next_cond);
  3311. }
  3312. lb_start_block(p, body);
  3313. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3314. lb_open_scope(p);
  3315. lb_build_stmt_list(p, cc->stmts);
  3316. lb_close_scope(p, lbDeferExit_Default, body);
  3317. lb_pop_target_list(p);
  3318. lb_emit_jump(p, done);
  3319. lb_start_block(p, next_cond);
  3320. }
  3321. if (default_block != nullptr) {
  3322. lb_emit_jump(p, default_block);
  3323. lb_start_block(p, default_block);
  3324. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3325. lb_open_scope(p);
  3326. lb_build_stmt_list(p, default_stmts);
  3327. lb_close_scope(p, lbDeferExit_Default, default_block);
  3328. lb_pop_target_list(p);
  3329. }
  3330. lb_emit_jump(p, done);
  3331. lb_start_block(p, done);
  3332. }
  3333. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3334. Entity *e = implicit_entity_of_node(clause);
  3335. GB_ASSERT(e != nullptr);
  3336. if (e->flags & EntityFlag_Value) {
  3337. // by value
  3338. GB_ASSERT(are_types_identical(e->type, value.type));
  3339. lbAddr x = lb_add_local(p, e->type, e, false);
  3340. lb_addr_store(p, x, value);
  3341. } else {
  3342. // by reference
  3343. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3344. lb_add_entity(p->module, e, value);
  3345. }
  3346. }
  3347. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3348. Entity *e = entity_of_node(stmt_val);
  3349. if (e == nullptr) {
  3350. return {};
  3351. }
  3352. if ((e->flags & EntityFlag_Value) == 0) {
  3353. if (LLVMIsALoadInst(value.value)) {
  3354. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3355. lb_add_entity(p->module, e, ptr);
  3356. return lb_addr(ptr);
  3357. }
  3358. }
  3359. // by value
  3360. lbAddr addr = lb_add_local(p, e->type, e, false);
  3361. lb_addr_store(p, addr, value);
  3362. return addr;
  3363. }
  3364. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3365. ast_node(cc, CaseClause, clause);
  3366. lb_push_target_list(p, label, done, nullptr, nullptr);
  3367. lb_open_scope(p);
  3368. lb_build_stmt_list(p, cc->stmts);
  3369. lb_close_scope(p, lbDeferExit_Default, body);
  3370. lb_pop_target_list(p);
  3371. lb_emit_jump(p, done);
  3372. }
  3373. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3374. lbModule *m = p->module;
  3375. ast_node(as, AssignStmt, ss->tag);
  3376. GB_ASSERT(as->lhs.count == 1);
  3377. GB_ASSERT(as->rhs.count == 1);
  3378. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3379. bool is_parent_ptr = is_type_pointer(parent.type);
  3380. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3381. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3382. lbValue parent_value = parent;
  3383. lbValue parent_ptr = parent;
  3384. if (!is_parent_ptr) {
  3385. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3386. }
  3387. lbValue tag_index = {};
  3388. lbValue union_data = {};
  3389. if (switch_kind == TypeSwitch_Union) {
  3390. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3391. tag_index = lb_emit_load(p, tag_ptr);
  3392. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3393. }
  3394. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3395. lb_emit_jump(p, start_block);
  3396. lb_start_block(p, start_block);
  3397. // NOTE(bill): Append this later
  3398. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3399. Ast *default_ = nullptr;
  3400. ast_node(body, BlockStmt, ss->body);
  3401. gb_local_persist i32 weird_count = 0;
  3402. for_array(i, body->stmts) {
  3403. Ast *clause = body->stmts[i];
  3404. ast_node(cc, CaseClause, clause);
  3405. if (cc->list.count == 0) {
  3406. default_ = clause;
  3407. continue;
  3408. }
  3409. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3410. lbBlock *next = nullptr;
  3411. Type *case_type = nullptr;
  3412. for_array(type_index, cc->list) {
  3413. next = lb_create_block(p, "typeswitch.next");
  3414. case_type = type_of_expr(cc->list[type_index]);
  3415. lbValue cond = {};
  3416. if (switch_kind == TypeSwitch_Union) {
  3417. Type *ut = base_type(type_deref(parent.type));
  3418. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3419. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3420. } else if (switch_kind == TypeSwitch_Any) {
  3421. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3422. lbValue case_typeid = lb_typeid(m, case_type);
  3423. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3424. }
  3425. GB_ASSERT(cond.value != nullptr);
  3426. lb_emit_if(p, cond, body, next);
  3427. lb_start_block(p, next);
  3428. }
  3429. Entity *case_entity = implicit_entity_of_node(clause);
  3430. lbValue value = parent_value;
  3431. lb_start_block(p, body);
  3432. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3433. if (cc->list.count == 1) {
  3434. lbValue data = {};
  3435. if (switch_kind == TypeSwitch_Union) {
  3436. data = union_data;
  3437. } else if (switch_kind == TypeSwitch_Any) {
  3438. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3439. data = any_data;
  3440. }
  3441. Type *ct = case_entity->type;
  3442. Type *ct_ptr = alloc_type_pointer(ct);
  3443. value = lb_emit_conv(p, data, ct_ptr);
  3444. if (!by_reference) {
  3445. value = lb_emit_load(p, value);
  3446. }
  3447. }
  3448. lb_store_type_case_implicit(p, clause, value);
  3449. lb_type_case_body(p, ss->label, clause, body, done);
  3450. lb_start_block(p, next);
  3451. }
  3452. if (default_ != nullptr) {
  3453. lb_store_type_case_implicit(p, default_, parent_value);
  3454. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3455. } else {
  3456. lb_emit_jump(p, done);
  3457. }
  3458. lb_start_block(p, done);
  3459. }
  3460. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3461. lbModule *m = p->module;
  3462. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3463. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3464. type = default_type(type);
  3465. lbValue short_circuit = {};
  3466. if (op == Token_CmpAnd) {
  3467. lb_build_cond(p, left, rhs, done);
  3468. short_circuit = lb_const_bool(m, type, false);
  3469. } else if (op == Token_CmpOr) {
  3470. lb_build_cond(p, left, done, rhs);
  3471. short_circuit = lb_const_bool(m, type, true);
  3472. }
  3473. if (rhs->preds.count == 0) {
  3474. lb_start_block(p, done);
  3475. return short_circuit;
  3476. }
  3477. if (done->preds.count == 0) {
  3478. lb_start_block(p, rhs);
  3479. return lb_build_expr(p, right);
  3480. }
  3481. Array<LLVMValueRef> incoming_values = {};
  3482. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3483. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3484. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3485. for_array(i, done->preds) {
  3486. incoming_values[i] = short_circuit.value;
  3487. incoming_blocks[i] = done->preds[i]->block;
  3488. }
  3489. lb_start_block(p, rhs);
  3490. lbValue edge = lb_build_expr(p, right);
  3491. incoming_values[done->preds.count] = edge.value;
  3492. incoming_blocks[done->preds.count] = p->curr_block->block;
  3493. lb_emit_jump(p, done);
  3494. lb_start_block(p, done);
  3495. lbValue res = {};
  3496. res.type = type;
  3497. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3498. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3499. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3500. return res;
  3501. }
  3502. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3503. Ast *prev_stmt = p->curr_stmt;
  3504. defer (p->curr_stmt = prev_stmt);
  3505. p->curr_stmt = node;
  3506. if (p->curr_block != nullptr) {
  3507. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3508. if (lb_is_instr_terminating(last_instr)) {
  3509. return;
  3510. }
  3511. }
  3512. u64 prev_state_flags = p->module->state_flags;
  3513. defer (p->module->state_flags = prev_state_flags);
  3514. if (node->state_flags != 0) {
  3515. u64 in = node->state_flags;
  3516. u64 out = p->module->state_flags;
  3517. if (in & StateFlag_bounds_check) {
  3518. out |= StateFlag_bounds_check;
  3519. out &= ~StateFlag_no_bounds_check;
  3520. } else if (in & StateFlag_no_bounds_check) {
  3521. out |= StateFlag_no_bounds_check;
  3522. out &= ~StateFlag_bounds_check;
  3523. }
  3524. p->module->state_flags = out;
  3525. }
  3526. switch (node->kind) {
  3527. case_ast_node(bs, EmptyStmt, node);
  3528. case_end;
  3529. case_ast_node(us, UsingStmt, node);
  3530. case_end;
  3531. case_ast_node(ws, WhenStmt, node);
  3532. lb_build_when_stmt(p, ws);
  3533. case_end;
  3534. case_ast_node(bs, BlockStmt, node);
  3535. if (bs->label != nullptr) {
  3536. lbBlock *done = lb_create_block(p, "block.done");
  3537. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3538. tl->is_block = true;
  3539. lb_open_scope(p);
  3540. lb_build_stmt_list(p, bs->stmts);
  3541. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3542. lb_emit_jump(p, done);
  3543. lb_start_block(p, done);
  3544. } else {
  3545. lb_open_scope(p);
  3546. lb_build_stmt_list(p, bs->stmts);
  3547. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3548. }
  3549. case_end;
  3550. case_ast_node(vd, ValueDecl, node);
  3551. if (!vd->is_mutable) {
  3552. return;
  3553. }
  3554. bool is_static = false;
  3555. if (vd->names.count > 0) {
  3556. Entity *e = entity_of_node(vd->names[0]);
  3557. if (e->flags & EntityFlag_Static) {
  3558. // NOTE(bill): If one of the entities is static, they all are
  3559. is_static = true;
  3560. }
  3561. }
  3562. if (is_static) {
  3563. for_array(i, vd->names) {
  3564. lbValue value = {};
  3565. if (vd->values.count > 0) {
  3566. GB_ASSERT(vd->names.count == vd->values.count);
  3567. Ast *ast_value = vd->values[i];
  3568. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3569. ast_value->tav.mode == Addressing_Invalid);
  3570. bool allow_local = false;
  3571. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3572. }
  3573. Ast *ident = vd->names[i];
  3574. GB_ASSERT(!is_blank_ident(ident));
  3575. Entity *e = entity_of_node(ident);
  3576. GB_ASSERT(e->flags & EntityFlag_Static);
  3577. String name = e->token.string;
  3578. String mangled_name = {};
  3579. {
  3580. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  3581. str = gb_string_appendc(str, "-");
  3582. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3583. mangled_name.text = cast(u8 *)str;
  3584. mangled_name.len = gb_string_length(str);
  3585. }
  3586. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  3587. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3588. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3589. if (value.value != nullptr) {
  3590. LLVMSetInitializer(global, value.value);
  3591. } else {
  3592. }
  3593. if (e->Variable.thread_local_model != "") {
  3594. LLVMSetThreadLocal(global, true);
  3595. String m = e->Variable.thread_local_model;
  3596. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3597. if (m == "default") {
  3598. mode = LLVMGeneralDynamicTLSModel;
  3599. } else if (m == "localdynamic") {
  3600. mode = LLVMLocalDynamicTLSModel;
  3601. } else if (m == "initialexec") {
  3602. mode = LLVMInitialExecTLSModel;
  3603. } else if (m == "localexec") {
  3604. mode = LLVMLocalExecTLSModel;
  3605. } else {
  3606. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3607. }
  3608. LLVMSetThreadLocalMode(global, mode);
  3609. } else {
  3610. LLVMSetLinkage(global, LLVMInternalLinkage);
  3611. }
  3612. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3613. lb_add_entity(p->module, e, global_val);
  3614. lb_add_member(p->module, mangled_name, global_val);
  3615. }
  3616. return;
  3617. }
  3618. if (vd->values.count == 0) { // declared and zero-initialized
  3619. for_array(i, vd->names) {
  3620. Ast *name = vd->names[i];
  3621. if (!is_blank_ident(name)) {
  3622. Entity *e = entity_of_node(name);
  3623. lb_add_local(p, e->type, e, true);
  3624. }
  3625. }
  3626. } else { // Tuple(s)
  3627. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  3628. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  3629. for_array(i, vd->names) {
  3630. Ast *name = vd->names[i];
  3631. lbAddr lval = {};
  3632. if (!is_blank_ident(name)) {
  3633. Entity *e = entity_of_node(name);
  3634. lval = lb_add_local(p, e->type, e, false);
  3635. }
  3636. array_add(&lvals, lval);
  3637. }
  3638. for_array(i, vd->values) {
  3639. lbValue init = lb_build_expr(p, vd->values[i]);
  3640. Type *t = init.type;
  3641. if (t->kind == Type_Tuple) {
  3642. for_array(i, t->Tuple.variables) {
  3643. Entity *e = t->Tuple.variables[i];
  3644. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3645. array_add(&inits, v);
  3646. }
  3647. } else {
  3648. array_add(&inits, init);
  3649. }
  3650. }
  3651. for_array(i, inits) {
  3652. lbAddr lval = lvals[i];
  3653. lbValue init = inits[i];
  3654. lb_addr_store(p, lval, init);
  3655. }
  3656. }
  3657. case_end;
  3658. case_ast_node(as, AssignStmt, node);
  3659. if (as->op.kind == Token_Eq) {
  3660. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  3661. for_array(i, as->lhs) {
  3662. Ast *lhs = as->lhs[i];
  3663. lbAddr lval = {};
  3664. if (!is_blank_ident(lhs)) {
  3665. lval = lb_build_addr(p, lhs);
  3666. }
  3667. array_add(&lvals, lval);
  3668. }
  3669. if (as->lhs.count == as->rhs.count) {
  3670. if (as->lhs.count == 1) {
  3671. lbAddr lval = lvals[0];
  3672. Ast *rhs = as->rhs[0];
  3673. lbValue init = lb_build_expr(p, rhs);
  3674. lb_addr_store(p, lvals[0], init);
  3675. } else {
  3676. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3677. for_array(i, as->rhs) {
  3678. lbValue init = lb_build_expr(p, as->rhs[i]);
  3679. array_add(&inits, init);
  3680. }
  3681. for_array(i, inits) {
  3682. lbAddr lval = lvals[i];
  3683. lbValue init = inits[i];
  3684. lb_addr_store(p, lval, init);
  3685. }
  3686. }
  3687. } else {
  3688. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3689. for_array(i, as->rhs) {
  3690. lbValue init = lb_build_expr(p, as->rhs[i]);
  3691. Type *t = init.type;
  3692. // TODO(bill): refactor for code reuse as this is repeated a bit
  3693. if (t->kind == Type_Tuple) {
  3694. for_array(i, t->Tuple.variables) {
  3695. Entity *e = t->Tuple.variables[i];
  3696. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3697. array_add(&inits, v);
  3698. }
  3699. } else {
  3700. array_add(&inits, init);
  3701. }
  3702. }
  3703. for_array(i, inits) {
  3704. lbAddr lval = lvals[i];
  3705. lbValue init = inits[i];
  3706. lb_addr_store(p, lval, init);
  3707. }
  3708. }
  3709. } else {
  3710. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  3711. // +=, -=, etc
  3712. i32 op = cast(i32)as->op.kind;
  3713. op += Token_Add - Token_AddEq; // Convert += to +
  3714. if (op == Token_CmpAnd || op == Token_CmpOr) {
  3715. Type *type = as->lhs[0]->tav.type;
  3716. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  3717. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3718. lb_addr_store(p, lhs, new_value);
  3719. } else {
  3720. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3721. lbValue value = lb_build_expr(p, as->rhs[0]);
  3722. lbValue old_value = lb_addr_load(p, lhs);
  3723. Type *type = old_value.type;
  3724. lbValue change = lb_emit_conv(p, value, type);
  3725. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  3726. lb_addr_store(p, lhs, new_value);
  3727. }
  3728. return;
  3729. }
  3730. case_end;
  3731. case_ast_node(es, ExprStmt, node);
  3732. lb_build_expr(p, es->expr);
  3733. case_end;
  3734. case_ast_node(ds, DeferStmt, node);
  3735. isize scope_index = p->scope_index;
  3736. lb_add_defer_node(p, scope_index, ds->stmt);
  3737. case_end;
  3738. case_ast_node(rs, ReturnStmt, node);
  3739. lbValue res = {};
  3740. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  3741. isize return_count = p->type->Proc.result_count;
  3742. isize res_count = rs->results.count;
  3743. if (return_count == 0) {
  3744. // No return values
  3745. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3746. LLVMBuildRetVoid(p->builder);
  3747. return;
  3748. } else if (return_count == 1) {
  3749. Entity *e = tuple->variables[0];
  3750. if (res_count == 0) {
  3751. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3752. GB_ASSERT(found);
  3753. res = lb_emit_load(p, *found);
  3754. } else {
  3755. res = lb_build_expr(p, rs->results[0]);
  3756. res = lb_emit_conv(p, res, e->type);
  3757. }
  3758. if (p->type->Proc.has_named_results) {
  3759. // NOTE(bill): store the named values before returning
  3760. if (e->token.string != "") {
  3761. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3762. GB_ASSERT(found != nullptr);
  3763. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  3764. }
  3765. }
  3766. } else {
  3767. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  3768. if (res_count != 0) {
  3769. for (isize res_index = 0; res_index < res_count; res_index++) {
  3770. lbValue res = lb_build_expr(p, rs->results[res_index]);
  3771. Type *t = res.type;
  3772. if (t->kind == Type_Tuple) {
  3773. for_array(i, t->Tuple.variables) {
  3774. Entity *e = t->Tuple.variables[i];
  3775. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  3776. array_add(&results, v);
  3777. }
  3778. } else {
  3779. array_add(&results, res);
  3780. }
  3781. }
  3782. } else {
  3783. for (isize res_index = 0; res_index < return_count; res_index++) {
  3784. Entity *e = tuple->variables[res_index];
  3785. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3786. GB_ASSERT(found);
  3787. lbValue res = lb_emit_load(p, *found);
  3788. array_add(&results, res);
  3789. }
  3790. }
  3791. GB_ASSERT(results.count == return_count);
  3792. if (p->type->Proc.has_named_results) {
  3793. // NOTE(bill): store the named values before returning
  3794. for_array(i, p->type->Proc.results->Tuple.variables) {
  3795. Entity *e = p->type->Proc.results->Tuple.variables[i];
  3796. if (e->kind != Entity_Variable) {
  3797. continue;
  3798. }
  3799. if (e->token.string == "") {
  3800. continue;
  3801. }
  3802. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3803. GB_ASSERT(found != nullptr);
  3804. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  3805. }
  3806. }
  3807. Type *ret_type = p->type->Proc.results;
  3808. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3809. res = lb_add_local_generated(p, ret_type, false).addr;
  3810. for_array(i, results) {
  3811. Entity *e = tuple->variables[i];
  3812. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  3813. lbValue val = lb_emit_conv(p, results[i], e->type);
  3814. lb_emit_store(p, field, val);
  3815. }
  3816. res = lb_emit_load(p, res);
  3817. }
  3818. if (p->abi_function_type) {
  3819. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  3820. if (res.value != nullptr) {
  3821. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  3822. } else {
  3823. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  3824. }
  3825. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3826. LLVMBuildRetVoid(p->builder);
  3827. } else {
  3828. LLVMValueRef ret_val = res.value;
  3829. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  3830. if (p->abi_function_type->ret.cast_type != nullptr) {
  3831. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  3832. }
  3833. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3834. LLVMBuildRet(p->builder, ret_val);
  3835. }
  3836. } else {
  3837. GB_ASSERT(!USE_LLVM_ABI);
  3838. if (p->type->Proc.return_by_pointer) {
  3839. if (res.value != nullptr) {
  3840. lb_addr_store(p, p->return_ptr, res);
  3841. } else {
  3842. lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type));
  3843. }
  3844. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3845. LLVMBuildRetVoid(p->builder);
  3846. } else {
  3847. GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name));
  3848. Type *abi_rt = p->type->Proc.abi_compat_result_type;
  3849. if (!are_types_identical(res.type, abi_rt)) {
  3850. res = lb_emit_transmute(p, res, abi_rt);
  3851. }
  3852. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3853. LLVMBuildRet(p->builder, res.value);
  3854. }
  3855. }
  3856. case_end;
  3857. case_ast_node(is, IfStmt, node);
  3858. lb_open_scope(p); // Scope #1
  3859. if (is->init != nullptr) {
  3860. // TODO(bill): Should this have a separate block to begin with?
  3861. #if 1
  3862. lbBlock *init = lb_create_block(p, "if.init");
  3863. lb_emit_jump(p, init);
  3864. lb_start_block(p, init);
  3865. #endif
  3866. lb_build_stmt(p, is->init);
  3867. }
  3868. lbBlock *then = lb_create_block(p, "if.then");
  3869. lbBlock *done = lb_create_block(p, "if.done");
  3870. lbBlock *else_ = done;
  3871. if (is->else_stmt != nullptr) {
  3872. else_ = lb_create_block(p, "if.else");
  3873. }
  3874. lb_build_cond(p, is->cond, then, else_);
  3875. lb_start_block(p, then);
  3876. if (is->label != nullptr) {
  3877. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  3878. tl->is_block = true;
  3879. }
  3880. lb_build_stmt(p, is->body);
  3881. lb_emit_jump(p, done);
  3882. if (is->else_stmt != nullptr) {
  3883. lb_start_block(p, else_);
  3884. lb_open_scope(p);
  3885. lb_build_stmt(p, is->else_stmt);
  3886. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3887. lb_emit_jump(p, done);
  3888. }
  3889. lb_start_block(p, done);
  3890. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3891. case_end;
  3892. case_ast_node(fs, ForStmt, node);
  3893. lb_open_scope(p); // Open Scope here
  3894. if (fs->init != nullptr) {
  3895. #if 1
  3896. lbBlock *init = lb_create_block(p, "for.init");
  3897. lb_emit_jump(p, init);
  3898. lb_start_block(p, init);
  3899. #endif
  3900. lb_build_stmt(p, fs->init);
  3901. }
  3902. lbBlock *body = lb_create_block(p, "for.body");
  3903. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  3904. lbBlock *loop = body;
  3905. if (fs->cond != nullptr) {
  3906. loop = lb_create_block(p, "for.loop");
  3907. }
  3908. lbBlock *post = loop;
  3909. if (fs->post != nullptr) {
  3910. post = lb_create_block(p, "for.post");
  3911. }
  3912. lb_emit_jump(p, loop);
  3913. lb_start_block(p, loop);
  3914. if (loop != body) {
  3915. lb_build_cond(p, fs->cond, body, done);
  3916. lb_start_block(p, body);
  3917. }
  3918. lb_push_target_list(p, fs->label, done, post, nullptr);
  3919. lb_build_stmt(p, fs->body);
  3920. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3921. lb_pop_target_list(p);
  3922. lb_emit_jump(p, post);
  3923. if (fs->post != nullptr) {
  3924. lb_start_block(p, post);
  3925. lb_build_stmt(p, fs->post);
  3926. lb_emit_jump(p, loop);
  3927. }
  3928. lb_start_block(p, done);
  3929. case_end;
  3930. case_ast_node(rs, RangeStmt, node);
  3931. lb_build_range_stmt(p, rs);
  3932. case_end;
  3933. case_ast_node(rs, InlineRangeStmt, node);
  3934. lb_build_inline_range_stmt(p, rs);
  3935. case_end;
  3936. case_ast_node(ss, SwitchStmt, node);
  3937. lb_build_switch_stmt(p, ss);
  3938. case_end;
  3939. case_ast_node(ss, TypeSwitchStmt, node);
  3940. lb_build_type_switch_stmt(p, ss);
  3941. case_end;
  3942. case_ast_node(bs, BranchStmt, node);
  3943. lbBlock *block = nullptr;
  3944. if (bs->label != nullptr) {
  3945. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  3946. switch (bs->token.kind) {
  3947. case Token_break: block = bb.break_; break;
  3948. case Token_continue: block = bb.continue_; break;
  3949. case Token_fallthrough:
  3950. GB_PANIC("fallthrough cannot have a label");
  3951. break;
  3952. }
  3953. } else {
  3954. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  3955. if (t->is_block) {
  3956. continue;
  3957. }
  3958. switch (bs->token.kind) {
  3959. case Token_break: block = t->break_; break;
  3960. case Token_continue: block = t->continue_; break;
  3961. case Token_fallthrough: block = t->fallthrough_; break;
  3962. }
  3963. }
  3964. }
  3965. if (block != nullptr) {
  3966. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  3967. }
  3968. lb_emit_jump(p, block);
  3969. case_end;
  3970. }
  3971. }
  3972. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  3973. cond = lb_emit_conv(p, cond, t_llvm_bool);
  3974. lbValue res = {};
  3975. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  3976. res.type = x.type;
  3977. return res;
  3978. }
  3979. lbValue lb_const_nil(lbModule *m, Type *type) {
  3980. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  3981. return lbValue{v, type};
  3982. }
  3983. lbValue lb_const_undef(lbModule *m, Type *type) {
  3984. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  3985. return lbValue{v, type};
  3986. }
  3987. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  3988. lbValue res = {};
  3989. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  3990. res.type = type;
  3991. return res;
  3992. }
  3993. lbValue lb_const_string(lbModule *m, String const &value) {
  3994. return lb_const_value(m, t_string, exact_value_string(value));
  3995. }
  3996. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  3997. lbValue res = {};
  3998. res.value = LLVMConstInt(lb_type(m, type), value, false);
  3999. res.type = type;
  4000. return res;
  4001. }
  4002. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  4003. GB_ASSERT(type_size_of(type) == 4);
  4004. u32 u = bit_cast<u32>(f);
  4005. if (is_type_different_to_arch_endianness(type)) {
  4006. u = gb_endian_swap32(u);
  4007. }
  4008. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  4009. return LLVMConstBitCast(i, lb_type(m, type));
  4010. }
  4011. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4012. x = lb_emit_conv(p, x, t);
  4013. y = lb_emit_conv(p, y, t);
  4014. if (is_type_float(t)) {
  4015. i64 sz = 8*type_size_of(t);
  4016. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4017. args[0] = x;
  4018. args[1] = y;
  4019. switch (sz) {
  4020. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  4021. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  4022. }
  4023. GB_PANIC("Unknown float type");
  4024. }
  4025. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  4026. }
  4027. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  4028. x = lb_emit_conv(p, x, t);
  4029. y = lb_emit_conv(p, y, t);
  4030. if (is_type_float(t)) {
  4031. i64 sz = 8*type_size_of(t);
  4032. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4033. args[0] = x;
  4034. args[1] = y;
  4035. switch (sz) {
  4036. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  4037. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  4038. }
  4039. GB_PANIC("Unknown float type");
  4040. }
  4041. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  4042. }
  4043. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  4044. lbValue z = {};
  4045. z = lb_emit_max(p, t, x, min);
  4046. z = lb_emit_min(p, t, z, max);
  4047. return z;
  4048. }
  4049. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  4050. StringHashKey key = string_hash_string(str);
  4051. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  4052. if (found != nullptr) {
  4053. return *found;
  4054. } else {
  4055. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4056. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4057. cast(char const *)str.text,
  4058. cast(unsigned)str.len,
  4059. false);
  4060. isize max_len = 7+8+1;
  4061. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  4062. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4063. len -= 1;
  4064. m->global_array_index++;
  4065. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4066. LLVMSetInitializer(global_data, data);
  4067. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4068. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4069. string_map_set(&m->const_strings, key, ptr);
  4070. return ptr;
  4071. }
  4072. }
  4073. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  4074. LLVMValueRef ptr = nullptr;
  4075. if (str.len != 0) {
  4076. ptr = lb_find_or_add_entity_string_ptr(m, str);
  4077. } else {
  4078. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4079. }
  4080. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4081. LLVMValueRef values[2] = {ptr, str_len};
  4082. lbValue res = {};
  4083. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  4084. res.type = t_string;
  4085. return res;
  4086. }
  4087. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  4088. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4089. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  4090. cast(char const *)str.text,
  4091. cast(unsigned)str.len,
  4092. false);
  4093. char *name = nullptr;
  4094. {
  4095. isize max_len = 7+8+1;
  4096. name = gb_alloc_array(permanent_allocator(), char, max_len);
  4097. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  4098. len -= 1;
  4099. m->global_array_index++;
  4100. }
  4101. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  4102. LLVMSetInitializer(global_data, data);
  4103. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  4104. LLVMValueRef ptr = nullptr;
  4105. if (str.len != 0) {
  4106. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  4107. } else {
  4108. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4109. }
  4110. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  4111. LLVMValueRef values[2] = {ptr, len};
  4112. lbValue res = {};
  4113. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  4114. res.type = t_u8_slice;
  4115. return res;
  4116. }
  4117. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  4118. isize index = type_info_index(info, type, false);
  4119. if (index >= 0) {
  4120. auto *set = &info->minimum_dependency_type_info_set;
  4121. for_array(i, set->entries) {
  4122. if (set->entries[i].ptr == index) {
  4123. return i+1;
  4124. }
  4125. }
  4126. }
  4127. if (err_on_not_found) {
  4128. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  4129. }
  4130. return -1;
  4131. }
  4132. lbValue lb_typeid(lbModule *m, Type *type) {
  4133. type = default_type(type);
  4134. u64 id = cast(u64)lb_type_info_index(m->info, type);
  4135. GB_ASSERT(id >= 0);
  4136. u64 kind = Typeid_Invalid;
  4137. u64 named = is_type_named(type) && type->kind != Type_Basic;
  4138. u64 special = 0;
  4139. u64 reserved = 0;
  4140. Type *bt = base_type(type);
  4141. TypeKind tk = bt->kind;
  4142. switch (tk) {
  4143. case Type_Basic: {
  4144. u32 flags = bt->Basic.flags;
  4145. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  4146. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  4147. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  4148. if (flags & BasicFlag_Float) kind = Typeid_Float;
  4149. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  4150. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  4151. if (flags & BasicFlag_String) kind = Typeid_String;
  4152. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  4153. } break;
  4154. case Type_Pointer: kind = Typeid_Pointer; break;
  4155. case Type_Array: kind = Typeid_Array; break;
  4156. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  4157. case Type_Slice: kind = Typeid_Slice; break;
  4158. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  4159. case Type_Map: kind = Typeid_Map; break;
  4160. case Type_Struct: kind = Typeid_Struct; break;
  4161. case Type_Enum: kind = Typeid_Enum; break;
  4162. case Type_Union: kind = Typeid_Union; break;
  4163. case Type_Tuple: kind = Typeid_Tuple; break;
  4164. case Type_Proc: kind = Typeid_Procedure; break;
  4165. case Type_BitField: kind = Typeid_Bit_Field; break;
  4166. case Type_BitSet: kind = Typeid_Bit_Set; break;
  4167. case Type_Opaque: kind = Typeid_Opaque; break;
  4168. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  4169. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  4170. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  4171. }
  4172. if (is_type_cstring(type)) {
  4173. special = 1;
  4174. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  4175. special = 1;
  4176. }
  4177. u64 data = 0;
  4178. if (build_context.word_size == 4) {
  4179. GB_ASSERT(id <= (1u<<24u));
  4180. data |= (id &~ (1u<<24)) << 0u; // index
  4181. data |= (kind &~ (1u<<5)) << 24u; // kind
  4182. data |= (named &~ (1u<<1)) << 29u; // kind
  4183. data |= (special &~ (1u<<1)) << 30u; // kind
  4184. data |= (reserved &~ (1u<<1)) << 31u; // kind
  4185. } else {
  4186. GB_ASSERT(build_context.word_size == 8);
  4187. GB_ASSERT(id <= (1ull<<56u));
  4188. data |= (id &~ (1ull<<56)) << 0ul; // index
  4189. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  4190. data |= (named &~ (1ull<<1)) << 61ull; // kind
  4191. data |= (special &~ (1ull<<1)) << 62ull; // kind
  4192. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  4193. }
  4194. lbValue res = {};
  4195. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  4196. res.type = t_typeid;
  4197. return res;
  4198. }
  4199. lbValue lb_type_info(lbModule *m, Type *type) {
  4200. type = default_type(type);
  4201. isize index = lb_type_info_index(m->info, type);
  4202. GB_ASSERT(index >= 0);
  4203. LLVMTypeRef it = lb_type(m, t_int);
  4204. LLVMValueRef indices[2] = {
  4205. LLVMConstInt(it, 0, false),
  4206. LLVMConstInt(it, index, true),
  4207. };
  4208. lbValue value = {};
  4209. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  4210. value.type = t_type_info_ptr;
  4211. return value;
  4212. }
  4213. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  4214. LLVMContextRef ctx = m->ctx;
  4215. type = default_type(type);
  4216. Type *original_type = type;
  4217. lbValue res = {};
  4218. res.type = original_type;
  4219. type = core_type(type);
  4220. value = convert_exact_value_for_type(value, type);
  4221. if (value.kind == ExactValue_Typeid) {
  4222. return lb_typeid(m, value.value_typeid);
  4223. }
  4224. if (value.kind == ExactValue_Invalid) {
  4225. return lb_const_nil(m, type);
  4226. }
  4227. if (value.kind == ExactValue_Procedure) {
  4228. Ast *expr = unparen_expr(value.value_procedure);
  4229. if (expr->kind == Ast_ProcLit) {
  4230. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4231. }
  4232. Entity *e = entity_from_expr(expr);
  4233. e = strip_entity_wrapping(e);
  4234. GB_ASSERT(e != nullptr);
  4235. auto *found = map_get(&m->values, hash_entity(e));
  4236. if (found) {
  4237. return *found;
  4238. }
  4239. GB_PANIC("Error in: %.*s(%td:%td), missing procedure %.*s\n", LIT(e->token.pos.file), e->token.pos.line, e->token.pos.column, LIT(e->token.string));
  4240. }
  4241. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4242. if (is_type_slice(type)) {
  4243. if (value.kind == ExactValue_String) {
  4244. GB_ASSERT(is_type_u8_slice(type));
  4245. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4246. return res;
  4247. } else {
  4248. ast_node(cl, CompoundLit, value.value_compound);
  4249. isize count = cl->elems.count;
  4250. if (count == 0) {
  4251. return lb_const_nil(m, type);
  4252. }
  4253. count = gb_max(cl->max_count, count);
  4254. Type *elem = base_type(type)->Slice.elem;
  4255. Type *t = alloc_type_array(elem, count);
  4256. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4257. LLVMValueRef array_data = nullptr;
  4258. if (allow_local && m->curr_procedure != nullptr) {
  4259. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4260. // its backing data on the stack
  4261. lbProcedure *p = m->curr_procedure;
  4262. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4263. LLVMTypeRef llvm_type = lb_type(m, t);
  4264. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4265. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4266. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4267. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4268. {
  4269. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4270. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4271. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4272. lbAddr slice = lb_add_local_generated(p, type, false);
  4273. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4274. return lb_addr_load(p, slice);
  4275. }
  4276. } else {
  4277. isize max_len = 7+8+1;
  4278. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4279. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4280. m->global_array_index++;
  4281. String name = make_string(cast(u8 *)str, len-1);
  4282. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4283. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4284. LLVMSetInitializer(array_data, backing_array.value);
  4285. lbValue g = {};
  4286. g.value = array_data;
  4287. g.type = t;
  4288. lb_add_entity(m, e, g);
  4289. lb_add_member(m, name, g);
  4290. {
  4291. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4292. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4293. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4294. LLVMValueRef values[2] = {ptr, len};
  4295. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4296. return res;
  4297. }
  4298. }
  4299. }
  4300. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4301. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4302. i64 count = type->Array.count;
  4303. Type *elem = type->Array.elem;
  4304. LLVMTypeRef et = lb_type(m, elem);
  4305. Rune rune;
  4306. isize offset = 0;
  4307. isize width = 1;
  4308. String s = value.value_string;
  4309. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4310. for (i64 i = 0; i < count && offset < s.len; i++) {
  4311. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4312. offset += width;
  4313. elems[i] = LLVMConstInt(et, rune, true);
  4314. }
  4315. GB_ASSERT(offset == s.len);
  4316. res.value = LLVMConstArray(et, elems, cast(unsigned)count);
  4317. return res;
  4318. }
  4319. GB_PANIC("HERE!\n");
  4320. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4321. cast(char const *)value.value_string.text,
  4322. cast(unsigned)value.value_string.len,
  4323. false /*DontNullTerminate*/);
  4324. res.value = data;
  4325. return res;
  4326. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4327. GB_ASSERT(type->Array.count == value.value_string.len);
  4328. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4329. cast(char const *)value.value_string.text,
  4330. cast(unsigned)value.value_string.len,
  4331. true /*DontNullTerminate*/);
  4332. res.value = data;
  4333. return res;
  4334. } else if (is_type_array(type) &&
  4335. value.kind != ExactValue_Invalid &&
  4336. value.kind != ExactValue_String &&
  4337. value.kind != ExactValue_Compound) {
  4338. i64 count = type->Array.count;
  4339. Type *elem = type->Array.elem;
  4340. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4341. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4342. for (i64 i = 0; i < count; i++) {
  4343. elems[i] = single_elem.value;
  4344. }
  4345. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  4346. return res;
  4347. }
  4348. switch (value.kind) {
  4349. case ExactValue_Invalid:
  4350. res.value = LLVMConstNull(lb_type(m, original_type));
  4351. return res;
  4352. case ExactValue_Bool:
  4353. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4354. return res;
  4355. case ExactValue_String:
  4356. {
  4357. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4358. lbValue res = {};
  4359. res.type = default_type(original_type);
  4360. if (is_type_cstring(res.type)) {
  4361. res.value = ptr;
  4362. } else {
  4363. if (value.value_string.len == 0) {
  4364. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4365. }
  4366. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4367. LLVMValueRef values[2] = {ptr, str_len};
  4368. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4369. }
  4370. return res;
  4371. }
  4372. case ExactValue_Integer:
  4373. if (is_type_pointer(type)) {
  4374. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4375. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4376. } else {
  4377. unsigned len = cast(unsigned)value.value_integer.len;
  4378. if (len == 0) {
  4379. u64 word = 0;
  4380. res.value = LLVMConstNull(lb_type(m, original_type));
  4381. } else {
  4382. u64 *words = big_int_ptr(&value.value_integer);
  4383. if (is_type_different_to_arch_endianness(type)) {
  4384. // NOTE(bill): Swap byte order for different endianness
  4385. i64 sz = type_size_of(type);
  4386. isize byte_len = gb_size_of(u64)*len;
  4387. u8 *old_bytes = cast(u8 *)words;
  4388. // TODO(bill): Use a different allocator here for a temporary allocation
  4389. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4390. for (i64 i = 0; i < sz; i++) {
  4391. new_bytes[i] = old_bytes[sz-1-i];
  4392. }
  4393. words = cast(u64 *)new_bytes;
  4394. }
  4395. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4396. if (value.value_integer.neg) {
  4397. res.value = LLVMConstNeg(res.value);
  4398. }
  4399. }
  4400. }
  4401. return res;
  4402. case ExactValue_Float:
  4403. if (type_size_of(type) == 4) {
  4404. f32 f = cast(f32)value.value_float;
  4405. res.value = lb_const_f32(m, f, type);
  4406. return res;
  4407. }
  4408. if (is_type_different_to_arch_endianness(type)) {
  4409. u64 u = bit_cast<u64>(value.value_float);
  4410. u = gb_endian_swap64(u);
  4411. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4412. } else {
  4413. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4414. }
  4415. return res;
  4416. case ExactValue_Complex:
  4417. {
  4418. LLVMValueRef values[2] = {};
  4419. switch (8*type_size_of(type)) {
  4420. case 64:
  4421. values[0] = lb_const_f32(m, cast(f32)value.value_complex.real);
  4422. values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag);
  4423. break;
  4424. case 128:
  4425. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real);
  4426. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag);
  4427. break;
  4428. }
  4429. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4430. return res;
  4431. }
  4432. break;
  4433. case ExactValue_Quaternion:
  4434. {
  4435. LLVMValueRef values[4] = {};
  4436. switch (8*type_size_of(type)) {
  4437. case 128:
  4438. // @QuaternionLayout
  4439. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real);
  4440. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag);
  4441. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag);
  4442. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag);
  4443. break;
  4444. case 256:
  4445. // @QuaternionLayout
  4446. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real);
  4447. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag);
  4448. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag);
  4449. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag);
  4450. break;
  4451. }
  4452. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  4453. return res;
  4454. }
  4455. break;
  4456. case ExactValue_Pointer:
  4457. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4458. return res;
  4459. case ExactValue_Compound:
  4460. if (is_type_slice(type)) {
  4461. return lb_const_value(m, type, value, allow_local);
  4462. } else if (is_type_array(type)) {
  4463. ast_node(cl, CompoundLit, value.value_compound);
  4464. Type *elem_type = type->Array.elem;
  4465. isize elem_count = cl->elems.count;
  4466. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4467. return lb_const_nil(m, original_type);
  4468. }
  4469. if (cl->elems[0]->kind == Ast_FieldValue) {
  4470. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4471. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4472. isize value_index = 0;
  4473. for (i64 i = 0; i < type->Array.count; i++) {
  4474. bool found = false;
  4475. for (isize j = 0; j < elem_count; j++) {
  4476. Ast *elem = cl->elems[j];
  4477. ast_node(fv, FieldValue, elem);
  4478. if (is_ast_range(fv->field)) {
  4479. ast_node(ie, BinaryExpr, fv->field);
  4480. TypeAndValue lo_tav = ie->left->tav;
  4481. TypeAndValue hi_tav = ie->right->tav;
  4482. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4483. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4484. TokenKind op = ie->op.kind;
  4485. i64 lo = exact_value_to_i64(lo_tav.value);
  4486. i64 hi = exact_value_to_i64(hi_tav.value);
  4487. if (op == Token_Ellipsis) {
  4488. hi += 1;
  4489. }
  4490. if (lo == i) {
  4491. TypeAndValue tav = fv->value->tav;
  4492. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4493. for (i64 k = lo; k < hi; k++) {
  4494. values[value_index++] = val;
  4495. }
  4496. found = true;
  4497. i += (hi-lo-1);
  4498. break;
  4499. }
  4500. } else {
  4501. TypeAndValue index_tav = fv->field->tav;
  4502. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4503. i64 index = exact_value_to_i64(index_tav.value);
  4504. if (index == i) {
  4505. TypeAndValue tav = fv->value->tav;
  4506. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4507. values[value_index++] = val;
  4508. found = true;
  4509. break;
  4510. }
  4511. }
  4512. }
  4513. if (!found) {
  4514. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4515. }
  4516. }
  4517. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4518. return res;
  4519. } else {
  4520. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4521. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4522. for (isize i = 0; i < elem_count; i++) {
  4523. TypeAndValue tav = cl->elems[i]->tav;
  4524. GB_ASSERT(tav.mode != Addressing_Invalid);
  4525. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4526. }
  4527. for (isize i = elem_count; i < type->Array.count; i++) {
  4528. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4529. }
  4530. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count);
  4531. return res;
  4532. }
  4533. } else if (is_type_enumerated_array(type)) {
  4534. ast_node(cl, CompoundLit, value.value_compound);
  4535. Type *elem_type = type->EnumeratedArray.elem;
  4536. isize elem_count = cl->elems.count;
  4537. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4538. return lb_const_nil(m, original_type);
  4539. }
  4540. if (cl->elems[0]->kind == Ast_FieldValue) {
  4541. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4542. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4543. isize value_index = 0;
  4544. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4545. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4546. for (i64 i = total_lo; i <= total_hi; i++) {
  4547. bool found = false;
  4548. for (isize j = 0; j < elem_count; j++) {
  4549. Ast *elem = cl->elems[j];
  4550. ast_node(fv, FieldValue, elem);
  4551. if (is_ast_range(fv->field)) {
  4552. ast_node(ie, BinaryExpr, fv->field);
  4553. TypeAndValue lo_tav = ie->left->tav;
  4554. TypeAndValue hi_tav = ie->right->tav;
  4555. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4556. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4557. TokenKind op = ie->op.kind;
  4558. i64 lo = exact_value_to_i64(lo_tav.value);
  4559. i64 hi = exact_value_to_i64(hi_tav.value);
  4560. if (op == Token_Ellipsis) {
  4561. hi += 1;
  4562. }
  4563. if (lo == i) {
  4564. TypeAndValue tav = fv->value->tav;
  4565. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4566. for (i64 k = lo; k < hi; k++) {
  4567. values[value_index++] = val;
  4568. }
  4569. found = true;
  4570. i += (hi-lo-1);
  4571. break;
  4572. }
  4573. } else {
  4574. TypeAndValue index_tav = fv->field->tav;
  4575. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4576. i64 index = exact_value_to_i64(index_tav.value);
  4577. if (index == i) {
  4578. TypeAndValue tav = fv->value->tav;
  4579. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4580. values[value_index++] = val;
  4581. found = true;
  4582. break;
  4583. }
  4584. }
  4585. }
  4586. if (!found) {
  4587. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4588. }
  4589. }
  4590. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4591. return res;
  4592. } else {
  4593. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4594. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4595. for (isize i = 0; i < elem_count; i++) {
  4596. TypeAndValue tav = cl->elems[i]->tav;
  4597. GB_ASSERT(tav.mode != Addressing_Invalid);
  4598. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4599. }
  4600. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4601. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4602. }
  4603. res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count);
  4604. return res;
  4605. }
  4606. } else if (is_type_simd_vector(type)) {
  4607. ast_node(cl, CompoundLit, value.value_compound);
  4608. Type *elem_type = type->SimdVector.elem;
  4609. isize elem_count = cl->elems.count;
  4610. if (elem_count == 0) {
  4611. return lb_const_nil(m, original_type);
  4612. }
  4613. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4614. isize total_elem_count = type->SimdVector.count;
  4615. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  4616. for (isize i = 0; i < elem_count; i++) {
  4617. TypeAndValue tav = cl->elems[i]->tav;
  4618. GB_ASSERT(tav.mode != Addressing_Invalid);
  4619. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4620. }
  4621. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4622. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4623. }
  4624. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4625. return res;
  4626. } else if (is_type_struct(type)) {
  4627. ast_node(cl, CompoundLit, value.value_compound);
  4628. if (cl->elems.count == 0) {
  4629. return lb_const_nil(m, original_type);
  4630. }
  4631. isize offset = 0;
  4632. if (type->Struct.custom_align > 0) {
  4633. offset = 1;
  4634. }
  4635. isize value_count = type->Struct.fields.count + offset;
  4636. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  4637. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  4638. if (cl->elems.count > 0) {
  4639. if (cl->elems[0]->kind == Ast_FieldValue) {
  4640. isize elem_count = cl->elems.count;
  4641. for (isize i = 0; i < elem_count; i++) {
  4642. ast_node(fv, FieldValue, cl->elems[i]);
  4643. String name = fv->field->Ident.token.string;
  4644. TypeAndValue tav = fv->value->tav;
  4645. GB_ASSERT(tav.mode != Addressing_Invalid);
  4646. Selection sel = lookup_field(type, name, false);
  4647. Entity *f = type->Struct.fields[sel.index[0]];
  4648. if (elem_type_can_be_constant(f->type)) {
  4649. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  4650. visited[offset+f->Variable.field_index] = true;
  4651. }
  4652. }
  4653. } else {
  4654. for_array(i, cl->elems) {
  4655. Entity *f = type->Struct.fields[i];
  4656. TypeAndValue tav = cl->elems[i]->tav;
  4657. ExactValue val = {};
  4658. if (tav.mode != Addressing_Invalid) {
  4659. val = tav.value;
  4660. }
  4661. if (elem_type_can_be_constant(f->type)) {
  4662. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  4663. visited[offset+f->Variable.field_index] = true;
  4664. }
  4665. }
  4666. }
  4667. }
  4668. for (isize i = 0; i < type->Struct.fields.count; i++) {
  4669. if (!visited[offset+i]) {
  4670. GB_ASSERT(values[offset+i] == nullptr);
  4671. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  4672. }
  4673. }
  4674. if (type->Struct.custom_align > 0) {
  4675. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  4676. }
  4677. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  4678. return res;
  4679. } else if (is_type_bit_set(type)) {
  4680. ast_node(cl, CompoundLit, value.value_compound);
  4681. if (cl->elems.count == 0) {
  4682. return lb_const_nil(m, original_type);
  4683. }
  4684. i64 sz = type_size_of(type);
  4685. if (sz == 0) {
  4686. return lb_const_nil(m, original_type);
  4687. }
  4688. u64 bits = 0;
  4689. for_array(i, cl->elems) {
  4690. Ast *e = cl->elems[i];
  4691. GB_ASSERT(e->kind != Ast_FieldValue);
  4692. TypeAndValue tav = e->tav;
  4693. if (tav.mode != Addressing_Constant) {
  4694. continue;
  4695. }
  4696. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  4697. i64 v = big_int_to_i64(&tav.value.value_integer);
  4698. i64 lower = type->BitSet.lower;
  4699. bits |= 1ull<<cast(u64)(v-lower);
  4700. }
  4701. if (is_type_different_to_arch_endianness(type)) {
  4702. i64 size = type_size_of(type);
  4703. switch (size) {
  4704. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  4705. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  4706. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  4707. }
  4708. }
  4709. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  4710. return res;
  4711. } else {
  4712. return lb_const_nil(m, original_type);
  4713. }
  4714. break;
  4715. case ExactValue_Procedure:
  4716. {
  4717. Ast *expr = value.value_procedure;
  4718. GB_ASSERT(expr != nullptr);
  4719. if (expr->kind == Ast_ProcLit) {
  4720. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4721. }
  4722. }
  4723. break;
  4724. case ExactValue_Typeid:
  4725. return lb_typeid(m, value.value_typeid);
  4726. }
  4727. return lb_const_nil(m, original_type);
  4728. }
  4729. u64 lb_generate_source_code_location_hash(TokenPos const &pos) {
  4730. u64 h = 0xcbf29ce484222325;
  4731. for (isize i = 0; i < pos.file.len; i++) {
  4732. h = (h ^ u64(pos.file[i])) * 0x100000001b3;
  4733. }
  4734. h = h ^ (u64(pos.line) * 0x100000001b3);
  4735. h = h ^ (u64(pos.column) * 0x100000001b3);
  4736. return h;
  4737. }
  4738. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  4739. lbModule *m = p->module;
  4740. LLVMValueRef fields[5] = {};
  4741. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  4742. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  4743. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  4744. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  4745. fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value;
  4746. lbValue res = {};
  4747. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5);
  4748. res.type = t_source_code_location;
  4749. return res;
  4750. }
  4751. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  4752. String proc_name = {};
  4753. if (p->entity) {
  4754. proc_name = p->entity->token.string;
  4755. }
  4756. TokenPos pos = {};
  4757. if (node) {
  4758. pos = ast_token(node).pos;
  4759. }
  4760. return lb_emit_source_code_location(p, proc_name, pos);
  4761. }
  4762. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  4763. switch (op) {
  4764. case Token_Add:
  4765. return x;
  4766. case Token_Not: // Boolean not
  4767. case Token_Xor: // Bitwise not
  4768. case Token_Sub: // Number negation
  4769. break;
  4770. case Token_Pointer:
  4771. GB_PANIC("This should be handled elsewhere");
  4772. break;
  4773. }
  4774. if (is_type_array(x.type)) {
  4775. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  4776. Type *tl = base_type(x.type);
  4777. lbValue val = lb_address_from_load_or_generate_local(p, x);
  4778. GB_ASSERT(is_type_array(type));
  4779. Type *elem_type = base_array_type(type);
  4780. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4781. lbAddr res_addr = lb_add_local_generated(p, type, false);
  4782. lbValue res = lb_addr_get_ptr(p, res_addr);
  4783. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4784. i32 count = cast(i32)tl->Array.count;
  4785. if (inline_array_arith) {
  4786. // inline
  4787. for (i32 i = 0; i < count; i++) {
  4788. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  4789. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4790. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  4791. }
  4792. } else {
  4793. auto loop_data = lb_loop_start(p, count, t_i32);
  4794. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  4795. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4796. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  4797. lb_loop_end(p, loop_data);
  4798. }
  4799. return lb_emit_load(p, res);
  4800. }
  4801. if (op == Token_Xor) {
  4802. lbValue cmp = {};
  4803. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  4804. cmp.type = x.type;
  4805. return lb_emit_conv(p, cmp, type);
  4806. }
  4807. if (op == Token_Not) {
  4808. lbValue cmp = {};
  4809. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  4810. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  4811. cmp.type = t_llvm_bool;
  4812. return lb_emit_conv(p, cmp, type);
  4813. }
  4814. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4815. Type *platform_type = integer_endian_type_to_platform_type(type);
  4816. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4817. lbValue res = {};
  4818. res.value = LLVMBuildNeg(p->builder, v.value, "");
  4819. res.type = platform_type;
  4820. return lb_emit_byte_swap(p, res, type);
  4821. }
  4822. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4823. Type *platform_type = integer_endian_type_to_platform_type(type);
  4824. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4825. lbValue res = {};
  4826. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  4827. res.type = platform_type;
  4828. return lb_emit_byte_swap(p, res, type);
  4829. }
  4830. lbValue res = {};
  4831. switch (op) {
  4832. case Token_Not: // Boolean not
  4833. case Token_Xor: // Bitwise not
  4834. res.value = LLVMBuildNot(p->builder, x.value, "");
  4835. res.type = x.type;
  4836. return res;
  4837. case Token_Sub: // Number negation
  4838. if (is_type_integer(x.type)) {
  4839. res.value = LLVMBuildNeg(p->builder, x.value, "");
  4840. } else if (is_type_float(x.type)) {
  4841. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  4842. } else if (is_type_complex(x.type)) {
  4843. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4844. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4845. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4846. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4847. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4848. return lb_addr_load(p, addr);
  4849. } else if (is_type_quaternion(x.type)) {
  4850. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4851. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4852. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  4853. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  4854. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4855. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4856. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4857. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  4858. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  4859. return lb_addr_load(p, addr);
  4860. } else {
  4861. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  4862. }
  4863. res.type = x.type;
  4864. return res;
  4865. }
  4866. return res;
  4867. }
  4868. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  4869. lbModule *m = p->module;
  4870. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  4871. lhs = lb_emit_conv(p, lhs, type);
  4872. rhs = lb_emit_conv(p, rhs, type);
  4873. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  4874. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4875. GB_ASSERT(is_type_array(type));
  4876. Type *elem_type = base_array_type(type);
  4877. lbAddr res = lb_add_local_generated(p, type, false);
  4878. i64 count = base_type(type)->Array.count;
  4879. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4880. if (inline_array_arith) {
  4881. for (i64 i = 0; i < count; i++) {
  4882. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  4883. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  4884. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  4885. lbValue a = lb_emit_load(p, a_ptr);
  4886. lbValue b = lb_emit_load(p, b_ptr);
  4887. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4888. lb_emit_store(p, dst_ptr, c);
  4889. }
  4890. } else {
  4891. auto loop_data = lb_loop_start(p, count, t_i32);
  4892. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  4893. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  4894. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  4895. lbValue a = lb_emit_load(p, a_ptr);
  4896. lbValue b = lb_emit_load(p, b_ptr);
  4897. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4898. lb_emit_store(p, dst_ptr, c);
  4899. lb_loop_end(p, loop_data);
  4900. }
  4901. return lb_addr_load(p, res);
  4902. } else if (is_type_complex(type)) {
  4903. lhs = lb_emit_conv(p, lhs, type);
  4904. rhs = lb_emit_conv(p, rhs, type);
  4905. Type *ft = base_complex_elem_type(type);
  4906. if (op == Token_Quo) {
  4907. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4908. args[0] = lhs;
  4909. args[1] = rhs;
  4910. switch (type_size_of(ft)) {
  4911. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  4912. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  4913. default: GB_PANIC("Unknown float type"); break;
  4914. }
  4915. }
  4916. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4917. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  4918. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  4919. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  4920. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  4921. lbValue real = {};
  4922. lbValue imag = {};
  4923. switch (op) {
  4924. case Token_Add:
  4925. real = lb_emit_arith(p, Token_Add, a, c, ft);
  4926. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  4927. break;
  4928. case Token_Sub:
  4929. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  4930. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  4931. break;
  4932. case Token_Mul: {
  4933. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  4934. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  4935. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  4936. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  4937. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  4938. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  4939. break;
  4940. }
  4941. }
  4942. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  4943. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  4944. return lb_addr_load(p, res);
  4945. } else if (is_type_quaternion(type)) {
  4946. lhs = lb_emit_conv(p, lhs, type);
  4947. rhs = lb_emit_conv(p, rhs, type);
  4948. Type *ft = base_complex_elem_type(type);
  4949. if (op == Token_Add || op == Token_Sub) {
  4950. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4951. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  4952. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  4953. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  4954. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  4955. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  4956. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  4957. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  4958. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  4959. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  4960. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  4961. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  4962. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  4963. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  4964. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  4965. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  4966. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  4967. return lb_addr_load(p, res);
  4968. } else if (op == Token_Mul) {
  4969. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4970. args[0] = lhs;
  4971. args[1] = rhs;
  4972. switch (8*type_size_of(ft)) {
  4973. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  4974. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  4975. default: GB_PANIC("Unknown float type"); break;
  4976. }
  4977. } else if (op == Token_Quo) {
  4978. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4979. args[0] = lhs;
  4980. args[1] = rhs;
  4981. switch (8*type_size_of(ft)) {
  4982. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  4983. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  4984. default: GB_PANIC("Unknown float type"); break;
  4985. }
  4986. }
  4987. }
  4988. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4989. switch (op) {
  4990. case Token_AndNot:
  4991. case Token_And:
  4992. case Token_Or:
  4993. case Token_Xor:
  4994. goto handle_op;
  4995. }
  4996. Type *platform_type = integer_endian_type_to_platform_type(type);
  4997. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4998. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4999. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5000. return lb_emit_byte_swap(p, res, type);
  5001. }
  5002. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  5003. Type *platform_type = integer_endian_type_to_platform_type(type);
  5004. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  5005. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  5006. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  5007. return lb_emit_byte_swap(p, res, type);
  5008. }
  5009. handle_op:
  5010. lhs = lb_emit_conv(p, lhs, type);
  5011. rhs = lb_emit_conv(p, rhs, type);
  5012. lbValue res = {};
  5013. res.type = type;
  5014. switch (op) {
  5015. case Token_Add:
  5016. if (is_type_float(type)) {
  5017. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  5018. return res;
  5019. }
  5020. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  5021. return res;
  5022. case Token_Sub:
  5023. if (is_type_float(type)) {
  5024. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  5025. return res;
  5026. }
  5027. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  5028. return res;
  5029. case Token_Mul:
  5030. if (is_type_float(type)) {
  5031. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  5032. return res;
  5033. }
  5034. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  5035. return res;
  5036. case Token_Quo:
  5037. if (is_type_float(type)) {
  5038. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  5039. return res;
  5040. } else if (is_type_unsigned(type)) {
  5041. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  5042. return res;
  5043. }
  5044. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  5045. return res;
  5046. case Token_Mod:
  5047. if (is_type_float(type)) {
  5048. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  5049. return res;
  5050. } else if (is_type_unsigned(type)) {
  5051. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5052. return res;
  5053. }
  5054. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5055. return res;
  5056. case Token_ModMod:
  5057. if (is_type_unsigned(type)) {
  5058. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  5059. return res;
  5060. } else {
  5061. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  5062. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  5063. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  5064. res.value = c;
  5065. return res;
  5066. }
  5067. case Token_And:
  5068. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  5069. return res;
  5070. case Token_Or:
  5071. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  5072. return res;
  5073. case Token_Xor:
  5074. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  5075. return res;
  5076. case Token_Shl:
  5077. {
  5078. rhs = lb_emit_conv(p, rhs, lhs.type);
  5079. LLVMValueRef lhsval = lhs.value;
  5080. LLVMValueRef bits = rhs.value;
  5081. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  5082. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  5083. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  5084. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  5085. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  5086. return res;
  5087. }
  5088. case Token_Shr:
  5089. {
  5090. rhs = lb_emit_conv(p, rhs, lhs.type);
  5091. LLVMValueRef lhsval = lhs.value;
  5092. LLVMValueRef bits = rhs.value;
  5093. bool is_unsigned = is_type_unsigned(type);
  5094. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  5095. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  5096. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  5097. if (is_unsigned) {
  5098. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  5099. } else {
  5100. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  5101. }
  5102. return res;
  5103. }
  5104. case Token_AndNot:
  5105. {
  5106. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  5107. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  5108. return res;
  5109. }
  5110. break;
  5111. }
  5112. GB_PANIC("unhandled operator of lb_emit_arith");
  5113. return {};
  5114. }
  5115. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  5116. ast_node(be, BinaryExpr, expr);
  5117. TypeAndValue tv = type_and_value_of_expr(expr);
  5118. switch (be->op.kind) {
  5119. case Token_Add:
  5120. case Token_Sub:
  5121. case Token_Mul:
  5122. case Token_Quo:
  5123. case Token_Mod:
  5124. case Token_ModMod:
  5125. case Token_And:
  5126. case Token_Or:
  5127. case Token_Xor:
  5128. case Token_AndNot:
  5129. case Token_Shl:
  5130. case Token_Shr: {
  5131. Type *type = default_type(tv.type);
  5132. lbValue left = lb_build_expr(p, be->left);
  5133. lbValue right = lb_build_expr(p, be->right);
  5134. return lb_emit_arith(p, be->op.kind, left, right, type);
  5135. }
  5136. case Token_CmpEq:
  5137. case Token_NotEq:
  5138. case Token_Lt:
  5139. case Token_LtEq:
  5140. case Token_Gt:
  5141. case Token_GtEq:
  5142. {
  5143. lbValue left = {};
  5144. lbValue right = {};
  5145. if (be->left->tav.mode == Addressing_Type) {
  5146. left = lb_typeid(p->module, be->left->tav.type);
  5147. }
  5148. if (be->right->tav.mode == Addressing_Type) {
  5149. right = lb_typeid(p->module, be->right->tav.type);
  5150. }
  5151. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  5152. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  5153. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  5154. Type *type = default_type(tv.type);
  5155. return lb_emit_conv(p, cmp, type);
  5156. }
  5157. case Token_CmpAnd:
  5158. case Token_CmpOr:
  5159. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  5160. case Token_in:
  5161. case Token_not_in:
  5162. {
  5163. lbValue left = lb_build_expr(p, be->left);
  5164. Type *type = default_type(tv.type);
  5165. lbValue right = lb_build_expr(p, be->right);
  5166. Type *rt = base_type(right.type);
  5167. switch (rt->kind) {
  5168. case Type_Map:
  5169. {
  5170. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  5171. lbValue h = lb_gen_map_header(p, addr, rt);
  5172. lbValue key = lb_gen_map_key(p, left, rt->Map.key);
  5173. auto args = array_make<lbValue>(permanent_allocator(), 2);
  5174. args[0] = h;
  5175. args[1] = key;
  5176. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  5177. if (be->op.kind == Token_in) {
  5178. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  5179. } else {
  5180. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  5181. }
  5182. }
  5183. break;
  5184. case Type_BitSet:
  5185. {
  5186. Type *key_type = rt->BitSet.elem;
  5187. GB_ASSERT(are_types_identical(left.type, key_type));
  5188. Type *it = bit_set_to_int(rt);
  5189. left = lb_emit_conv(p, left, it);
  5190. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  5191. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  5192. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  5193. bit = lb_emit_conv(p, bit, it);
  5194. lbValue old_value = lb_emit_transmute(p, right, it);
  5195. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  5196. if (be->op.kind == Token_in) {
  5197. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5198. } else {
  5199. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  5200. }
  5201. }
  5202. break;
  5203. default:
  5204. GB_PANIC("Invalid 'in' type");
  5205. }
  5206. break;
  5207. }
  5208. break;
  5209. default:
  5210. GB_PANIC("Invalid binary expression");
  5211. break;
  5212. }
  5213. return {};
  5214. }
  5215. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  5216. Type *prev_src = src;
  5217. // Type *prev_dst = dst;
  5218. src = base_type(type_deref(src));
  5219. // dst = base_type(type_deref(dst));
  5220. bool src_is_ptr = src != prev_src;
  5221. // bool dst_is_ptr = dst != prev_dst;
  5222. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  5223. for_array(i, src->Struct.fields) {
  5224. Entity *f = src->Struct.fields[i];
  5225. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  5226. if (are_types_identical(dst, f->type)) {
  5227. return f->token.string;
  5228. }
  5229. if (src_is_ptr && is_type_pointer(dst)) {
  5230. if (are_types_identical(type_deref(dst), f->type)) {
  5231. return f->token.string;
  5232. }
  5233. }
  5234. if (is_type_struct(f->type)) {
  5235. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5236. if (name.len > 0) {
  5237. return name;
  5238. }
  5239. }
  5240. }
  5241. }
  5242. return str_lit("");
  5243. }
  5244. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5245. GB_ASSERT(is_type_pointer(value.type));
  5246. GB_ASSERT(is_type_pointer(t));
  5247. GB_ASSERT(lb_is_const(value));
  5248. lbValue res = {};
  5249. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5250. res.type = t;
  5251. return res;
  5252. }
  5253. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5254. lbModule *m = p->module;
  5255. t = reduce_tuple_to_single_type(t);
  5256. Type *src_type = value.type;
  5257. if (are_types_identical(t, src_type)) {
  5258. return value;
  5259. }
  5260. Type *src = core_type(src_type);
  5261. Type *dst = core_type(t);
  5262. GB_ASSERT(src != nullptr);
  5263. GB_ASSERT(dst != nullptr);
  5264. if (is_type_untyped_nil(src)) {
  5265. return lb_const_nil(m, t);
  5266. }
  5267. if (is_type_untyped_undef(src)) {
  5268. return lb_const_undef(m, t);
  5269. }
  5270. if (LLVMIsConstant(value.value)) {
  5271. if (is_type_any(dst)) {
  5272. Type *st = default_type(src_type);
  5273. lbAddr default_value = lb_add_local_generated(p, st, false);
  5274. lb_addr_store(p, default_value, value);
  5275. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5276. lbValue id = lb_typeid(m, st);
  5277. lbAddr res = lb_add_local_generated(p, t, false);
  5278. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5279. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5280. lb_emit_store(p, a0, data);
  5281. lb_emit_store(p, a1, id);
  5282. return lb_addr_load(p, res);
  5283. } else if (dst->kind == Type_Basic) {
  5284. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5285. String str = lb_get_const_string(m, value);
  5286. lbValue res = {};
  5287. res.type = t;
  5288. res.value = llvm_cstring(m, str);
  5289. return res;
  5290. }
  5291. // if (is_type_float(dst)) {
  5292. // return value;
  5293. // } else if (is_type_integer(dst)) {
  5294. // return value;
  5295. // }
  5296. // ExactValue ev = value->Constant.value;
  5297. // if (is_type_float(dst)) {
  5298. // ev = exact_value_to_float(ev);
  5299. // } else if (is_type_complex(dst)) {
  5300. // ev = exact_value_to_complex(ev);
  5301. // } else if (is_type_quaternion(dst)) {
  5302. // ev = exact_value_to_quaternion(ev);
  5303. // } else if (is_type_string(dst)) {
  5304. // // Handled elsewhere
  5305. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5306. // } else if (is_type_integer(dst)) {
  5307. // ev = exact_value_to_integer(ev);
  5308. // } else if (is_type_pointer(dst)) {
  5309. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5310. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5311. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5312. // }
  5313. // return lb_const_value(p->module, t, ev);
  5314. }
  5315. }
  5316. if (are_types_identical(src, dst)) {
  5317. if (!are_types_identical(src_type, t)) {
  5318. return lb_emit_transmute(p, value, t);
  5319. }
  5320. return value;
  5321. }
  5322. // bool <-> llvm bool
  5323. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5324. lbValue res = {};
  5325. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5326. res.type = dst;
  5327. return res;
  5328. }
  5329. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5330. lbValue res = {};
  5331. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5332. res.type = dst;
  5333. return res;
  5334. }
  5335. // integer -> integer
  5336. if (is_type_integer(src) && is_type_integer(dst)) {
  5337. GB_ASSERT(src->kind == Type_Basic &&
  5338. dst->kind == Type_Basic);
  5339. i64 sz = type_size_of(default_type(src));
  5340. i64 dz = type_size_of(default_type(dst));
  5341. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5342. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5343. value = lb_emit_byte_swap(p, value, platform_src_type);
  5344. }
  5345. LLVMOpcode op = LLVMTrunc;
  5346. if (dz < sz) {
  5347. op = LLVMTrunc;
  5348. } else if (dz == sz) {
  5349. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5350. // NOTE(bill): Copy the value just for type correctness
  5351. op = LLVMBitCast;
  5352. } else if (dz > sz) {
  5353. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5354. }
  5355. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5356. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5357. lbValue res = {};
  5358. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5359. res.type = t;
  5360. return lb_emit_byte_swap(p, res, t);
  5361. } else {
  5362. lbValue res = {};
  5363. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5364. res.type = t;
  5365. return res;
  5366. }
  5367. }
  5368. // boolean -> boolean/integer
  5369. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5370. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5371. lbValue res = {};
  5372. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5373. res.type = t;
  5374. return res;
  5375. }
  5376. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5377. return lb_emit_transmute(p, value, dst);
  5378. }
  5379. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5380. return lb_emit_transmute(p, value, dst);
  5381. }
  5382. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5383. return lb_emit_transmute(p, value, dst);
  5384. }
  5385. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5386. return lb_emit_transmute(p, value, dst);
  5387. }
  5388. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5389. lbValue c = lb_emit_conv(p, value, t_cstring);
  5390. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5391. args[0] = c;
  5392. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5393. return lb_emit_conv(p, s, dst);
  5394. }
  5395. // integer -> boolean
  5396. if (is_type_integer(src) && is_type_boolean(dst)) {
  5397. lbValue res = {};
  5398. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5399. res.type = t_llvm_bool;
  5400. return lb_emit_conv(p, res, t);
  5401. }
  5402. // float -> float
  5403. if (is_type_float(src) && is_type_float(dst)) {
  5404. i64 sz = type_size_of(src);
  5405. i64 dz = type_size_of(dst);
  5406. if (dz == sz) {
  5407. if (types_have_same_internal_endian(src, dst)) {
  5408. lbValue res = {};
  5409. res.type = t;
  5410. res.value = value.value;
  5411. return res;
  5412. } else {
  5413. return lb_emit_byte_swap(p, value, t);
  5414. }
  5415. }
  5416. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5417. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5418. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5419. lbValue res = {};
  5420. res = lb_emit_conv(p, value, platform_src_type);
  5421. res = lb_emit_conv(p, res, platform_dst_type);
  5422. if (is_type_different_to_arch_endianness(dst)) {
  5423. res = lb_emit_byte_swap(p, res, t);
  5424. }
  5425. return lb_emit_conv(p, res, t);
  5426. }
  5427. lbValue res = {};
  5428. res.type = t;
  5429. if (dz >= sz) {
  5430. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5431. } else {
  5432. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5433. }
  5434. return res;
  5435. }
  5436. if (is_type_complex(src) && is_type_complex(dst)) {
  5437. Type *ft = base_complex_elem_type(dst);
  5438. lbAddr gen = lb_add_local_generated(p, dst, false);
  5439. lbValue gp = lb_addr_get_ptr(p, gen);
  5440. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5441. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5442. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5443. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5444. return lb_addr_load(p, gen);
  5445. }
  5446. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5447. // @QuaternionLayout
  5448. Type *ft = base_complex_elem_type(dst);
  5449. lbAddr gen = lb_add_local_generated(p, dst, false);
  5450. lbValue gp = lb_addr_get_ptr(p, gen);
  5451. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5452. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5453. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5454. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5455. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5456. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5457. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5458. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5459. return lb_addr_load(p, gen);
  5460. }
  5461. if (is_type_float(src) && is_type_complex(dst)) {
  5462. Type *ft = base_complex_elem_type(dst);
  5463. lbAddr gen = lb_add_local_generated(p, dst, true);
  5464. lbValue gp = lb_addr_get_ptr(p, gen);
  5465. lbValue real = lb_emit_conv(p, value, ft);
  5466. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5467. return lb_addr_load(p, gen);
  5468. }
  5469. if (is_type_float(src) && is_type_quaternion(dst)) {
  5470. Type *ft = base_complex_elem_type(dst);
  5471. lbAddr gen = lb_add_local_generated(p, dst, true);
  5472. lbValue gp = lb_addr_get_ptr(p, gen);
  5473. lbValue real = lb_emit_conv(p, value, ft);
  5474. // @QuaternionLayout
  5475. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5476. return lb_addr_load(p, gen);
  5477. }
  5478. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5479. Type *ft = base_complex_elem_type(dst);
  5480. lbAddr gen = lb_add_local_generated(p, dst, true);
  5481. lbValue gp = lb_addr_get_ptr(p, gen);
  5482. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5483. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5484. // @QuaternionLayout
  5485. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5486. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5487. return lb_addr_load(p, gen);
  5488. }
  5489. // float <-> integer
  5490. if (is_type_float(src) && is_type_integer(dst)) {
  5491. lbValue res = {};
  5492. res.type = t;
  5493. if (is_type_unsigned(dst)) {
  5494. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5495. } else {
  5496. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5497. }
  5498. return res;
  5499. }
  5500. if (is_type_integer(src) && is_type_float(dst)) {
  5501. lbValue res = {};
  5502. res.type = t;
  5503. if (is_type_unsigned(src)) {
  5504. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5505. } else {
  5506. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5507. }
  5508. return res;
  5509. }
  5510. // Pointer <-> uintptr
  5511. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5512. lbValue res = {};
  5513. res.type = t;
  5514. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5515. return res;
  5516. }
  5517. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5518. lbValue res = {};
  5519. res.type = t;
  5520. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5521. return res;
  5522. }
  5523. #if 1
  5524. if (is_type_union(dst)) {
  5525. for_array(i, dst->Union.variants) {
  5526. Type *vt = dst->Union.variants[i];
  5527. if (are_types_identical(vt, src_type)) {
  5528. lbAddr parent = lb_add_local_generated(p, t, true);
  5529. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5530. return lb_addr_load(p, parent);
  5531. }
  5532. }
  5533. }
  5534. #endif
  5535. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5536. // subtype polymorphism casting
  5537. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5538. Type *st = type_deref(src_type);
  5539. Type *pst = st;
  5540. st = type_deref(st);
  5541. bool st_is_ptr = is_type_pointer(src_type);
  5542. st = base_type(st);
  5543. Type *dt = t;
  5544. bool dt_is_ptr = type_deref(dt) != dt;
  5545. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5546. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5547. if (field_name.len > 0) {
  5548. // NOTE(bill): It can be casted
  5549. Selection sel = lookup_field(st, field_name, false, true);
  5550. if (sel.entity != nullptr) {
  5551. if (st_is_ptr) {
  5552. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5553. Type *rt = res.type;
  5554. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5555. res = lb_emit_load(p, res);
  5556. }
  5557. return res;
  5558. } else {
  5559. if (is_type_pointer(value.type)) {
  5560. Type *rt = value.type;
  5561. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5562. value = lb_emit_load(p, value);
  5563. } else {
  5564. value = lb_emit_deep_field_gep(p, value, sel);
  5565. return lb_emit_load(p, value);
  5566. }
  5567. }
  5568. return lb_emit_deep_field_ev(p, value, sel);
  5569. }
  5570. } else {
  5571. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5572. }
  5573. }
  5574. }
  5575. // Pointer <-> Pointer
  5576. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5577. lbValue res = {};
  5578. res.type = t;
  5579. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5580. return res;
  5581. }
  5582. // proc <-> proc
  5583. if (is_type_proc(src) && is_type_proc(dst)) {
  5584. lbValue res = {};
  5585. res.type = t;
  5586. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5587. return res;
  5588. }
  5589. // pointer -> proc
  5590. if (is_type_pointer(src) && is_type_proc(dst)) {
  5591. lbValue res = {};
  5592. res.type = t;
  5593. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5594. return res;
  5595. }
  5596. // proc -> pointer
  5597. if (is_type_proc(src) && is_type_pointer(dst)) {
  5598. lbValue res = {};
  5599. res.type = t;
  5600. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5601. return res;
  5602. }
  5603. // []byte/[]u8 <-> string
  5604. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5605. return lb_emit_transmute(p, value, t);
  5606. }
  5607. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5608. return lb_emit_transmute(p, value, t);
  5609. }
  5610. if (is_type_array(dst)) {
  5611. Type *elem = dst->Array.elem;
  5612. lbValue e = lb_emit_conv(p, value, elem);
  5613. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5614. lbAddr v = lb_add_local_generated(p, t, false);
  5615. isize index_count = cast(isize)dst->Array.count;
  5616. for (isize i = 0; i < index_count; i++) {
  5617. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  5618. lb_emit_store(p, elem, e);
  5619. }
  5620. return lb_addr_load(p, v);
  5621. }
  5622. if (is_type_any(dst)) {
  5623. if (is_type_untyped_nil(src)) {
  5624. return lb_const_nil(p->module, t);
  5625. }
  5626. if (is_type_untyped_undef(src)) {
  5627. return lb_const_undef(p->module, t);
  5628. }
  5629. lbAddr result = lb_add_local_generated(p, t, true);
  5630. Type *st = default_type(src_type);
  5631. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5632. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5633. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5634. data = lb_emit_conv(p, data, t_rawptr);
  5635. lbValue id = lb_typeid(p->module, st);
  5636. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5637. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5638. lb_emit_store(p, any_data, data);
  5639. lb_emit_store(p, any_id, id);
  5640. return lb_addr_load(p, result);
  5641. }
  5642. i64 src_sz = type_size_of(src);
  5643. i64 dst_sz = type_size_of(dst);
  5644. if (src_sz == dst_sz) {
  5645. // bit_set <-> integer
  5646. if (is_type_integer(src) && is_type_bit_set(dst)) {
  5647. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  5648. res.type = dst;
  5649. return res;
  5650. }
  5651. if (is_type_bit_set(src) && is_type_integer(dst)) {
  5652. lbValue bs = value;
  5653. bs.type = bit_set_to_int(src);
  5654. return lb_emit_conv(p, bs, dst);
  5655. }
  5656. // typeid <-> integer
  5657. if (is_type_integer(src) && is_type_typeid(dst)) {
  5658. return lb_emit_transmute(p, value, dst);
  5659. }
  5660. if (is_type_typeid(src) && is_type_integer(dst)) {
  5661. return lb_emit_transmute(p, value, dst);
  5662. }
  5663. }
  5664. if (is_type_untyped(src)) {
  5665. if (is_type_string(src) && is_type_string(dst)) {
  5666. lbAddr result = lb_add_local_generated(p, t, false);
  5667. lb_addr_store(p, result, value);
  5668. return lb_addr_load(p, result);
  5669. }
  5670. }
  5671. gb_printf_err("%.*s\n", LIT(p->name));
  5672. gb_printf_err("lb_emit_conv: src -> dst\n");
  5673. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5674. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5675. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  5676. gb_printf_err("Not Identical %p != %p\n", src, dst);
  5677. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5678. type_to_string(src_type), type_to_string(t),
  5679. LIT(p->name));
  5680. return {};
  5681. }
  5682. bool lb_is_type_aggregate(Type *t) {
  5683. t = base_type(t);
  5684. switch (t->kind) {
  5685. case Type_Basic:
  5686. switch (t->Basic.kind) {
  5687. case Basic_string:
  5688. case Basic_any:
  5689. return true;
  5690. // case Basic_complex32:
  5691. case Basic_complex64:
  5692. case Basic_complex128:
  5693. case Basic_quaternion128:
  5694. case Basic_quaternion256:
  5695. return true;
  5696. }
  5697. break;
  5698. case Type_Pointer:
  5699. return false;
  5700. case Type_Array:
  5701. case Type_Slice:
  5702. case Type_Struct:
  5703. case Type_Union:
  5704. case Type_Tuple:
  5705. case Type_DynamicArray:
  5706. case Type_Map:
  5707. case Type_BitField:
  5708. case Type_SimdVector:
  5709. return true;
  5710. case Type_Named:
  5711. return lb_is_type_aggregate(t->Named.base);
  5712. }
  5713. return false;
  5714. }
  5715. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  5716. Type *src_type = value.type;
  5717. if (are_types_identical(t, src_type)) {
  5718. return value;
  5719. }
  5720. lbValue res = {};
  5721. res.type = t;
  5722. Type *src = base_type(src_type);
  5723. Type *dst = base_type(t);
  5724. lbModule *m = p->module;
  5725. i64 sz = type_size_of(src);
  5726. i64 dz = type_size_of(dst);
  5727. if (sz != dz) {
  5728. LLVMTypeRef s = lb_type(m, src);
  5729. LLVMTypeRef d = lb_type(m, dst);
  5730. i64 llvm_sz = lb_sizeof(s);
  5731. i64 llvm_dz = lb_sizeof(d);
  5732. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  5733. }
  5734. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5735. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5736. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5737. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5738. return res;
  5739. }
  5740. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5741. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5742. return res;
  5743. }
  5744. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5745. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5746. return res;
  5747. }
  5748. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5749. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5750. return res;
  5751. }
  5752. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5753. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5754. return res;
  5755. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5756. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5757. return res;
  5758. }
  5759. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5760. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  5761. return res;
  5762. }
  5763. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  5764. lbValue s = lb_address_from_load_or_generate_local(p, value);
  5765. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  5766. return lb_emit_load(p, d);
  5767. }
  5768. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  5769. // GB_PANIC("lb_emit_transmute");
  5770. return res;
  5771. }
  5772. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  5773. GB_ASSERT(addr.kind == lbAddr_Context);
  5774. GB_ASSERT(addr.ctx.sel.index.count == 0);
  5775. lbModule *m = p->module;
  5776. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5777. args[0] = addr.addr;
  5778. lb_emit_runtime_call(p, "__init_context", args);
  5779. }
  5780. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  5781. ctx.kind = lbAddr_Context;
  5782. lbContextData cd = {ctx, p->scope_index};
  5783. array_add(&p->context_stack, cd);
  5784. }
  5785. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  5786. if (p->context_stack.count > 0) {
  5787. return p->context_stack[p->context_stack.count-1].ctx;
  5788. }
  5789. Type *pt = base_type(p->type);
  5790. GB_ASSERT(pt->kind == Type_Proc);
  5791. {
  5792. lbAddr c = lb_add_local_generated(p, t_context, false);
  5793. c.kind = lbAddr_Context;
  5794. lb_emit_init_context(p, c);
  5795. lb_push_context_onto_stack(p, c);
  5796. return c;
  5797. }
  5798. }
  5799. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  5800. if (LLVMIsALoadInst(value.value)) {
  5801. lbValue res = {};
  5802. res.value = LLVMGetOperand(value.value, 0);
  5803. res.type = alloc_type_pointer(value.type);
  5804. return res;
  5805. }
  5806. GB_ASSERT(is_type_typed(value.type));
  5807. lbAddr res = lb_add_local_generated(p, value.type, false);
  5808. lb_addr_store(p, res, value);
  5809. return res.addr;
  5810. }
  5811. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  5812. if (LLVMIsALoadInst(value.value)) {
  5813. lbValue res = {};
  5814. res.value = LLVMGetOperand(value.value, 0);
  5815. res.type = alloc_type_pointer(value.type);
  5816. return res;
  5817. }
  5818. GB_PANIC("lb_address_from_load");
  5819. return {};
  5820. }
  5821. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  5822. i64 type_alignment = type_align_of(new_type);
  5823. if (alignment < type_alignment) {
  5824. alignment = type_alignment;
  5825. }
  5826. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  5827. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  5828. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  5829. lb_addr_store(p, ptr, val);
  5830. ptr.kind = lbAddr_Context;
  5831. return ptr.addr;
  5832. }
  5833. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  5834. GB_ASSERT(is_type_pointer(s.type));
  5835. Type *t = base_type(type_deref(s.type));
  5836. Type *result_type = nullptr;
  5837. if (t->kind == Type_Opaque) {
  5838. t = t->Opaque.elem;
  5839. }
  5840. if (is_type_relative_pointer(t)) {
  5841. s = lb_addr_get_ptr(p, lb_addr(s));
  5842. }
  5843. if (is_type_struct(t)) {
  5844. result_type = get_struct_field_type(t, index);
  5845. } else if (is_type_union(t)) {
  5846. GB_ASSERT(index == -1);
  5847. return lb_emit_union_tag_ptr(p, s);
  5848. } else if (is_type_tuple(t)) {
  5849. GB_ASSERT(t->Tuple.variables.count > 0);
  5850. result_type = t->Tuple.variables[index]->type;
  5851. } else if (is_type_complex(t)) {
  5852. Type *ft = base_complex_elem_type(t);
  5853. switch (index) {
  5854. case 0: result_type = ft; break;
  5855. case 1: result_type = ft; break;
  5856. }
  5857. } else if (is_type_quaternion(t)) {
  5858. Type *ft = base_complex_elem_type(t);
  5859. switch (index) {
  5860. case 0: result_type = ft; break;
  5861. case 1: result_type = ft; break;
  5862. case 2: result_type = ft; break;
  5863. case 3: result_type = ft; break;
  5864. }
  5865. } else if (is_type_slice(t)) {
  5866. switch (index) {
  5867. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5868. case 1: result_type = t_int; break;
  5869. }
  5870. } else if (is_type_string(t)) {
  5871. switch (index) {
  5872. case 0: result_type = t_u8_ptr; break;
  5873. case 1: result_type = t_int; break;
  5874. }
  5875. } else if (is_type_any(t)) {
  5876. switch (index) {
  5877. case 0: result_type = t_rawptr; break;
  5878. case 1: result_type = t_typeid; break;
  5879. }
  5880. } else if (is_type_dynamic_array(t)) {
  5881. switch (index) {
  5882. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5883. case 1: result_type = t_int; break;
  5884. case 2: result_type = t_int; break;
  5885. case 3: result_type = t_allocator; break;
  5886. }
  5887. } else if (is_type_map(t)) {
  5888. init_map_internal_types(t);
  5889. Type *itp = alloc_type_pointer(t->Map.internal_type);
  5890. s = lb_emit_transmute(p, s, itp);
  5891. Type *gst = t->Map.internal_type;
  5892. GB_ASSERT(gst->kind == Type_Struct);
  5893. switch (index) {
  5894. case 0: result_type = get_struct_field_type(gst, 0); break;
  5895. case 1: result_type = get_struct_field_type(gst, 1); break;
  5896. }
  5897. } else if (is_type_array(t)) {
  5898. return lb_emit_array_epi(p, s, index);
  5899. } else if (is_type_relative_slice(t)) {
  5900. switch (index) {
  5901. case 0: result_type = t->RelativeSlice.base_integer; break;
  5902. case 1: result_type = t->RelativeSlice.base_integer; break;
  5903. }
  5904. } else {
  5905. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  5906. }
  5907. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  5908. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5909. index += 1;
  5910. }
  5911. if (lb_is_const(s)) {
  5912. lbModule *m = p->module;
  5913. lbValue res = {};
  5914. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  5915. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5916. res.type = alloc_type_pointer(result_type);
  5917. return res;
  5918. } else {
  5919. lbValue res = {};
  5920. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  5921. res.type = alloc_type_pointer(result_type);
  5922. return res;
  5923. }
  5924. }
  5925. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  5926. if (LLVMIsALoadInst(s.value)) {
  5927. lbValue res = {};
  5928. res.value = LLVMGetOperand(s.value, 0);
  5929. res.type = alloc_type_pointer(s.type);
  5930. lbValue ptr = lb_emit_struct_ep(p, res, index);
  5931. return lb_emit_load(p, ptr);
  5932. }
  5933. Type *t = base_type(s.type);
  5934. Type *result_type = nullptr;
  5935. switch (t->kind) {
  5936. case Type_Basic:
  5937. switch (t->Basic.kind) {
  5938. case Basic_string:
  5939. switch (index) {
  5940. case 0: result_type = t_u8_ptr; break;
  5941. case 1: result_type = t_int; break;
  5942. }
  5943. break;
  5944. case Basic_any:
  5945. switch (index) {
  5946. case 0: result_type = t_rawptr; break;
  5947. case 1: result_type = t_typeid; break;
  5948. }
  5949. break;
  5950. case Basic_complex64: case Basic_complex128:
  5951. {
  5952. Type *ft = base_complex_elem_type(t);
  5953. switch (index) {
  5954. case 0: result_type = ft; break;
  5955. case 1: result_type = ft; break;
  5956. }
  5957. break;
  5958. }
  5959. case Basic_quaternion128: case Basic_quaternion256:
  5960. {
  5961. Type *ft = base_complex_elem_type(t);
  5962. switch (index) {
  5963. case 0: result_type = ft; break;
  5964. case 1: result_type = ft; break;
  5965. case 2: result_type = ft; break;
  5966. case 3: result_type = ft; break;
  5967. }
  5968. break;
  5969. }
  5970. }
  5971. break;
  5972. case Type_Struct:
  5973. result_type = get_struct_field_type(t, index);
  5974. break;
  5975. case Type_Union:
  5976. GB_ASSERT(index == -1);
  5977. // return lb_emit_union_tag_value(p, s);
  5978. GB_PANIC("lb_emit_union_tag_value");
  5979. case Type_Tuple:
  5980. GB_ASSERT(t->Tuple.variables.count > 0);
  5981. result_type = t->Tuple.variables[index]->type;
  5982. if (t->Tuple.variables.count == 1) {
  5983. return s;
  5984. }
  5985. break;
  5986. case Type_Slice:
  5987. switch (index) {
  5988. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5989. case 1: result_type = t_int; break;
  5990. }
  5991. break;
  5992. case Type_DynamicArray:
  5993. switch (index) {
  5994. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5995. case 1: result_type = t_int; break;
  5996. case 2: result_type = t_int; break;
  5997. case 3: result_type = t_allocator; break;
  5998. }
  5999. break;
  6000. case Type_Map:
  6001. {
  6002. init_map_internal_types(t);
  6003. Type *gst = t->Map.generated_struct_type;
  6004. switch (index) {
  6005. case 0: result_type = get_struct_field_type(gst, 0); break;
  6006. case 1: result_type = get_struct_field_type(gst, 1); break;
  6007. }
  6008. }
  6009. break;
  6010. case Type_Array:
  6011. result_type = t->Array.elem;
  6012. break;
  6013. default:
  6014. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  6015. break;
  6016. }
  6017. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  6018. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  6019. index += 1;
  6020. }
  6021. lbValue res = {};
  6022. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  6023. res.type = result_type;
  6024. return res;
  6025. }
  6026. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  6027. GB_ASSERT(sel.index.count > 0);
  6028. Type *type = type_deref(e.type);
  6029. for_array(i, sel.index) {
  6030. i32 index = cast(i32)sel.index[i];
  6031. if (is_type_pointer(type)) {
  6032. type = type_deref(type);
  6033. e = lb_emit_load(p, e);
  6034. }
  6035. type = core_type(type);
  6036. if (type->kind == Type_Opaque) {
  6037. type = type->Opaque.elem;
  6038. }
  6039. if (is_type_quaternion(type)) {
  6040. e = lb_emit_struct_ep(p, e, index);
  6041. } else if (is_type_raw_union(type)) {
  6042. type = get_struct_field_type(type, index);
  6043. GB_ASSERT(is_type_pointer(e.type));
  6044. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  6045. } else if (is_type_struct(type)) {
  6046. type = get_struct_field_type(type, index);
  6047. e = lb_emit_struct_ep(p, e, index);
  6048. } else if (type->kind == Type_Union) {
  6049. GB_ASSERT(index == -1);
  6050. type = t_type_info_ptr;
  6051. e = lb_emit_struct_ep(p, e, index);
  6052. } else if (type->kind == Type_Tuple) {
  6053. type = type->Tuple.variables[index]->type;
  6054. e = lb_emit_struct_ep(p, e, index);
  6055. } else if (type->kind == Type_Basic) {
  6056. switch (type->Basic.kind) {
  6057. case Basic_any: {
  6058. if (index == 0) {
  6059. type = t_rawptr;
  6060. } else if (index == 1) {
  6061. type = t_type_info_ptr;
  6062. }
  6063. e = lb_emit_struct_ep(p, e, index);
  6064. break;
  6065. }
  6066. case Basic_string:
  6067. e = lb_emit_struct_ep(p, e, index);
  6068. break;
  6069. default:
  6070. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6071. break;
  6072. }
  6073. } else if (type->kind == Type_Slice) {
  6074. e = lb_emit_struct_ep(p, e, index);
  6075. } else if (type->kind == Type_DynamicArray) {
  6076. e = lb_emit_struct_ep(p, e, index);
  6077. } else if (type->kind == Type_Array) {
  6078. e = lb_emit_array_epi(p, e, index);
  6079. } else if (type->kind == Type_Map) {
  6080. e = lb_emit_struct_ep(p, e, index);
  6081. } else if (type->kind == Type_RelativePointer) {
  6082. e = lb_emit_struct_ep(p, e, index);
  6083. } else {
  6084. GB_PANIC("un-gep-able type %s", type_to_string(type));
  6085. }
  6086. }
  6087. return e;
  6088. }
  6089. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  6090. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  6091. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  6092. return lb_emit_load(p, res);
  6093. }
  6094. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  6095. // NOTE(bill): The prev block may defer injection before it's terminator
  6096. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  6097. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  6098. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  6099. return;
  6100. }
  6101. isize prev_context_stack_count = p->context_stack.count;
  6102. defer (p->context_stack.count = prev_context_stack_count);
  6103. p->context_stack.count = d.context_stack_count;
  6104. lbBlock *b = lb_create_block(p, "defer");
  6105. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6106. lb_emit_jump(p, b);
  6107. }
  6108. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  6109. lb_emit_jump(p, b);
  6110. }
  6111. lb_start_block(p, b);
  6112. if (d.kind == lbDefer_Node) {
  6113. lb_build_stmt(p, d.stmt);
  6114. } else if (d.kind == lbDefer_Instr) {
  6115. // NOTE(bill): Need to make a new copy
  6116. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  6117. LLVMInsertIntoBuilder(p->builder, instr);
  6118. } else if (d.kind == lbDefer_Proc) {
  6119. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  6120. }
  6121. }
  6122. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  6123. isize count = p->defer_stmts.count;
  6124. isize i = count;
  6125. while (i --> 0) {
  6126. lbDefer d = p->defer_stmts[i];
  6127. isize prev_context_stack_count = p->context_stack.count;
  6128. defer (p->context_stack.count = prev_context_stack_count);
  6129. p->context_stack.count = d.context_stack_count;
  6130. if (kind == lbDeferExit_Default) {
  6131. if (p->scope_index == d.scope_index &&
  6132. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  6133. lb_build_defer_stmt(p, d);
  6134. array_pop(&p->defer_stmts);
  6135. continue;
  6136. } else {
  6137. break;
  6138. }
  6139. } else if (kind == lbDeferExit_Return) {
  6140. lb_build_defer_stmt(p, d);
  6141. } else if (kind == lbDeferExit_Branch) {
  6142. GB_ASSERT(block != nullptr);
  6143. isize lower_limit = block->scope_index;
  6144. if (lower_limit < d.scope_index) {
  6145. lb_build_defer_stmt(p, d);
  6146. }
  6147. }
  6148. }
  6149. }
  6150. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  6151. lbDefer d = {lbDefer_Node};
  6152. d.scope_index = scope_index;
  6153. d.context_stack_count = p->context_stack.count;
  6154. d.block = p->curr_block;
  6155. d.stmt = stmt;
  6156. array_add(&p->defer_stmts, d);
  6157. return d;
  6158. }
  6159. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  6160. lbDefer d = {lbDefer_Proc};
  6161. d.scope_index = p->scope_index;
  6162. d.block = p->curr_block;
  6163. d.proc.deferred = deferred;
  6164. d.proc.result_as_args = result_as_args;
  6165. array_add(&p->defer_stmts, d);
  6166. return d;
  6167. }
  6168. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  6169. Array<lbValue> array = {};
  6170. Type *t = base_type(value.type);
  6171. if (t == nullptr) {
  6172. // Do nothing
  6173. } else if (is_type_tuple(t)) {
  6174. GB_ASSERT(t->kind == Type_Tuple);
  6175. auto *rt = &t->Tuple;
  6176. if (rt->variables.count > 0) {
  6177. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  6178. for_array(i, rt->variables) {
  6179. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  6180. array[i] = elem;
  6181. }
  6182. }
  6183. } else {
  6184. array = array_make<lbValue>(permanent_allocator(), 1);
  6185. array[0] = value;
  6186. }
  6187. return array;
  6188. }
  6189. 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) {
  6190. unsigned arg_count = cast(unsigned)processed_args.count;
  6191. if (return_ptr.value != nullptr) {
  6192. arg_count += 1;
  6193. }
  6194. if (context_ptr.addr.value != nullptr) {
  6195. arg_count += 1;
  6196. }
  6197. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  6198. isize arg_index = 0;
  6199. if (return_ptr.value != nullptr) {
  6200. args[arg_index++] = return_ptr.value;
  6201. }
  6202. for_array(i, processed_args) {
  6203. lbValue arg = processed_args[i];
  6204. args[arg_index++] = arg.value;
  6205. }
  6206. if (context_ptr.addr.value != nullptr) {
  6207. args[arg_index++] = context_ptr.addr.value;
  6208. }
  6209. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  6210. GB_ASSERT(curr_block != p->decl_block->block);
  6211. if (USE_LLVM_ABI) {
  6212. LLVMTypeRef ftp = lb_type(p->module, value.type);
  6213. LLVMTypeRef ft = LLVMGetElementType(ftp);
  6214. LLVMValueRef fn = value.value;
  6215. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  6216. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  6217. }
  6218. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  6219. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  6220. LLVMValueRef ret = LLVMBuildCall2(p->builder, ft, fn, args, arg_count, "");;
  6221. lbValue res = {};
  6222. res.value = ret;
  6223. res.type = abi_rt;
  6224. return res;
  6225. } else {
  6226. LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");;
  6227. lbValue res = {};
  6228. res.value = ret;
  6229. res.type = abi_rt;
  6230. return res;
  6231. }
  6232. }
  6233. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  6234. String name = make_string_c(c_name);
  6235. AstPackage *pkg = p->module->info->runtime_package;
  6236. Entity *e = scope_lookup_current(pkg->scope, name);
  6237. lbValue *found = nullptr;
  6238. if (p->module != e->code_gen_module) {
  6239. gb_mutex_lock(&p->module->mutex);
  6240. }
  6241. found = map_get(&e->code_gen_module->values, hash_entity(e));
  6242. if (p->module != e->code_gen_module) {
  6243. gb_mutex_unlock(&p->module->mutex);
  6244. }
  6245. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6246. return lb_emit_call(p, *found, args);
  6247. }
  6248. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6249. lbModule *m = p->module;
  6250. Type *pt = base_type(value.type);
  6251. GB_ASSERT(pt->kind == Type_Proc);
  6252. Type *results = pt->Proc.results;
  6253. if (p->entity != nullptr) {
  6254. if (p->entity->flags & EntityFlag_Disabled) {
  6255. return {};
  6256. }
  6257. }
  6258. lbAddr context_ptr = {};
  6259. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6260. context_ptr = lb_find_or_generate_context_ptr(p);
  6261. }
  6262. defer (if (pt->Proc.diverging) {
  6263. LLVMBuildUnreachable(p->builder);
  6264. });
  6265. set_procedure_abi_types(pt);
  6266. bool is_c_vararg = pt->Proc.c_vararg;
  6267. isize param_count = pt->Proc.param_count;
  6268. if (is_c_vararg) {
  6269. GB_ASSERT(param_count-1 <= args.count);
  6270. param_count -= 1;
  6271. } else {
  6272. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6273. }
  6274. lbValue result = {};
  6275. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6276. if (USE_LLVM_ABI) {
  6277. lbFunctionType **ft_found = nullptr;
  6278. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6279. if (!ft_found) {
  6280. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6281. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6282. }
  6283. GB_ASSERT(ft_found != nullptr);
  6284. lbFunctionType *ft = *ft_found;
  6285. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6286. unsigned param_index = 0;
  6287. for (isize i = 0; i < param_count; i++) {
  6288. Entity *e = pt->Proc.params->Tuple.variables[i];
  6289. if (e->kind != Entity_Variable) {
  6290. continue;
  6291. }
  6292. GB_ASSERT(e->flags & EntityFlag_Param);
  6293. Type *original_type = e->type;
  6294. lbArgType *arg = &ft->args[param_index];
  6295. if (arg->kind == lbArg_Ignore) {
  6296. continue;
  6297. }
  6298. lbValue x = lb_emit_conv(p, args[i], original_type);
  6299. LLVMTypeRef xt = lb_type(p->module, x.type);
  6300. if (arg->kind == lbArg_Direct) {
  6301. LLVMTypeRef abi_type = arg->cast_type;
  6302. if (!abi_type) {
  6303. abi_type = arg->type;
  6304. }
  6305. if (xt == abi_type) {
  6306. array_add(&processed_args, x);
  6307. } else {
  6308. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6309. array_add(&processed_args, x);
  6310. }
  6311. } else if (arg->kind == lbArg_Indirect) {
  6312. lbValue ptr = {};
  6313. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6314. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6315. // i.e. `T const &` in C++
  6316. ptr = lb_address_from_load_or_generate_local(p, x);
  6317. } else {
  6318. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6319. }
  6320. array_add(&processed_args, ptr);
  6321. }
  6322. param_index += 1;
  6323. }
  6324. if (inlining == ProcInlining_none) {
  6325. inlining = p->inlining;
  6326. }
  6327. Type *rt = reduce_tuple_to_single_type(results);
  6328. if (return_by_pointer) {
  6329. lbValue return_ptr = {};
  6330. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6331. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6332. return_ptr = p->return_ptr_hint_value;
  6333. p->return_ptr_hint_used = true;
  6334. }
  6335. }
  6336. if (return_ptr.value == nullptr) {
  6337. lbAddr r = lb_add_local_generated(p, rt, true);
  6338. return_ptr = r.addr;
  6339. }
  6340. GB_ASSERT(is_type_pointer(return_ptr.type));
  6341. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6342. result = lb_emit_load(p, return_ptr);
  6343. } else if (rt != nullptr) {
  6344. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6345. if (ft->ret.cast_type) {
  6346. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  6347. }
  6348. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  6349. result.type = rt;
  6350. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  6351. result.type = t_llvm_bool;
  6352. }
  6353. if (!is_type_tuple(rt)) {
  6354. result = lb_emit_conv(p, result, rt);
  6355. }
  6356. } else {
  6357. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6358. }
  6359. } else {
  6360. for (isize i = 0; i < param_count; i++) {
  6361. Entity *e = pt->Proc.params->Tuple.variables[i];
  6362. if (e->kind != Entity_Variable) {
  6363. // array_add(&processed_args, args[i]);
  6364. continue;
  6365. }
  6366. GB_ASSERT(e->flags & EntityFlag_Param);
  6367. Type *original_type = e->type;
  6368. Type *new_type = pt->Proc.abi_compat_params[i];
  6369. Type *arg_type = args[i].type;
  6370. if (are_types_identical(arg_type, new_type)) {
  6371. // NOTE(bill): Done
  6372. array_add(&processed_args, args[i]);
  6373. } else if (!are_types_identical(original_type, new_type)) {
  6374. if (is_type_pointer(new_type) && !is_type_pointer(original_type)) {
  6375. Type *av = core_type(type_deref(new_type));
  6376. if (are_types_identical(av, core_type(original_type))) {
  6377. if (e->flags&EntityFlag_ImplicitReference) {
  6378. array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i]));
  6379. } else if (!is_type_pointer(arg_type)) {
  6380. array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16));
  6381. }
  6382. } else {
  6383. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  6384. }
  6385. } else if (new_type == t_llvm_bool) {
  6386. array_add(&processed_args, lb_emit_conv(p, args[i], new_type));
  6387. } else if (is_type_integer(new_type) || is_type_float(new_type) || is_type_boolean(new_type)) {
  6388. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  6389. } else if (is_type_simd_vector(new_type)) {
  6390. array_add(&processed_args, lb_emit_transmute(p, args[i], new_type));
  6391. } else if (is_type_tuple(new_type)) {
  6392. Type *abi_type = pt->Proc.abi_compat_params[i];
  6393. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  6394. lbValue x = {};
  6395. i64 st_sz = type_size_of(st);
  6396. i64 arg_sz = type_size_of(args[i].type);
  6397. if (st_sz == arg_sz) {
  6398. x = lb_emit_transmute(p, args[i], st);
  6399. } else {
  6400. // NOTE(bill): struct{f32, f32, f32} != struct{#simd[2]f32, f32}
  6401. GB_ASSERT(st_sz > arg_sz);
  6402. lbAddr xx = lb_add_local_generated(p, st, false);
  6403. lbValue pp = lb_emit_conv(p, xx.addr, alloc_type_pointer(args[i].type));
  6404. lb_emit_store(p, pp, args[i]);
  6405. x = lb_addr_load(p, xx);
  6406. }
  6407. for (isize j = 0; j < new_type->Tuple.variables.count; j++) {
  6408. lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j);
  6409. array_add(&processed_args, xx);
  6410. }
  6411. }
  6412. } else {
  6413. lbValue x = lb_emit_conv(p, args[i], new_type);
  6414. array_add(&processed_args, x);
  6415. }
  6416. }
  6417. if (inlining == ProcInlining_none) {
  6418. inlining = p->inlining;
  6419. }
  6420. Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type);
  6421. Type *rt = reduce_tuple_to_single_type(results);
  6422. if (pt->Proc.return_by_pointer) {
  6423. lbValue return_ptr = {};
  6424. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6425. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6426. return_ptr = p->return_ptr_hint_value;
  6427. p->return_ptr_hint_used = true;
  6428. }
  6429. }
  6430. if (return_ptr.value == nullptr) {
  6431. lbAddr r = lb_add_local_generated(p, rt, true);
  6432. return_ptr = r.addr;
  6433. }
  6434. GB_ASSERT(is_type_pointer(return_ptr.type));
  6435. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6436. result = lb_emit_load(p, return_ptr);
  6437. } else {
  6438. result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining);
  6439. if (abi_rt != rt) {
  6440. result = lb_emit_transmute(p, result, rt);
  6441. }
  6442. }
  6443. }
  6444. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6445. if (found != nullptr) {
  6446. Entity *e = *found;
  6447. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6448. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6449. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6450. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6451. GB_ASSERT(deferred_found != nullptr);
  6452. lbValue deferred = *deferred_found;
  6453. auto in_args = args;
  6454. Array<lbValue> result_as_args = {};
  6455. switch (kind) {
  6456. case DeferredProcedure_none:
  6457. break;
  6458. case DeferredProcedure_in:
  6459. result_as_args = in_args;
  6460. break;
  6461. case DeferredProcedure_out:
  6462. result_as_args = lb_value_to_array(p, result);
  6463. break;
  6464. case DeferredProcedure_in_out:
  6465. {
  6466. auto out_args = lb_value_to_array(p, result);
  6467. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6468. array_copy(&result_as_args, in_args, 0);
  6469. array_copy(&result_as_args, out_args, in_args.count);
  6470. }
  6471. break;
  6472. }
  6473. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6474. }
  6475. }
  6476. return result;
  6477. }
  6478. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6479. Type *t = s.type;
  6480. GB_ASSERT(is_type_pointer(t));
  6481. Type *st = base_type(type_deref(t));
  6482. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6483. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6484. LLVMValueRef indices[2] = {};
  6485. indices[0] = llvm_zero(p->module);
  6486. indices[1] = lb_emit_conv(p, index, t_int).value;
  6487. Type *ptr = base_array_type(st);
  6488. lbValue res = {};
  6489. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6490. res.type = alloc_type_pointer(ptr);
  6491. return res;
  6492. }
  6493. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6494. Type *t = s.type;
  6495. GB_ASSERT(is_type_pointer(t));
  6496. Type *st = base_type(type_deref(t));
  6497. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6498. GB_ASSERT(0 <= index);
  6499. Type *ptr = base_array_type(st);
  6500. LLVMValueRef indices[2] = {
  6501. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6502. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6503. };
  6504. lbValue res = {};
  6505. if (lb_is_const(s)) {
  6506. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6507. } else {
  6508. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6509. }
  6510. res.type = alloc_type_pointer(ptr);
  6511. return res;
  6512. }
  6513. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6514. LLVMValueRef indices[1] = {index.value};
  6515. lbValue res = {};
  6516. res.type = ptr.type;
  6517. if (lb_is_const(ptr) && lb_is_const(index)) {
  6518. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6519. } else {
  6520. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6521. }
  6522. return res;
  6523. }
  6524. LLVMValueRef llvm_const_slice(lbValue data, lbValue len) {
  6525. GB_ASSERT(is_type_pointer(data.type));
  6526. GB_ASSERT(are_types_identical(len.type, t_int));
  6527. LLVMValueRef vals[2] = {
  6528. data.value,
  6529. len.value,
  6530. };
  6531. return LLVMConstStruct(vals, gb_count_of(vals), false);
  6532. }
  6533. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6534. Type *t = lb_addr_type(slice);
  6535. GB_ASSERT(is_type_slice(t));
  6536. lbValue ptr = lb_addr_get_ptr(p, slice);
  6537. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6538. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6539. }
  6540. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6541. Type *t = lb_addr_type(string);
  6542. GB_ASSERT(is_type_string(t));
  6543. lbValue ptr = lb_addr_get_ptr(p, string);
  6544. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6545. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6546. }
  6547. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6548. Type *t = base_type(string.type);
  6549. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6550. return lb_emit_struct_ev(p, string, 0);
  6551. }
  6552. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6553. Type *t = base_type(string.type);
  6554. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6555. return lb_emit_struct_ev(p, string, 1);
  6556. }
  6557. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6558. GB_ASSERT(is_type_cstring(value.type));
  6559. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6560. args[0] = lb_emit_conv(p, value, t_cstring);
  6561. return lb_emit_runtime_call(p, "cstring_len", args);
  6562. }
  6563. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6564. Type *t = type_deref(array_ptr.type);
  6565. GB_ASSERT(is_type_array(t));
  6566. return lb_emit_struct_ep(p, array_ptr, 0);
  6567. }
  6568. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6569. GB_ASSERT(is_type_slice(slice.type));
  6570. return lb_emit_struct_ev(p, slice, 0);
  6571. }
  6572. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6573. GB_ASSERT(is_type_slice(slice.type));
  6574. return lb_emit_struct_ev(p, slice, 1);
  6575. }
  6576. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6577. GB_ASSERT(is_type_dynamic_array(da.type));
  6578. return lb_emit_struct_ev(p, da, 0);
  6579. }
  6580. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6581. GB_ASSERT(is_type_dynamic_array(da.type));
  6582. return lb_emit_struct_ev(p, da, 1);
  6583. }
  6584. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6585. GB_ASSERT(is_type_dynamic_array(da.type));
  6586. return lb_emit_struct_ev(p, da, 2);
  6587. }
  6588. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6589. GB_ASSERT(is_type_dynamic_array(da.type));
  6590. return lb_emit_struct_ev(p, da, 3);
  6591. }
  6592. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6593. Type *t = base_type(value.type);
  6594. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6595. init_map_internal_types(t);
  6596. Type *gst = t->Map.generated_struct_type;
  6597. i32 index = 1;
  6598. lbValue entries = lb_emit_struct_ev(p, value, index);
  6599. return entries;
  6600. }
  6601. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6602. Type *t = base_type(type_deref(value.type));
  6603. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6604. init_map_internal_types(t);
  6605. Type *gst = t->Map.generated_struct_type;
  6606. i32 index = 1;
  6607. lbValue entries = lb_emit_struct_ep(p, value, index);
  6608. return entries;
  6609. }
  6610. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6611. lbValue entries = lb_map_entries(p, value);
  6612. return lb_dynamic_array_len(p, entries);
  6613. }
  6614. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6615. lbValue entries = lb_map_entries(p, value);
  6616. return lb_dynamic_array_cap(p, entries);
  6617. }
  6618. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6619. Type *t = base_type(value.type);
  6620. bool is_ptr = false;
  6621. if (is_type_pointer(t)) {
  6622. is_ptr = true;
  6623. t = base_type(type_deref(t));
  6624. }
  6625. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6626. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6627. }
  6628. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6629. t->Struct.soa_kind == StructSoa_Dynamic);
  6630. isize n = 0;
  6631. Type *elem = base_type(t->Struct.soa_elem);
  6632. if (elem->kind == Type_Struct) {
  6633. n = elem->Struct.fields.count;
  6634. } else if (elem->kind == Type_Array) {
  6635. n = elem->Array.count;
  6636. } else {
  6637. GB_PANIC("Unreachable");
  6638. }
  6639. if (is_ptr) {
  6640. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6641. return lb_emit_load(p, v);
  6642. }
  6643. return lb_emit_struct_ev(p, value, cast(i32)n);
  6644. }
  6645. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6646. Type *t = base_type(value.type);
  6647. bool is_ptr = false;
  6648. if (is_type_pointer(t)) {
  6649. is_ptr = true;
  6650. t = base_type(type_deref(t));
  6651. }
  6652. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6653. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6654. }
  6655. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6656. isize n = 0;
  6657. Type *elem = base_type(t->Struct.soa_elem);
  6658. if (elem->kind == Type_Struct) {
  6659. n = elem->Struct.fields.count+1;
  6660. } else if (elem->kind == Type_Array) {
  6661. n = elem->Array.count+1;
  6662. } else {
  6663. GB_PANIC("Unreachable");
  6664. }
  6665. if (is_ptr) {
  6666. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6667. return lb_emit_load(p, v);
  6668. }
  6669. return lb_emit_struct_ev(p, value, cast(i32)n);
  6670. }
  6671. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  6672. ast_node(ce, CallExpr, expr);
  6673. switch (id) {
  6674. case BuiltinProc_DIRECTIVE: {
  6675. ast_node(bd, BasicDirective, ce->proc);
  6676. String name = bd->name;
  6677. GB_ASSERT(name == "location");
  6678. String procedure = p->entity->token.string;
  6679. TokenPos pos = ast_token(ce->proc).pos;
  6680. if (ce->args.count > 0) {
  6681. Ast *ident = unselector_expr(ce->args[0]);
  6682. GB_ASSERT(ident->kind == Ast_Ident);
  6683. Entity *e = entity_of_node(ident);
  6684. GB_ASSERT(e != nullptr);
  6685. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  6686. procedure = e->parent_proc_decl->entity->token.string;
  6687. } else {
  6688. procedure = str_lit("");
  6689. }
  6690. pos = e->token.pos;
  6691. }
  6692. return lb_emit_source_code_location(p, procedure, pos);
  6693. }
  6694. case BuiltinProc_type_info_of: {
  6695. Ast *arg = ce->args[0];
  6696. TypeAndValue tav = type_and_value_of_expr(arg);
  6697. if (tav.mode == Addressing_Type) {
  6698. Type *t = default_type(type_of_expr(arg));
  6699. return lb_type_info(p->module, t);
  6700. }
  6701. GB_ASSERT(is_type_typeid(tav.type));
  6702. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6703. args[0] = lb_build_expr(p, arg);
  6704. return lb_emit_runtime_call(p, "__type_info_of", args);
  6705. }
  6706. case BuiltinProc_typeid_of: {
  6707. Ast *arg = ce->args[0];
  6708. TypeAndValue tav = type_and_value_of_expr(arg);
  6709. GB_ASSERT(tav.mode == Addressing_Type);
  6710. Type *t = default_type(type_of_expr(arg));
  6711. return lb_typeid(p->module, t);
  6712. }
  6713. case BuiltinProc_len: {
  6714. lbValue v = lb_build_expr(p, ce->args[0]);
  6715. Type *t = base_type(v.type);
  6716. if (is_type_pointer(t)) {
  6717. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6718. v = lb_emit_load(p, v);
  6719. t = type_deref(t);
  6720. }
  6721. if (is_type_cstring(t)) {
  6722. return lb_cstring_len(p, v);
  6723. } else if (is_type_string(t)) {
  6724. return lb_string_len(p, v);
  6725. } else if (is_type_array(t)) {
  6726. GB_PANIC("Array lengths are constant");
  6727. } else if (is_type_slice(t)) {
  6728. return lb_slice_len(p, v);
  6729. } else if (is_type_dynamic_array(t)) {
  6730. return lb_dynamic_array_len(p, v);
  6731. } else if (is_type_map(t)) {
  6732. return lb_map_len(p, v);
  6733. } else if (is_type_soa_struct(t)) {
  6734. return lb_soa_struct_len(p, v);
  6735. }
  6736. GB_PANIC("Unreachable");
  6737. break;
  6738. }
  6739. case BuiltinProc_cap: {
  6740. lbValue v = lb_build_expr(p, ce->args[0]);
  6741. Type *t = base_type(v.type);
  6742. if (is_type_pointer(t)) {
  6743. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6744. v = lb_emit_load(p, v);
  6745. t = type_deref(t);
  6746. }
  6747. if (is_type_string(t)) {
  6748. GB_PANIC("Unreachable");
  6749. } else if (is_type_array(t)) {
  6750. GB_PANIC("Array lengths are constant");
  6751. } else if (is_type_slice(t)) {
  6752. return lb_slice_len(p, v);
  6753. } else if (is_type_dynamic_array(t)) {
  6754. return lb_dynamic_array_cap(p, v);
  6755. } else if (is_type_map(t)) {
  6756. return lb_map_cap(p, v);
  6757. } else if (is_type_soa_struct(t)) {
  6758. return lb_soa_struct_cap(p, v);
  6759. }
  6760. GB_PANIC("Unreachable");
  6761. break;
  6762. }
  6763. case BuiltinProc_swizzle: {
  6764. isize index_count = ce->args.count-1;
  6765. if (is_type_simd_vector(tv.type)) {
  6766. lbValue vec = lb_build_expr(p, ce->args[0]);
  6767. if (index_count == 0) {
  6768. return vec;
  6769. }
  6770. unsigned mask_len = cast(unsigned)index_count;
  6771. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  6772. for (isize i = 1; i < ce->args.count; i++) {
  6773. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6774. GB_ASSERT(is_type_integer(tv.type));
  6775. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6776. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  6777. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  6778. }
  6779. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  6780. LLVMValueRef v1 = vec.value;
  6781. LLVMValueRef v2 = vec.value;
  6782. lbValue res = {};
  6783. res.type = tv.type;
  6784. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  6785. return res;
  6786. }
  6787. lbAddr addr = lb_build_addr(p, ce->args[0]);
  6788. if (index_count == 0) {
  6789. return lb_addr_load(p, addr);
  6790. }
  6791. lbValue src = lb_addr_get_ptr(p, addr);
  6792. // TODO(bill): Should this be zeroed or not?
  6793. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  6794. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  6795. for (i32 i = 1; i < ce->args.count; i++) {
  6796. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6797. GB_ASSERT(is_type_integer(tv.type));
  6798. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6799. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  6800. i32 dst_index = i-1;
  6801. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  6802. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  6803. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  6804. }
  6805. return lb_addr_load(p, dst);
  6806. }
  6807. case BuiltinProc_complex: {
  6808. lbValue real = lb_build_expr(p, ce->args[0]);
  6809. lbValue imag = lb_build_expr(p, ce->args[1]);
  6810. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6811. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6812. Type *ft = base_complex_elem_type(tv.type);
  6813. real = lb_emit_conv(p, real, ft);
  6814. imag = lb_emit_conv(p, imag, ft);
  6815. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  6816. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  6817. return lb_emit_load(p, dst);
  6818. }
  6819. case BuiltinProc_quaternion: {
  6820. lbValue real = lb_build_expr(p, ce->args[0]);
  6821. lbValue imag = lb_build_expr(p, ce->args[1]);
  6822. lbValue jmag = lb_build_expr(p, ce->args[2]);
  6823. lbValue kmag = lb_build_expr(p, ce->args[3]);
  6824. // @QuaternionLayout
  6825. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6826. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6827. Type *ft = base_complex_elem_type(tv.type);
  6828. real = lb_emit_conv(p, real, ft);
  6829. imag = lb_emit_conv(p, imag, ft);
  6830. jmag = lb_emit_conv(p, jmag, ft);
  6831. kmag = lb_emit_conv(p, kmag, ft);
  6832. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  6833. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  6834. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  6835. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  6836. return lb_emit_load(p, dst);
  6837. }
  6838. case BuiltinProc_real: {
  6839. lbValue val = lb_build_expr(p, ce->args[0]);
  6840. if (is_type_complex(val.type)) {
  6841. lbValue real = lb_emit_struct_ev(p, val, 0);
  6842. return lb_emit_conv(p, real, tv.type);
  6843. } else if (is_type_quaternion(val.type)) {
  6844. // @QuaternionLayout
  6845. lbValue real = lb_emit_struct_ev(p, val, 3);
  6846. return lb_emit_conv(p, real, tv.type);
  6847. }
  6848. GB_PANIC("invalid type for real");
  6849. return {};
  6850. }
  6851. case BuiltinProc_imag: {
  6852. lbValue val = lb_build_expr(p, ce->args[0]);
  6853. if (is_type_complex(val.type)) {
  6854. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6855. return lb_emit_conv(p, imag, tv.type);
  6856. } else if (is_type_quaternion(val.type)) {
  6857. // @QuaternionLayout
  6858. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6859. return lb_emit_conv(p, imag, tv.type);
  6860. }
  6861. GB_PANIC("invalid type for imag");
  6862. return {};
  6863. }
  6864. case BuiltinProc_jmag: {
  6865. lbValue val = lb_build_expr(p, ce->args[0]);
  6866. if (is_type_quaternion(val.type)) {
  6867. // @QuaternionLayout
  6868. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6869. return lb_emit_conv(p, imag, tv.type);
  6870. }
  6871. GB_PANIC("invalid type for jmag");
  6872. return {};
  6873. }
  6874. case BuiltinProc_kmag: {
  6875. lbValue val = lb_build_expr(p, ce->args[0]);
  6876. if (is_type_quaternion(val.type)) {
  6877. // @QuaternionLayout
  6878. lbValue imag = lb_emit_struct_ev(p, val, 2);
  6879. return lb_emit_conv(p, imag, tv.type);
  6880. }
  6881. GB_PANIC("invalid type for kmag");
  6882. return {};
  6883. }
  6884. case BuiltinProc_conj: {
  6885. lbValue val = lb_build_expr(p, ce->args[0]);
  6886. lbValue res = {};
  6887. Type *t = val.type;
  6888. if (is_type_complex(t)) {
  6889. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6890. lbValue real = lb_emit_struct_ev(p, val, 0);
  6891. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6892. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6893. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  6894. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  6895. } else if (is_type_quaternion(t)) {
  6896. // @QuaternionLayout
  6897. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6898. lbValue real = lb_emit_struct_ev(p, val, 3);
  6899. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6900. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  6901. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  6902. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6903. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  6904. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  6905. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  6906. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  6907. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  6908. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  6909. }
  6910. return lb_emit_load(p, res);
  6911. }
  6912. case BuiltinProc_expand_to_tuple: {
  6913. lbValue val = lb_build_expr(p, ce->args[0]);
  6914. Type *t = base_type(val.type);
  6915. if (!is_type_tuple(tv.type)) {
  6916. if (t->kind == Type_Struct) {
  6917. GB_ASSERT(t->Struct.fields.count == 1);
  6918. return lb_emit_struct_ev(p, val, 0);
  6919. } else if (t->kind == Type_Array) {
  6920. GB_ASSERT(t->Array.count == 1);
  6921. return lb_emit_array_epi(p, val, 0);
  6922. } else {
  6923. GB_PANIC("Unknown type of expand_to_tuple");
  6924. }
  6925. }
  6926. GB_ASSERT(is_type_tuple(tv.type));
  6927. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6928. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6929. if (t->kind == Type_Struct) {
  6930. for_array(src_index, t->Struct.fields) {
  6931. Entity *field = t->Struct.fields[src_index];
  6932. i32 field_index = field->Variable.field_index;
  6933. lbValue f = lb_emit_struct_ev(p, val, field_index);
  6934. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  6935. lb_emit_store(p, ep, f);
  6936. }
  6937. } else if (t->kind == Type_Array) {
  6938. // TODO(bill): Clean-up this code
  6939. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  6940. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6941. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  6942. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  6943. lb_emit_store(p, ep, f);
  6944. }
  6945. } else {
  6946. GB_PANIC("Unknown type of expand_to_tuple");
  6947. }
  6948. return lb_emit_load(p, tuple);
  6949. }
  6950. case BuiltinProc_min: {
  6951. Type *t = type_of_expr(expr);
  6952. if (ce->args.count == 2) {
  6953. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6954. } else {
  6955. lbValue x = lb_build_expr(p, ce->args[0]);
  6956. for (isize i = 1; i < ce->args.count; i++) {
  6957. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  6958. }
  6959. return x;
  6960. }
  6961. }
  6962. case BuiltinProc_max: {
  6963. Type *t = type_of_expr(expr);
  6964. if (ce->args.count == 2) {
  6965. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6966. } else {
  6967. lbValue x = lb_build_expr(p, ce->args[0]);
  6968. for (isize i = 1; i < ce->args.count; i++) {
  6969. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  6970. }
  6971. return x;
  6972. }
  6973. }
  6974. case BuiltinProc_abs: {
  6975. lbValue x = lb_build_expr(p, ce->args[0]);
  6976. Type *t = x.type;
  6977. if (is_type_unsigned(t)) {
  6978. return x;
  6979. }
  6980. if (is_type_quaternion(t)) {
  6981. i64 sz = 8*type_size_of(t);
  6982. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6983. args[0] = x;
  6984. switch (sz) {
  6985. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  6986. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  6987. }
  6988. GB_PANIC("Unknown complex type");
  6989. } else if (is_type_complex(t)) {
  6990. i64 sz = 8*type_size_of(t);
  6991. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6992. args[0] = x;
  6993. switch (sz) {
  6994. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  6995. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  6996. }
  6997. GB_PANIC("Unknown complex type");
  6998. } else if (is_type_float(t)) {
  6999. i64 sz = 8*type_size_of(t);
  7000. auto args = array_make<lbValue>(permanent_allocator(), 1);
  7001. args[0] = x;
  7002. switch (sz) {
  7003. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  7004. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  7005. }
  7006. GB_PANIC("Unknown float type");
  7007. }
  7008. lbValue zero = lb_const_nil(p->module, t);
  7009. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  7010. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  7011. return lb_emit_select(p, cond, neg, x);
  7012. }
  7013. case BuiltinProc_clamp:
  7014. return lb_emit_clamp(p, type_of_expr(expr),
  7015. lb_build_expr(p, ce->args[0]),
  7016. lb_build_expr(p, ce->args[1]),
  7017. lb_build_expr(p, ce->args[2]));
  7018. // "Intrinsics"
  7019. case BuiltinProc_alloca:
  7020. {
  7021. lbValue sz = lb_build_expr(p, ce->args[0]);
  7022. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  7023. lbValue res = {};
  7024. res.type = t_u8_ptr;
  7025. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  7026. LLVMSetAlignment(res.value, cast(unsigned)al);
  7027. return res;
  7028. }
  7029. case BuiltinProc_cpu_relax:
  7030. {
  7031. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  7032. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  7033. "pause", 5,
  7034. "", 0,
  7035. /*HasSideEffects*/true, /*IsAlignStack*/false,
  7036. LLVMInlineAsmDialectATT
  7037. );
  7038. GB_ASSERT(the_asm != nullptr);
  7039. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  7040. }
  7041. return {};
  7042. case BuiltinProc_atomic_fence:
  7043. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  7044. return {};
  7045. case BuiltinProc_atomic_fence_acq:
  7046. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  7047. return {};
  7048. case BuiltinProc_atomic_fence_rel:
  7049. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  7050. return {};
  7051. case BuiltinProc_atomic_fence_acqrel:
  7052. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  7053. return {};
  7054. case BuiltinProc_atomic_store:
  7055. case BuiltinProc_atomic_store_rel:
  7056. case BuiltinProc_atomic_store_relaxed:
  7057. case BuiltinProc_atomic_store_unordered: {
  7058. lbValue dst = lb_build_expr(p, ce->args[0]);
  7059. lbValue val = lb_build_expr(p, ce->args[1]);
  7060. val = lb_emit_conv(p, val, type_deref(dst.type));
  7061. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  7062. switch (id) {
  7063. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7064. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  7065. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7066. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7067. }
  7068. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7069. return {};
  7070. }
  7071. case BuiltinProc_atomic_load:
  7072. case BuiltinProc_atomic_load_acq:
  7073. case BuiltinProc_atomic_load_relaxed:
  7074. case BuiltinProc_atomic_load_unordered: {
  7075. lbValue dst = lb_build_expr(p, ce->args[0]);
  7076. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  7077. switch (id) {
  7078. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  7079. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  7080. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  7081. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  7082. }
  7083. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  7084. lbValue res = {};
  7085. res.value = instr;
  7086. res.type = type_deref(dst.type);
  7087. return res;
  7088. }
  7089. case BuiltinProc_atomic_add:
  7090. case BuiltinProc_atomic_add_acq:
  7091. case BuiltinProc_atomic_add_rel:
  7092. case BuiltinProc_atomic_add_acqrel:
  7093. case BuiltinProc_atomic_add_relaxed:
  7094. case BuiltinProc_atomic_sub:
  7095. case BuiltinProc_atomic_sub_acq:
  7096. case BuiltinProc_atomic_sub_rel:
  7097. case BuiltinProc_atomic_sub_acqrel:
  7098. case BuiltinProc_atomic_sub_relaxed:
  7099. case BuiltinProc_atomic_and:
  7100. case BuiltinProc_atomic_and_acq:
  7101. case BuiltinProc_atomic_and_rel:
  7102. case BuiltinProc_atomic_and_acqrel:
  7103. case BuiltinProc_atomic_and_relaxed:
  7104. case BuiltinProc_atomic_nand:
  7105. case BuiltinProc_atomic_nand_acq:
  7106. case BuiltinProc_atomic_nand_rel:
  7107. case BuiltinProc_atomic_nand_acqrel:
  7108. case BuiltinProc_atomic_nand_relaxed:
  7109. case BuiltinProc_atomic_or:
  7110. case BuiltinProc_atomic_or_acq:
  7111. case BuiltinProc_atomic_or_rel:
  7112. case BuiltinProc_atomic_or_acqrel:
  7113. case BuiltinProc_atomic_or_relaxed:
  7114. case BuiltinProc_atomic_xor:
  7115. case BuiltinProc_atomic_xor_acq:
  7116. case BuiltinProc_atomic_xor_rel:
  7117. case BuiltinProc_atomic_xor_acqrel:
  7118. case BuiltinProc_atomic_xor_relaxed:
  7119. case BuiltinProc_atomic_xchg:
  7120. case BuiltinProc_atomic_xchg_acq:
  7121. case BuiltinProc_atomic_xchg_rel:
  7122. case BuiltinProc_atomic_xchg_acqrel:
  7123. case BuiltinProc_atomic_xchg_relaxed: {
  7124. lbValue dst = lb_build_expr(p, ce->args[0]);
  7125. lbValue val = lb_build_expr(p, ce->args[1]);
  7126. val = lb_emit_conv(p, val, type_deref(dst.type));
  7127. LLVMAtomicRMWBinOp op = {};
  7128. LLVMAtomicOrdering ordering = {};
  7129. switch (id) {
  7130. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7131. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  7132. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  7133. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7134. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  7135. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7136. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  7137. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  7138. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7139. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  7140. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7141. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  7142. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  7143. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7144. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  7145. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7146. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  7147. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  7148. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7149. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  7150. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7151. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  7152. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  7153. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7154. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  7155. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7156. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  7157. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  7158. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7159. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  7160. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  7161. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  7162. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  7163. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  7164. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  7165. }
  7166. lbValue res = {};
  7167. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  7168. res.type = tv.type;
  7169. return res;
  7170. }
  7171. case BuiltinProc_atomic_cxchg:
  7172. case BuiltinProc_atomic_cxchg_acq:
  7173. case BuiltinProc_atomic_cxchg_rel:
  7174. case BuiltinProc_atomic_cxchg_acqrel:
  7175. case BuiltinProc_atomic_cxchg_relaxed:
  7176. case BuiltinProc_atomic_cxchg_failrelaxed:
  7177. case BuiltinProc_atomic_cxchg_failacq:
  7178. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  7179. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  7180. case BuiltinProc_atomic_cxchgweak:
  7181. case BuiltinProc_atomic_cxchgweak_acq:
  7182. case BuiltinProc_atomic_cxchgweak_rel:
  7183. case BuiltinProc_atomic_cxchgweak_acqrel:
  7184. case BuiltinProc_atomic_cxchgweak_relaxed:
  7185. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  7186. case BuiltinProc_atomic_cxchgweak_failacq:
  7187. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  7188. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  7189. Type *type = expr->tav.type;
  7190. lbValue address = lb_build_expr(p, ce->args[0]);
  7191. Type *elem = type_deref(address.type);
  7192. lbValue old_value = lb_build_expr(p, ce->args[1]);
  7193. lbValue new_value = lb_build_expr(p, ce->args[2]);
  7194. old_value = lb_emit_conv(p, old_value, elem);
  7195. new_value = lb_emit_conv(p, new_value, elem);
  7196. LLVMAtomicOrdering success_ordering = {};
  7197. LLVMAtomicOrdering failure_ordering = {};
  7198. LLVMBool weak = false;
  7199. switch (id) {
  7200. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7201. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7202. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7203. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7204. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7205. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7206. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  7207. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7208. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  7209. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  7210. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7211. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7212. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  7213. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7214. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7215. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  7216. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7217. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  7218. }
  7219. // TODO(bill): Figure out how to make it weak
  7220. LLVMBool single_threaded = weak;
  7221. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  7222. p->builder, address.value,
  7223. old_value.value, new_value.value,
  7224. success_ordering,
  7225. failure_ordering,
  7226. single_threaded
  7227. );
  7228. GB_ASSERT(tv.type->kind == Type_Tuple);
  7229. Type *fix_typed = alloc_type_tuple();
  7230. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  7231. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  7232. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  7233. lbValue res = {};
  7234. res.value = value;
  7235. res.type = fix_typed;
  7236. return res;
  7237. }
  7238. }
  7239. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  7240. return {};
  7241. }
  7242. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  7243. switch (param_value.kind) {
  7244. case ParameterValue_Constant:
  7245. if (is_type_constant_type(parameter_type)) {
  7246. return lb_const_value(p->module, parameter_type, param_value.value);
  7247. } else {
  7248. ExactValue ev = param_value.value;
  7249. lbValue arg = {};
  7250. Type *type = type_of_expr(param_value.original_ast_expr);
  7251. if (type != nullptr) {
  7252. arg = lb_const_value(p->module, type, ev);
  7253. } else {
  7254. arg = lb_const_value(p->module, parameter_type, param_value.value);
  7255. }
  7256. return lb_emit_conv(p, arg, parameter_type);
  7257. }
  7258. case ParameterValue_Nil:
  7259. return lb_const_nil(p->module, parameter_type);
  7260. case ParameterValue_Location:
  7261. {
  7262. String proc_name = {};
  7263. if (p->entity != nullptr) {
  7264. proc_name = p->entity->token.string;
  7265. }
  7266. return lb_emit_source_code_location(p, proc_name, pos);
  7267. }
  7268. case ParameterValue_Value:
  7269. return lb_build_expr(p, param_value.ast_value);
  7270. }
  7271. return lb_const_nil(p->module, parameter_type);
  7272. }
  7273. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  7274. lbModule *m = p->module;
  7275. TypeAndValue tv = type_and_value_of_expr(expr);
  7276. ast_node(ce, CallExpr, expr);
  7277. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  7278. AddressingMode proc_mode = proc_tv.mode;
  7279. if (proc_mode == Addressing_Type) {
  7280. GB_ASSERT(ce->args.count == 1);
  7281. lbValue x = lb_build_expr(p, ce->args[0]);
  7282. lbValue y = lb_emit_conv(p, x, tv.type);
  7283. return y;
  7284. }
  7285. Ast *pexpr = unparen_expr(ce->proc);
  7286. if (proc_mode == Addressing_Builtin) {
  7287. Entity *e = entity_of_node(pexpr);
  7288. BuiltinProcId id = BuiltinProc_Invalid;
  7289. if (e != nullptr) {
  7290. id = cast(BuiltinProcId)e->Builtin.id;
  7291. } else {
  7292. id = BuiltinProc_DIRECTIVE;
  7293. }
  7294. return lb_build_builtin_proc(p, expr, tv, id);
  7295. }
  7296. // NOTE(bill): Regular call
  7297. lbValue value = {};
  7298. Ast *proc_expr = unparen_expr(ce->proc);
  7299. if (proc_expr->tav.mode == Addressing_Constant) {
  7300. ExactValue v = proc_expr->tav.value;
  7301. switch (v.kind) {
  7302. case ExactValue_Integer:
  7303. {
  7304. u64 u = big_int_to_u64(&v.value_integer);
  7305. lbValue x = {};
  7306. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7307. x.type = t_uintptr;
  7308. x = lb_emit_conv(p, x, t_rawptr);
  7309. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7310. break;
  7311. }
  7312. case ExactValue_Pointer:
  7313. {
  7314. u64 u = cast(u64)v.value_pointer;
  7315. lbValue x = {};
  7316. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  7317. x.type = t_uintptr;
  7318. x = lb_emit_conv(p, x, t_rawptr);
  7319. value = lb_emit_conv(p, x, proc_expr->tav.type);
  7320. break;
  7321. }
  7322. }
  7323. }
  7324. if (value.value == nullptr) {
  7325. value = lb_build_expr(p, proc_expr);
  7326. }
  7327. GB_ASSERT(value.value != nullptr);
  7328. Type *proc_type_ = base_type(value.type);
  7329. GB_ASSERT(proc_type_->kind == Type_Proc);
  7330. TypeProc *pt = &proc_type_->Proc;
  7331. set_procedure_abi_types(proc_type_);
  7332. if (is_call_expr_field_value(ce)) {
  7333. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7334. for_array(arg_index, ce->args) {
  7335. Ast *arg = ce->args[arg_index];
  7336. ast_node(fv, FieldValue, arg);
  7337. GB_ASSERT(fv->field->kind == Ast_Ident);
  7338. String name = fv->field->Ident.token.string;
  7339. isize index = lookup_procedure_parameter(pt, name);
  7340. GB_ASSERT(index >= 0);
  7341. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7342. if (tav.mode == Addressing_Type) {
  7343. args[index] = lb_const_nil(m, tav.type);
  7344. } else {
  7345. args[index] = lb_build_expr(p, fv->value);
  7346. }
  7347. }
  7348. TypeTuple *params = &pt->params->Tuple;
  7349. for (isize i = 0; i < args.count; i++) {
  7350. Entity *e = params->variables[i];
  7351. if (e->kind == Entity_TypeName) {
  7352. args[i] = lb_const_nil(m, e->type);
  7353. } else if (e->kind == Entity_Constant) {
  7354. continue;
  7355. } else {
  7356. GB_ASSERT(e->kind == Entity_Variable);
  7357. if (args[i].value == nullptr) {
  7358. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7359. } else {
  7360. args[i] = lb_emit_conv(p, args[i], e->type);
  7361. }
  7362. }
  7363. }
  7364. for (isize i = 0; i < args.count; i++) {
  7365. Entity *e = params->variables[i];
  7366. if (args[i].type == nullptr) {
  7367. continue;
  7368. } else if (is_type_untyped_nil(args[i].type)) {
  7369. args[i] = lb_const_nil(m, e->type);
  7370. } else if (is_type_untyped_undef(args[i].type)) {
  7371. args[i] = lb_const_undef(m, e->type);
  7372. }
  7373. }
  7374. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7375. }
  7376. isize arg_index = 0;
  7377. isize arg_count = 0;
  7378. for_array(i, ce->args) {
  7379. Ast *arg = ce->args[i];
  7380. TypeAndValue tav = type_and_value_of_expr(arg);
  7381. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7382. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7383. Type *at = tav.type;
  7384. if (at->kind == Type_Tuple) {
  7385. arg_count += at->Tuple.variables.count;
  7386. } else {
  7387. arg_count++;
  7388. }
  7389. }
  7390. isize param_count = 0;
  7391. if (pt->params) {
  7392. GB_ASSERT(pt->params->kind == Type_Tuple);
  7393. param_count = pt->params->Tuple.variables.count;
  7394. }
  7395. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  7396. isize variadic_index = pt->variadic_index;
  7397. bool variadic = pt->variadic && variadic_index >= 0;
  7398. bool vari_expand = ce->ellipsis.pos.line != 0;
  7399. bool is_c_vararg = pt->c_vararg;
  7400. String proc_name = {};
  7401. if (p->entity != nullptr) {
  7402. proc_name = p->entity->token.string;
  7403. }
  7404. TokenPos pos = ast_token(ce->proc).pos;
  7405. TypeTuple *param_tuple = nullptr;
  7406. if (pt->params) {
  7407. GB_ASSERT(pt->params->kind == Type_Tuple);
  7408. param_tuple = &pt->params->Tuple;
  7409. }
  7410. for_array(i, ce->args) {
  7411. Ast *arg = ce->args[i];
  7412. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  7413. if (arg_tv.mode == Addressing_Type) {
  7414. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  7415. } else {
  7416. lbValue a = lb_build_expr(p, arg);
  7417. Type *at = a.type;
  7418. if (at->kind == Type_Tuple) {
  7419. for_array(i, at->Tuple.variables) {
  7420. Entity *e = at->Tuple.variables[i];
  7421. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7422. args[arg_index++] = v;
  7423. }
  7424. } else {
  7425. args[arg_index++] = a;
  7426. }
  7427. }
  7428. }
  7429. if (param_count > 0) {
  7430. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7431. GB_ASSERT(param_count < 1000000);
  7432. if (arg_count < param_count) {
  7433. isize end = cast(isize)param_count;
  7434. if (variadic) {
  7435. end = variadic_index;
  7436. }
  7437. while (arg_index < end) {
  7438. Entity *e = param_tuple->variables[arg_index];
  7439. GB_ASSERT(e->kind == Entity_Variable);
  7440. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7441. }
  7442. }
  7443. if (is_c_vararg) {
  7444. GB_ASSERT(variadic);
  7445. GB_ASSERT(!vari_expand);
  7446. isize i = 0;
  7447. for (; i < variadic_index; i++) {
  7448. Entity *e = param_tuple->variables[i];
  7449. if (e->kind == Entity_Variable) {
  7450. args[i] = lb_emit_conv(p, args[i], e->type);
  7451. }
  7452. }
  7453. Type *variadic_type = param_tuple->variables[i]->type;
  7454. GB_ASSERT(is_type_slice(variadic_type));
  7455. variadic_type = base_type(variadic_type)->Slice.elem;
  7456. if (!is_type_any(variadic_type)) {
  7457. for (; i < arg_count; i++) {
  7458. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7459. }
  7460. } else {
  7461. for (; i < arg_count; i++) {
  7462. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7463. }
  7464. }
  7465. } else if (variadic) {
  7466. isize i = 0;
  7467. for (; i < variadic_index; i++) {
  7468. Entity *e = param_tuple->variables[i];
  7469. if (e->kind == Entity_Variable) {
  7470. args[i] = lb_emit_conv(p, args[i], e->type);
  7471. }
  7472. }
  7473. if (!vari_expand) {
  7474. Type *variadic_type = param_tuple->variables[i]->type;
  7475. GB_ASSERT(is_type_slice(variadic_type));
  7476. variadic_type = base_type(variadic_type)->Slice.elem;
  7477. for (; i < arg_count; i++) {
  7478. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7479. }
  7480. }
  7481. } else {
  7482. for (isize i = 0; i < param_count; i++) {
  7483. Entity *e = param_tuple->variables[i];
  7484. if (e->kind == Entity_Variable) {
  7485. if (args[i].value == nullptr) {
  7486. continue;
  7487. }
  7488. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7489. args[i] = lb_emit_conv(p, args[i], e->type);
  7490. }
  7491. }
  7492. }
  7493. if (variadic && !vari_expand && !is_c_vararg) {
  7494. // variadic call argument generation
  7495. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7496. Type *elem_type = base_type(slice_type)->Slice.elem;
  7497. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7498. isize slice_len = arg_count+1 - (variadic_index+1);
  7499. if (slice_len > 0) {
  7500. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7501. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7502. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7503. lb_emit_store(p, addr, args[i]);
  7504. }
  7505. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7506. lbValue len = lb_const_int(m, t_int, slice_len);
  7507. lb_fill_slice(p, slice, base_elem, len);
  7508. }
  7509. arg_count = param_count;
  7510. args[variadic_index] = lb_addr_load(p, slice);
  7511. }
  7512. }
  7513. if (variadic && variadic_index+1 < param_count) {
  7514. for (isize i = variadic_index+1; i < param_count; i++) {
  7515. Entity *e = param_tuple->variables[i];
  7516. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7517. }
  7518. }
  7519. isize final_count = param_count;
  7520. if (is_c_vararg) {
  7521. final_count = arg_count;
  7522. }
  7523. if (param_tuple != nullptr) {
  7524. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7525. Entity *e = param_tuple->variables[i];
  7526. if (args[i].type == nullptr) {
  7527. continue;
  7528. } else if (is_type_untyped_nil(args[i].type)) {
  7529. args[i] = lb_const_nil(m, e->type);
  7530. } else if (is_type_untyped_undef(args[i].type)) {
  7531. args[i] = lb_const_undef(m, e->type);
  7532. }
  7533. }
  7534. }
  7535. auto call_args = array_slice(args, 0, final_count);
  7536. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7537. }
  7538. bool lb_is_const(lbValue value) {
  7539. LLVMValueRef v = value.value;
  7540. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7541. // TODO(bill): Is this correct behaviour?
  7542. return true;
  7543. }
  7544. if (LLVMIsConstant(v)) {
  7545. return true;
  7546. }
  7547. return false;
  7548. }
  7549. bool lb_is_const_nil(lbValue value) {
  7550. LLVMValueRef v = value.value;
  7551. if (LLVMIsConstant(v)) {
  7552. if (LLVMIsAConstantAggregateZero(v)) {
  7553. return true;
  7554. } else if (LLVMIsAConstantPointerNull(v)) {
  7555. return true;
  7556. }
  7557. }
  7558. return false;
  7559. }
  7560. String lb_get_const_string(lbModule *m, lbValue value) {
  7561. GB_ASSERT(lb_is_const(value));
  7562. Type *t = base_type(value.type);
  7563. GB_ASSERT(are_types_identical(t, t_string));
  7564. unsigned ptr_indices[1] = {0};
  7565. unsigned len_indices[1] = {1};
  7566. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7567. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7568. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7569. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7570. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7571. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7572. size_t length = 0;
  7573. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7574. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7575. return make_string(cast(u8 const *)text, real_length);
  7576. }
  7577. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7578. GB_ASSERT(is_type_pointer(addr.type));
  7579. Type *type = type_deref(addr.type);
  7580. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7581. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7582. }
  7583. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7584. AstPackage *pkg = m->info->runtime_package;
  7585. Entity *e = scope_lookup_current(pkg->scope, name);
  7586. lbValue *found = nullptr;
  7587. if (m != e->code_gen_module) {
  7588. gb_mutex_lock(&m->mutex);
  7589. }
  7590. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7591. if (m != e->code_gen_module) {
  7592. gb_mutex_unlock(&m->mutex);
  7593. }
  7594. GB_ASSERT(found != nullptr);
  7595. return found->value;
  7596. }
  7597. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7598. Type *vt = core_type(value.type);
  7599. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7600. // TODO(bill): lb_emit_byte_swap
  7601. lbValue res = {};
  7602. res.type = platform_type;
  7603. res.value = value.value;
  7604. int sz = cast(int)type_size_of(vt);
  7605. if (sz > 1) {
  7606. if (is_type_float(platform_type)) {
  7607. String name = {};
  7608. switch (sz) {
  7609. case 4: name = str_lit("bswap_f32"); break;
  7610. case 8: name = str_lit("bswap_f64"); break;
  7611. default: GB_PANIC("unhandled byteswap size"); break;
  7612. }
  7613. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7614. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7615. } else {
  7616. GB_ASSERT(is_type_integer(platform_type));
  7617. String name = {};
  7618. switch (sz) {
  7619. case 2: name = str_lit("bswap_16"); break;
  7620. case 4: name = str_lit("bswap_32"); break;
  7621. case 8: name = str_lit("bswap_64"); break;
  7622. case 16: name = str_lit("bswap_128"); break;
  7623. default: GB_PANIC("unhandled byteswap size"); break;
  7624. }
  7625. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7626. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7627. }
  7628. }
  7629. return res;
  7630. }
  7631. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  7632. lbLoopData data = {};
  7633. lbValue max = lb_const_int(p->module, t_int, count);
  7634. data.idx_addr = lb_add_local_generated(p, index_type, true);
  7635. data.body = lb_create_block(p, "loop.body");
  7636. data.done = lb_create_block(p, "loop.done");
  7637. data.loop = lb_create_block(p, "loop.loop");
  7638. lb_emit_jump(p, data.loop);
  7639. lb_start_block(p, data.loop);
  7640. data.idx = lb_addr_load(p, data.idx_addr);
  7641. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  7642. lb_emit_if(p, cond, data.body, data.done);
  7643. lb_start_block(p, data.body);
  7644. return data;
  7645. }
  7646. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  7647. if (data.idx_addr.addr.value != nullptr) {
  7648. lb_emit_increment(p, data.idx_addr.addr);
  7649. lb_emit_jump(p, data.loop);
  7650. lb_start_block(p, data.done);
  7651. }
  7652. }
  7653. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  7654. lbValue res = {};
  7655. res.type = t_llvm_bool;
  7656. Type *t = x.type;
  7657. if (is_type_pointer(t)) {
  7658. if (op_kind == Token_CmpEq) {
  7659. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7660. } else if (op_kind == Token_NotEq) {
  7661. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7662. }
  7663. return res;
  7664. } else if (is_type_cstring(t)) {
  7665. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  7666. if (op_kind == Token_CmpEq) {
  7667. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  7668. } else if (op_kind == Token_NotEq) {
  7669. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  7670. }
  7671. return res;
  7672. } else if (is_type_proc(t)) {
  7673. if (op_kind == Token_CmpEq) {
  7674. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7675. } else if (op_kind == Token_NotEq) {
  7676. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7677. }
  7678. return res;
  7679. } else if (is_type_any(t)) {
  7680. // TODO(bill): is this correct behaviour for nil comparison for any?
  7681. lbValue data = lb_emit_struct_ev(p, x, 0);
  7682. lbValue ti = lb_emit_struct_ev(p, x, 1);
  7683. if (op_kind == Token_CmpEq) {
  7684. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  7685. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  7686. res.value = LLVMBuildOr(p->builder, a, b, "");
  7687. return res;
  7688. } else if (op_kind == Token_NotEq) {
  7689. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  7690. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  7691. res.value = LLVMBuildAnd(p->builder, a, b, "");
  7692. return res;
  7693. }
  7694. } else if (is_type_slice(t)) {
  7695. lbValue len = lb_emit_struct_ev(p, x, 1);
  7696. if (op_kind == Token_CmpEq) {
  7697. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7698. return res;
  7699. } else if (op_kind == Token_NotEq) {
  7700. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7701. return res;
  7702. }
  7703. } else if (is_type_dynamic_array(t)) {
  7704. lbValue cap = lb_emit_struct_ev(p, x, 2);
  7705. if (op_kind == Token_CmpEq) {
  7706. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7707. return res;
  7708. } else if (op_kind == Token_NotEq) {
  7709. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7710. return res;
  7711. }
  7712. } else if (is_type_map(t)) {
  7713. lbValue cap = lb_map_cap(p, x);
  7714. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  7715. } else if (is_type_union(t)) {
  7716. if (type_size_of(t) == 0) {
  7717. if (op_kind == Token_CmpEq) {
  7718. return lb_const_bool(p->module, t_llvm_bool, true);
  7719. } else if (op_kind == Token_NotEq) {
  7720. return lb_const_bool(p->module, t_llvm_bool, false);
  7721. }
  7722. } else {
  7723. lbValue tag = lb_emit_union_tag_value(p, x);
  7724. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  7725. }
  7726. } else if (is_type_typeid(t)) {
  7727. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  7728. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  7729. } else if (is_type_bit_field(t)) {
  7730. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7731. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7732. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7733. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7734. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7735. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7736. return res;
  7737. } else if (is_type_soa_struct(t)) {
  7738. Type *bt = base_type(t);
  7739. if (bt->Struct.soa_kind == StructSoa_Slice) {
  7740. lbValue len = lb_soa_struct_len(p, x);
  7741. if (op_kind == Token_CmpEq) {
  7742. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7743. return res;
  7744. } else if (op_kind == Token_NotEq) {
  7745. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7746. return res;
  7747. }
  7748. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  7749. lbValue cap = lb_soa_struct_cap(p, x);
  7750. if (op_kind == Token_CmpEq) {
  7751. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7752. return res;
  7753. } else if (op_kind == Token_NotEq) {
  7754. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7755. return res;
  7756. }
  7757. }
  7758. } else if (is_type_struct(t) && type_has_nil(t)) {
  7759. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7760. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7761. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7762. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7763. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7764. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7765. return res;
  7766. }
  7767. return {};
  7768. }
  7769. lbValue lb_get_compare_proc_for_type(lbModule *m, Type *type) {
  7770. Type *original_type = type;
  7771. type = base_type(type);
  7772. GB_ASSERT(type->kind == Type_Struct);
  7773. type_set_offsets(type);
  7774. Type *pt = alloc_type_pointer(type);
  7775. LLVMTypeRef ptr_type = lb_type(m, pt);
  7776. auto key = hash_type(type);
  7777. lbProcedure **found = map_get(&m->compare_procs, key);
  7778. lbProcedure *compare_proc = nullptr;
  7779. if (found) {
  7780. compare_proc = *found;
  7781. } else {
  7782. static Type *proc_type = nullptr;
  7783. if (proc_type == nullptr) {
  7784. Type *args[2] = {t_rawptr, t_rawptr};
  7785. proc_type = alloc_type_proc_from_types(args, 2, t_bool, false, ProcCC_Contextless);
  7786. set_procedure_abi_types(proc_type);
  7787. }
  7788. static u32 proc_index = 0;
  7789. char buf[16] = {};
  7790. isize n = gb_snprintf(buf, 16, "__$cmp%u", ++proc_index);
  7791. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  7792. String proc_name = make_string_c(str);
  7793. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, proc_type);
  7794. lb_begin_procedure_body(p);
  7795. LLVMValueRef x = LLVMGetParam(p->value, 0);
  7796. LLVMValueRef y = LLVMGetParam(p->value, 1);
  7797. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  7798. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  7799. lbValue lhs = {x, pt};
  7800. lbValue rhs = {y, pt};
  7801. lbBlock *block_false = lb_create_block(p, "bfalse");
  7802. lbValue res = lb_const_bool(m, t_bool, true);
  7803. for_array(i, type->Struct.fields) {
  7804. lbBlock *next_block = lb_create_block(p, "btrue");
  7805. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  7806. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  7807. lbValue left = lb_emit_load(p, pleft);
  7808. lbValue right = lb_emit_load(p, pright);
  7809. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  7810. lb_emit_if(p, ok, next_block, block_false);
  7811. lb_emit_jump(p, next_block);
  7812. lb_start_block(p, next_block);
  7813. }
  7814. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  7815. lb_start_block(p, block_false);
  7816. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  7817. lb_end_procedure_body(p);
  7818. map_set(&m->compare_procs, key, p);
  7819. compare_proc = p;
  7820. }
  7821. GB_ASSERT(compare_proc != nullptr);
  7822. return {compare_proc->value, compare_proc->type};
  7823. }
  7824. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  7825. Type *a = core_type(left.type);
  7826. Type *b = core_type(right.type);
  7827. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  7828. lbValue nil_check = {};
  7829. if (is_type_untyped_nil(left.type)) {
  7830. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  7831. } else if (is_type_untyped_nil(right.type)) {
  7832. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  7833. }
  7834. if (nil_check.value != nullptr) {
  7835. return nil_check;
  7836. }
  7837. if (are_types_identical(a, b)) {
  7838. // NOTE(bill): No need for a conversion
  7839. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  7840. left = lb_emit_conv(p, left, right.type);
  7841. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  7842. right = lb_emit_conv(p, right, left.type);
  7843. } else {
  7844. Type *lt = left.type;
  7845. Type *rt = right.type;
  7846. if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  7847. Type *blt = base_type(lt);
  7848. Type *brt = base_type(rt);
  7849. GB_ASSERT(is_type_bit_field_value(blt));
  7850. GB_ASSERT(is_type_bit_field_value(brt));
  7851. i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits);
  7852. i64 bytes = bits / 8;
  7853. switch (bytes) {
  7854. case 1:
  7855. left = lb_emit_conv(p, left, t_u8);
  7856. right = lb_emit_conv(p, right, t_u8);
  7857. break;
  7858. case 2:
  7859. left = lb_emit_conv(p, left, t_u16);
  7860. right = lb_emit_conv(p, right, t_u16);
  7861. break;
  7862. case 4:
  7863. left = lb_emit_conv(p, left, t_u32);
  7864. right = lb_emit_conv(p, right, t_u32);
  7865. break;
  7866. case 8:
  7867. left = lb_emit_conv(p, left, t_u64);
  7868. right = lb_emit_conv(p, right, t_u64);
  7869. break;
  7870. default: GB_PANIC("Unknown integer size"); break;
  7871. }
  7872. }
  7873. lt = left.type;
  7874. rt = right.type;
  7875. i64 ls = type_size_of(lt);
  7876. i64 rs = type_size_of(rt);
  7877. if (ls < rs) {
  7878. left = lb_emit_conv(p, left, rt);
  7879. } else if (ls > rs) {
  7880. right = lb_emit_conv(p, right, lt);
  7881. } else {
  7882. right = lb_emit_conv(p, right, lt);
  7883. }
  7884. }
  7885. if (is_type_array(a)) {
  7886. Type *tl = base_type(a);
  7887. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  7888. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  7889. TokenKind cmp_op = Token_And;
  7890. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  7891. if (op_kind == Token_NotEq) {
  7892. res = lb_const_bool(p->module, t_llvm_bool, false);
  7893. cmp_op = Token_Or;
  7894. } else if (op_kind == Token_CmpEq) {
  7895. res = lb_const_bool(p->module, t_llvm_bool, true);
  7896. cmp_op = Token_And;
  7897. }
  7898. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  7899. i32 count = cast(i32)tl->Array.count;
  7900. if (inline_array_arith) {
  7901. // inline
  7902. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7903. lb_addr_store(p, val, res);
  7904. for (i32 i = 0; i < count; i++) {
  7905. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  7906. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  7907. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7908. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7909. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7910. }
  7911. return lb_addr_load(p, val);
  7912. } else {
  7913. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  7914. // TODO(bill): Test to see if this is actually faster!!!!
  7915. auto args = array_make<lbValue>(permanent_allocator(), 3);
  7916. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7917. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  7918. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  7919. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  7920. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  7921. return lb_emit_conv(p, res, t_bool);
  7922. } else {
  7923. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7924. lb_addr_store(p, val, res);
  7925. auto loop_data = lb_loop_start(p, count, t_i32);
  7926. {
  7927. lbValue i = loop_data.idx;
  7928. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  7929. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  7930. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7931. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7932. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7933. }
  7934. lb_loop_end(p, loop_data);
  7935. return lb_addr_load(p, val);
  7936. }
  7937. }
  7938. }
  7939. if (is_type_struct(a) && is_type_comparable(a)) {
  7940. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  7941. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  7942. lbValue res = {};
  7943. if (is_type_simple_compare(a)) {
  7944. // TODO(bill): Test to see if this is actually faster!!!!
  7945. auto args = array_make<lbValue>(permanent_allocator(), 3);
  7946. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  7947. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  7948. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  7949. res = lb_emit_runtime_call(p, "memory_equal", args);
  7950. } else {
  7951. lbValue value = lb_get_compare_proc_for_type(p->module, a);
  7952. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7953. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  7954. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  7955. res = lb_emit_call(p, value, args);
  7956. }
  7957. if (op_kind == Token_NotEq) {
  7958. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  7959. }
  7960. return res;
  7961. }
  7962. if (is_type_string(a)) {
  7963. if (is_type_cstring(a)) {
  7964. left = lb_emit_conv(p, left, t_string);
  7965. right = lb_emit_conv(p, right, t_string);
  7966. }
  7967. char const *runtime_procedure = nullptr;
  7968. switch (op_kind) {
  7969. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  7970. case Token_NotEq: runtime_procedure = "string_ne"; break;
  7971. case Token_Lt: runtime_procedure = "string_lt"; break;
  7972. case Token_Gt: runtime_procedure = "string_gt"; break;
  7973. case Token_LtEq: runtime_procedure = "string_le"; break;
  7974. case Token_GtEq: runtime_procedure = "string_gt"; break;
  7975. }
  7976. GB_ASSERT(runtime_procedure != nullptr);
  7977. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7978. args[0] = left;
  7979. args[1] = right;
  7980. return lb_emit_runtime_call(p, runtime_procedure, args);
  7981. }
  7982. if (is_type_complex(a)) {
  7983. char const *runtime_procedure = "";
  7984. i64 sz = 8*type_size_of(a);
  7985. switch (sz) {
  7986. case 64:
  7987. switch (op_kind) {
  7988. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  7989. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  7990. }
  7991. break;
  7992. case 128:
  7993. switch (op_kind) {
  7994. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  7995. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  7996. }
  7997. break;
  7998. }
  7999. GB_ASSERT(runtime_procedure != nullptr);
  8000. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8001. args[0] = left;
  8002. args[1] = right;
  8003. return lb_emit_runtime_call(p, runtime_procedure, args);
  8004. }
  8005. if (is_type_quaternion(a)) {
  8006. char const *runtime_procedure = "";
  8007. i64 sz = 8*type_size_of(a);
  8008. switch (sz) {
  8009. case 128:
  8010. switch (op_kind) {
  8011. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  8012. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  8013. }
  8014. break;
  8015. case 256:
  8016. switch (op_kind) {
  8017. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  8018. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  8019. }
  8020. break;
  8021. }
  8022. GB_ASSERT(runtime_procedure != nullptr);
  8023. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8024. args[0] = left;
  8025. args[1] = right;
  8026. return lb_emit_runtime_call(p, runtime_procedure, args);
  8027. }
  8028. if (is_type_bit_set(a)) {
  8029. switch (op_kind) {
  8030. case Token_Lt:
  8031. case Token_LtEq:
  8032. case Token_Gt:
  8033. case Token_GtEq:
  8034. {
  8035. Type *it = bit_set_to_int(a);
  8036. lbValue lhs = lb_emit_transmute(p, left, it);
  8037. lbValue rhs = lb_emit_transmute(p, right, it);
  8038. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  8039. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  8040. // (lhs & rhs) == lhs
  8041. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  8042. res.type = t_llvm_bool;
  8043. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  8044. // (lhs & rhs) == rhs
  8045. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  8046. res.type = t_llvm_bool;
  8047. }
  8048. // NOTE(bill): Strict subsets
  8049. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  8050. // res &~ (lhs == rhs)
  8051. lbValue eq = {};
  8052. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  8053. eq.type = t_llvm_bool;
  8054. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  8055. }
  8056. return res;
  8057. }
  8058. case Token_CmpEq:
  8059. case Token_NotEq:
  8060. {
  8061. LLVMIntPredicate pred = {};
  8062. switch (op_kind) {
  8063. case Token_CmpEq: pred = LLVMIntEQ; break;
  8064. case Token_NotEq: pred = LLVMIntNE; break;
  8065. }
  8066. lbValue res = {};
  8067. res.type = t_llvm_bool;
  8068. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8069. return res;
  8070. }
  8071. }
  8072. }
  8073. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  8074. Type *t = left.type;
  8075. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  8076. Type *platform_type = integer_endian_type_to_platform_type(t);
  8077. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  8078. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  8079. left = x;
  8080. right = y;
  8081. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  8082. Type *platform_type = integer_endian_type_to_platform_type(t);
  8083. lbValue x = lb_emit_conv(p, left, platform_type);
  8084. lbValue y = lb_emit_conv(p, right, platform_type);
  8085. left = x;
  8086. right = y;
  8087. }
  8088. }
  8089. a = core_type(left.type);
  8090. b = core_type(right.type);
  8091. lbValue res = {};
  8092. res.type = t_llvm_bool;
  8093. if (is_type_integer(a) ||
  8094. is_type_boolean(a) ||
  8095. is_type_pointer(a) ||
  8096. is_type_proc(a) ||
  8097. is_type_enum(a)) {
  8098. LLVMIntPredicate pred = {};
  8099. if (is_type_unsigned(left.type)) {
  8100. switch (op_kind) {
  8101. case Token_Gt: pred = LLVMIntUGT; break;
  8102. case Token_GtEq: pred = LLVMIntUGE; break;
  8103. case Token_Lt: pred = LLVMIntULT; break;
  8104. case Token_LtEq: pred = LLVMIntULE; break;
  8105. }
  8106. } else {
  8107. switch (op_kind) {
  8108. case Token_Gt: pred = LLVMIntSGT; break;
  8109. case Token_GtEq: pred = LLVMIntSGE; break;
  8110. case Token_Lt: pred = LLVMIntSLT; break;
  8111. case Token_LtEq: pred = LLVMIntSLE; break;
  8112. }
  8113. }
  8114. switch (op_kind) {
  8115. case Token_CmpEq: pred = LLVMIntEQ; break;
  8116. case Token_NotEq: pred = LLVMIntNE; break;
  8117. }
  8118. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8119. } else if (is_type_float(a)) {
  8120. LLVMRealPredicate pred = {};
  8121. switch (op_kind) {
  8122. case Token_CmpEq: pred = LLVMRealOEQ; break;
  8123. case Token_Gt: pred = LLVMRealOGT; break;
  8124. case Token_GtEq: pred = LLVMRealOGE; break;
  8125. case Token_Lt: pred = LLVMRealOLT; break;
  8126. case Token_LtEq: pred = LLVMRealOLE; break;
  8127. case Token_NotEq: pred = LLVMRealONE; break;
  8128. }
  8129. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  8130. } else if (is_type_typeid(a)) {
  8131. LLVMIntPredicate pred = {};
  8132. switch (op_kind) {
  8133. case Token_Gt: pred = LLVMIntUGT; break;
  8134. case Token_GtEq: pred = LLVMIntUGE; break;
  8135. case Token_Lt: pred = LLVMIntULT; break;
  8136. case Token_LtEq: pred = LLVMIntULE; break;
  8137. case Token_CmpEq: pred = LLVMIntEQ; break;
  8138. case Token_NotEq: pred = LLVMIntNE; break;
  8139. }
  8140. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  8141. } else {
  8142. 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)));
  8143. }
  8144. return res;
  8145. }
  8146. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  8147. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  8148. if (found != nullptr) {
  8149. lbValue value = {};
  8150. value.value = (*found)->value;
  8151. value.type = (*found)->type;
  8152. return value;
  8153. }
  8154. ast_node(pl, ProcLit, expr);
  8155. // NOTE(bill): Generate a new name
  8156. // parent$count
  8157. isize name_len = prefix_name.len + 1 + 8 + 1;
  8158. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  8159. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  8160. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  8161. String name = make_string((u8 *)name_text, name_len-1);
  8162. Type *type = type_of_expr(expr);
  8163. set_procedure_abi_types(type);
  8164. Token token = {};
  8165. token.pos = ast_token(expr).pos;
  8166. token.kind = Token_Ident;
  8167. token.string = name;
  8168. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  8169. e->decl_info = pl->decl;
  8170. lbProcedure *p = lb_create_procedure(m, e);
  8171. lbValue value = {};
  8172. value.value = p->value;
  8173. value.type = p->type;
  8174. array_add(&m->procedures_to_generate, p);
  8175. if (parent != nullptr) {
  8176. array_add(&parent->children, p);
  8177. } else {
  8178. string_map_set(&m->members, name, value);
  8179. }
  8180. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  8181. return value;
  8182. }
  8183. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  8184. lbModule *m = p->module;
  8185. Type *src_type = value.type;
  8186. bool is_ptr = is_type_pointer(src_type);
  8187. bool is_tuple = true;
  8188. Type *tuple = type;
  8189. if (type->kind != Type_Tuple) {
  8190. is_tuple = false;
  8191. tuple = make_optional_ok_type(type);
  8192. }
  8193. lbAddr v = lb_add_local_generated(p, tuple, true);
  8194. if (is_ptr) {
  8195. value = lb_emit_load(p, value);
  8196. }
  8197. Type *src = base_type(type_deref(src_type));
  8198. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  8199. Type *dst = tuple->Tuple.variables[0]->type;
  8200. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  8201. lbValue tag = {};
  8202. lbValue dst_tag = {};
  8203. lbValue cond = {};
  8204. lbValue data = {};
  8205. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8206. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8207. if (is_type_union_maybe_pointer(src)) {
  8208. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8209. } else {
  8210. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  8211. dst_tag = lb_const_union_tag(m, src, dst);
  8212. }
  8213. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8214. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8215. if (data.value != nullptr) {
  8216. GB_ASSERT(is_type_union_maybe_pointer(src));
  8217. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8218. } else {
  8219. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8220. }
  8221. lb_emit_if(p, cond, ok_block, end_block);
  8222. lb_start_block(p, ok_block);
  8223. if (data.value == nullptr) {
  8224. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8225. }
  8226. lb_emit_store(p, gep0, data);
  8227. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8228. lb_emit_jump(p, end_block);
  8229. lb_start_block(p, end_block);
  8230. if (!is_tuple) {
  8231. if (do_conversion_check) {
  8232. // NOTE(bill): Panic on invalid conversion
  8233. Type *dst_type = tuple->Tuple.variables[0]->type;
  8234. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8235. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8236. args[0] = ok;
  8237. args[1] = lb_const_string(m, pos.file);
  8238. args[2] = lb_const_int(m, t_int, pos.line);
  8239. args[3] = lb_const_int(m, t_int, pos.column);
  8240. args[4] = lb_typeid(m, src_type);
  8241. args[5] = lb_typeid(m, dst_type);
  8242. lb_emit_runtime_call(p, "type_assertion_check", args);
  8243. }
  8244. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8245. }
  8246. return lb_addr_load(p, v);
  8247. }
  8248. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8249. lbModule *m = p->module;
  8250. Type *src_type = value.type;
  8251. if (is_type_pointer(src_type)) {
  8252. value = lb_emit_load(p, value);
  8253. }
  8254. bool is_tuple = true;
  8255. Type *tuple = type;
  8256. if (type->kind != Type_Tuple) {
  8257. is_tuple = false;
  8258. tuple = make_optional_ok_type(type);
  8259. }
  8260. Type *dst_type = tuple->Tuple.variables[0]->type;
  8261. lbAddr v = lb_add_local_generated(p, tuple, true);
  8262. lbValue dst_typeid = lb_typeid(m, dst_type);
  8263. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  8264. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  8265. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  8266. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  8267. lb_emit_if(p, cond, ok_block, end_block);
  8268. lb_start_block(p, ok_block);
  8269. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8270. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8271. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  8272. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  8273. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  8274. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8275. lb_emit_jump(p, end_block);
  8276. lb_start_block(p, end_block);
  8277. if (!is_tuple) {
  8278. // NOTE(bill): Panic on invalid conversion
  8279. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8280. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8281. args[0] = ok;
  8282. args[1] = lb_const_string(m, pos.file);
  8283. args[2] = lb_const_int(m, t_int, pos.line);
  8284. args[3] = lb_const_int(m, t_int, pos.column);
  8285. args[4] = any_typeid;
  8286. args[5] = dst_typeid;
  8287. lb_emit_runtime_call(p, "type_assertion_check", args);
  8288. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  8289. }
  8290. return v;
  8291. }
  8292. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8293. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  8294. }
  8295. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  8296. lbModule *m = p->module;
  8297. u64 prev_state_flags = p->module->state_flags;
  8298. defer (p->module->state_flags = prev_state_flags);
  8299. if (expr->state_flags != 0) {
  8300. u64 in = expr->state_flags;
  8301. u64 out = p->module->state_flags;
  8302. if (in & StateFlag_bounds_check) {
  8303. out |= StateFlag_bounds_check;
  8304. out &= ~StateFlag_no_bounds_check;
  8305. } else if (in & StateFlag_no_bounds_check) {
  8306. out |= StateFlag_no_bounds_check;
  8307. out &= ~StateFlag_bounds_check;
  8308. }
  8309. p->module->state_flags = out;
  8310. }
  8311. expr = unparen_expr(expr);
  8312. TypeAndValue tv = type_and_value_of_expr(expr);
  8313. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "%s", expr_to_string(expr));
  8314. GB_ASSERT(tv.mode != Addressing_Type);
  8315. if (tv.value.kind != ExactValue_Invalid) {
  8316. // NOTE(bill): Short on constant values
  8317. return lb_const_value(p->module, tv.type, tv.value);
  8318. }
  8319. switch (expr->kind) {
  8320. case_ast_node(bl, BasicLit, expr);
  8321. TokenPos pos = bl->token.pos;
  8322. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  8323. case_end;
  8324. case_ast_node(bd, BasicDirective, expr);
  8325. TokenPos pos = bd->token.pos;
  8326. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  8327. case_end;
  8328. case_ast_node(i, Implicit, expr);
  8329. return lb_addr_load(p, lb_build_addr(p, expr));
  8330. case_end;
  8331. case_ast_node(u, Undef, expr)
  8332. lbValue res = {};
  8333. if (is_type_untyped(tv.type)) {
  8334. res.value = nullptr;
  8335. res.type = t_untyped_undef;
  8336. } else {
  8337. res.value = LLVMGetUndef(lb_type(m, tv.type));
  8338. res.type = tv.type;
  8339. }
  8340. return res;
  8341. case_end;
  8342. case_ast_node(i, Ident, expr);
  8343. Entity *e = entity_from_expr(expr);
  8344. e = strip_entity_wrapping(e);
  8345. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  8346. if (e->kind == Entity_Builtin) {
  8347. Token token = ast_token(expr);
  8348. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  8349. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  8350. LIT(token.pos.file), token.pos.line, token.pos.column);
  8351. return {};
  8352. } else if (e->kind == Entity_Nil) {
  8353. lbValue res = {};
  8354. res.value = nullptr;
  8355. res.type = e->type;
  8356. return res;
  8357. }
  8358. GB_ASSERT(e->kind != Entity_ProcGroup);
  8359. auto *found = map_get(&p->module->values, hash_entity(e));
  8360. if (found) {
  8361. auto v = *found;
  8362. // NOTE(bill): This is because pointers are already pointers in LLVM
  8363. if (is_type_proc(v.type)) {
  8364. return v;
  8365. }
  8366. return lb_emit_load(p, v);
  8367. } else if (e != nullptr && e->kind == Entity_Variable) {
  8368. return lb_addr_load(p, lb_build_addr(p, expr));
  8369. }
  8370. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  8371. String pkg = {};
  8372. if (e->pkg) {
  8373. pkg = e->pkg->name;
  8374. }
  8375. 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);
  8376. return {};
  8377. case_end;
  8378. case_ast_node(de, DerefExpr, expr);
  8379. return lb_addr_load(p, lb_build_addr(p, expr));
  8380. case_end;
  8381. case_ast_node(se, SelectorExpr, expr);
  8382. TypeAndValue tav = type_and_value_of_expr(expr);
  8383. GB_ASSERT(tav.mode != Addressing_Invalid);
  8384. return lb_addr_load(p, lb_build_addr(p, expr));
  8385. case_end;
  8386. case_ast_node(ise, ImplicitSelectorExpr, expr);
  8387. TypeAndValue tav = type_and_value_of_expr(expr);
  8388. GB_ASSERT(tav.mode == Addressing_Constant);
  8389. return lb_const_value(p->module, tv.type, tv.value);
  8390. case_end;
  8391. case_ast_node(se, SelectorCallExpr, expr);
  8392. GB_ASSERT(se->modified_call);
  8393. TypeAndValue tav = type_and_value_of_expr(expr);
  8394. GB_ASSERT(tav.mode != Addressing_Invalid);
  8395. return lb_build_expr(p, se->call);
  8396. case_end;
  8397. case_ast_node(te, TernaryExpr, expr);
  8398. LLVMValueRef incoming_values[2] = {};
  8399. LLVMBasicBlockRef incoming_blocks[2] = {};
  8400. GB_ASSERT(te->y != nullptr);
  8401. lbBlock *then = lb_create_block(p, "if.then");
  8402. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8403. lbBlock *else_ = lb_create_block(p, "if.else");
  8404. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8405. lb_start_block(p, then);
  8406. Type *type = default_type(type_of_expr(expr));
  8407. lb_open_scope(p);
  8408. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8409. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8410. lb_emit_jump(p, done);
  8411. lb_start_block(p, else_);
  8412. lb_open_scope(p);
  8413. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8414. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8415. lb_emit_jump(p, done);
  8416. lb_start_block(p, done);
  8417. lbValue res = {};
  8418. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8419. res.type = type;
  8420. GB_ASSERT(p->curr_block->preds.count >= 2);
  8421. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8422. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8423. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8424. return res;
  8425. case_end;
  8426. case_ast_node(te, TernaryIfExpr, expr);
  8427. LLVMValueRef incoming_values[2] = {};
  8428. LLVMBasicBlockRef incoming_blocks[2] = {};
  8429. GB_ASSERT(te->y != nullptr);
  8430. lbBlock *then = lb_create_block(p, "if.then");
  8431. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8432. lbBlock *else_ = lb_create_block(p, "if.else");
  8433. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8434. lb_start_block(p, then);
  8435. Type *type = default_type(type_of_expr(expr));
  8436. lb_open_scope(p);
  8437. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8438. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8439. lb_emit_jump(p, done);
  8440. lb_start_block(p, else_);
  8441. lb_open_scope(p);
  8442. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8443. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8444. lb_emit_jump(p, done);
  8445. lb_start_block(p, done);
  8446. lbValue res = {};
  8447. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8448. res.type = type;
  8449. GB_ASSERT(p->curr_block->preds.count >= 2);
  8450. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8451. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8452. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8453. return res;
  8454. case_end;
  8455. case_ast_node(te, TernaryWhenExpr, expr);
  8456. TypeAndValue tav = type_and_value_of_expr(te->cond);
  8457. GB_ASSERT(tav.mode == Addressing_Constant);
  8458. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  8459. if (tav.value.value_bool) {
  8460. return lb_build_expr(p, te->x);
  8461. } else {
  8462. return lb_build_expr(p, te->y);
  8463. }
  8464. case_end;
  8465. case_ast_node(ta, TypeAssertion, expr);
  8466. TokenPos pos = ast_token(expr).pos;
  8467. Type *type = tv.type;
  8468. lbValue e = lb_build_expr(p, ta->expr);
  8469. Type *t = type_deref(e.type);
  8470. if (is_type_union(t)) {
  8471. return lb_emit_union_cast(p, e, type, pos);
  8472. } else if (is_type_any(t)) {
  8473. return lb_emit_any_cast(p, e, type, pos);
  8474. } else {
  8475. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8476. }
  8477. case_end;
  8478. case_ast_node(tc, TypeCast, expr);
  8479. lbValue e = lb_build_expr(p, tc->expr);
  8480. switch (tc->token.kind) {
  8481. case Token_cast:
  8482. return lb_emit_conv(p, e, tv.type);
  8483. case Token_transmute:
  8484. return lb_emit_transmute(p, e, tv.type);
  8485. }
  8486. GB_PANIC("Invalid AST TypeCast");
  8487. case_end;
  8488. case_ast_node(ac, AutoCast, expr);
  8489. return lb_build_expr(p, ac->expr);
  8490. case_end;
  8491. case_ast_node(ue, UnaryExpr, expr);
  8492. switch (ue->op.kind) {
  8493. case Token_And: {
  8494. Ast *ue_expr = unparen_expr(ue->expr);
  8495. if (ue_expr->kind == Ast_CompoundLit) {
  8496. lbValue v = lb_build_expr(p, ue->expr);
  8497. Type *type = v.type;
  8498. lbAddr addr = {};
  8499. if (p->is_startup) {
  8500. addr = lb_add_global_generated(p->module, type, v);
  8501. } else {
  8502. addr = lb_add_local_generated(p, type, false);
  8503. }
  8504. lb_addr_store(p, addr, v);
  8505. return addr.addr;
  8506. } else if (ue_expr->kind == Ast_TypeAssertion) {
  8507. GB_ASSERT(is_type_pointer(tv.type));
  8508. ast_node(ta, TypeAssertion, ue_expr);
  8509. TokenPos pos = ast_token(expr).pos;
  8510. Type *type = type_of_expr(ue_expr);
  8511. GB_ASSERT(!is_type_tuple(type));
  8512. lbValue e = lb_build_expr(p, ta->expr);
  8513. Type *t = type_deref(e.type);
  8514. if (is_type_union(t)) {
  8515. lbValue v = e;
  8516. if (!is_type_pointer(v.type)) {
  8517. v = lb_address_from_load_or_generate_local(p, v);
  8518. }
  8519. Type *src_type = type_deref(v.type);
  8520. Type *dst_type = type;
  8521. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  8522. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  8523. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  8524. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8525. args[0] = ok;
  8526. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8527. args[2] = lb_const_int(p->module, t_int, pos.line);
  8528. args[3] = lb_const_int(p->module, t_int, pos.column);
  8529. args[4] = lb_typeid(p->module, src_type);
  8530. args[5] = lb_typeid(p->module, dst_type);
  8531. lb_emit_runtime_call(p, "type_assertion_check", args);
  8532. lbValue data_ptr = v;
  8533. return lb_emit_conv(p, data_ptr, tv.type);
  8534. } else if (is_type_any(t)) {
  8535. lbValue v = e;
  8536. if (is_type_pointer(v.type)) {
  8537. v = lb_emit_load(p, v);
  8538. }
  8539. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  8540. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  8541. lbValue id = lb_typeid(p->module, type);
  8542. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  8543. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8544. args[0] = ok;
  8545. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8546. args[2] = lb_const_int(p->module, t_int, pos.line);
  8547. args[3] = lb_const_int(p->module, t_int, pos.column);
  8548. args[4] = any_id;
  8549. args[5] = id;
  8550. lb_emit_runtime_call(p, "type_assertion_check", args);
  8551. return lb_emit_conv(p, data_ptr, tv.type);
  8552. } else {
  8553. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  8554. }
  8555. }
  8556. return lb_build_addr_ptr(p, ue->expr);
  8557. }
  8558. default:
  8559. {
  8560. lbValue v = lb_build_expr(p, ue->expr);
  8561. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  8562. }
  8563. }
  8564. case_end;
  8565. case_ast_node(be, BinaryExpr, expr);
  8566. return lb_build_binary_expr(p, expr);
  8567. case_end;
  8568. case_ast_node(pl, ProcLit, expr);
  8569. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  8570. case_end;
  8571. case_ast_node(cl, CompoundLit, expr);
  8572. return lb_addr_load(p, lb_build_addr(p, expr));
  8573. case_end;
  8574. case_ast_node(ce, CallExpr, expr);
  8575. lbValue res = lb_build_call_expr(p, expr);
  8576. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  8577. GB_ASSERT(is_type_tuple(res.type));
  8578. GB_ASSERT(res.type->Tuple.variables.count == 2);
  8579. return lb_emit_struct_ev(p, res, 0);
  8580. }
  8581. return res;
  8582. case_end;
  8583. case_ast_node(se, SliceExpr, expr);
  8584. return lb_addr_load(p, lb_build_addr(p, expr));
  8585. case_end;
  8586. case_ast_node(ie, IndexExpr, expr);
  8587. return lb_addr_load(p, lb_build_addr(p, expr));
  8588. case_end;
  8589. case_ast_node(ia, InlineAsmExpr, expr);
  8590. Type *t = type_of_expr(expr);
  8591. GB_ASSERT(is_type_asm_proc(t));
  8592. String asm_string = {};
  8593. String constraints_string = {};
  8594. TypeAndValue tav;
  8595. tav = type_and_value_of_expr(ia->asm_string);
  8596. GB_ASSERT(is_type_string(tav.type));
  8597. GB_ASSERT(tav.value.kind == ExactValue_String);
  8598. asm_string = tav.value.value_string;
  8599. tav = type_and_value_of_expr(ia->constraints_string);
  8600. GB_ASSERT(is_type_string(tav.type));
  8601. GB_ASSERT(tav.value.kind == ExactValue_String);
  8602. constraints_string = tav.value.value_string;
  8603. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  8604. switch (ia->dialect) {
  8605. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  8606. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  8607. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  8608. default: GB_PANIC("Unhandled inline asm dialect"); break;
  8609. }
  8610. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  8611. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8612. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  8613. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  8614. ia->has_side_effects, ia->is_align_stack, dialect
  8615. );
  8616. GB_ASSERT(the_asm != nullptr);
  8617. return {the_asm, t};
  8618. case_end;
  8619. }
  8620. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  8621. return {};
  8622. }
  8623. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  8624. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  8625. String name = e->token.string;
  8626. Entity *parent = e->using_parent;
  8627. Selection sel = lookup_field(parent->type, name, false);
  8628. GB_ASSERT(sel.entity != nullptr);
  8629. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  8630. lbValue v = {};
  8631. if (pv != nullptr) {
  8632. v = *pv;
  8633. } else {
  8634. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  8635. v = lb_build_addr_ptr(p, e->using_expr);
  8636. }
  8637. GB_ASSERT(v.value != nullptr);
  8638. GB_ASSERT(parent->type == type_deref(v.type));
  8639. return lb_emit_deep_field_gep(p, v, sel);
  8640. }
  8641. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  8642. GB_ASSERT(e != nullptr);
  8643. if (e->kind == Entity_Constant) {
  8644. Type *t = default_type(type_of_expr(expr));
  8645. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  8646. lbAddr g = lb_add_global_generated(p->module, t, v);
  8647. return g;
  8648. }
  8649. lbValue v = {};
  8650. lbValue *found = map_get(&p->module->values, hash_entity(e));
  8651. if (found) {
  8652. v = *found;
  8653. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  8654. // NOTE(bill): Calculate the using variable every time
  8655. v = lb_get_using_variable(p, e);
  8656. }
  8657. if (v.value == nullptr) {
  8658. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  8659. LIT(p->name),
  8660. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  8661. GB_PANIC("Unknown value");
  8662. }
  8663. return lb_addr(v);
  8664. }
  8665. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  8666. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  8667. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  8668. map_type = base_type(map_type);
  8669. GB_ASSERT(map_type->kind == Type_Map);
  8670. Type *key_type = map_type->Map.key;
  8671. Type *val_type = map_type->Map.value;
  8672. // NOTE(bill): Removes unnecessary allocation if split gep
  8673. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  8674. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  8675. lb_emit_store(p, gep0, m);
  8676. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_const_bool(p->module, t_bool, is_type_string(key_type)));
  8677. i64 entry_size = type_size_of (map_type->Map.entry_type);
  8678. i64 entry_align = type_align_of (map_type->Map.entry_type);
  8679. i64 value_offset = type_offset_of(map_type->Map.entry_type, 2);
  8680. i64 value_size = type_size_of (map_type->Map.value);
  8681. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  8682. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  8683. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, value_offset));
  8684. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, value_size));
  8685. return lb_addr_load(p, h);
  8686. }
  8687. lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) {
  8688. Type *hash_type = t_u64;
  8689. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  8690. lbValue vp = lb_addr_get_ptr(p, v);
  8691. Type *t = base_type(key.type);
  8692. key = lb_emit_conv(p, key, key_type);
  8693. if (is_type_string(t)) {
  8694. lbValue str = lb_emit_conv(p, key, t_string);
  8695. lbValue hashed_str = {};
  8696. if (lb_is_const(str)) {
  8697. String v = lb_get_const_string(p->module, str);
  8698. u64 hs = fnv64a(v.text, v.len);
  8699. hashed_str = lb_const_int(p->module, t_u64, hs);
  8700. } else {
  8701. auto args = array_make<lbValue>(permanent_allocator(), 1);
  8702. args[0] = str;
  8703. hashed_str = lb_emit_runtime_call(p, "default_hash_string", args);
  8704. }
  8705. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_str);
  8706. lbValue key_data = lb_emit_struct_ep(p, vp, 1);
  8707. key_data = lb_emit_conv(p, key_data, alloc_type_pointer(key_type));
  8708. lb_emit_store(p, key_data, str);
  8709. } else {
  8710. i64 sz = type_size_of(t);
  8711. GB_ASSERT(sz <= 8);
  8712. if (sz != 0) {
  8713. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8714. args[0] = lb_address_from_load_or_generate_local(p, key);
  8715. args[1] = lb_const_int(p->module, t_int, sz);
  8716. lbValue hash = lb_emit_runtime_call(p, "default_hash_ptr", args);
  8717. lbValue hash_ptr = lb_emit_struct_ep(p, vp, 0);
  8718. lbValue key_data = lb_emit_struct_ep(p, vp, 1);
  8719. key_data = lb_emit_conv(p, key_data, alloc_type_pointer(key_type));
  8720. lb_emit_store(p, hash_ptr, hash);
  8721. lb_emit_store(p, key_data, key);
  8722. }
  8723. }
  8724. return lb_addr_load(p, v);
  8725. }
  8726. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  8727. lbValue map_key, lbValue map_value, Ast *node) {
  8728. map_type = base_type(map_type);
  8729. GB_ASSERT(map_type->kind == Type_Map);
  8730. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  8731. lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key);
  8732. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  8733. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  8734. lb_addr_store(p, value_addr, v);
  8735. auto args = array_make<lbValue>(permanent_allocator(), 4);
  8736. args[0] = h;
  8737. args[1] = key;
  8738. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  8739. args[3] = lb_emit_source_code_location(p, node);
  8740. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  8741. }
  8742. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  8743. expr = unparen_expr(expr);
  8744. switch (expr->kind) {
  8745. case_ast_node(i, Implicit, expr);
  8746. lbAddr v = {};
  8747. switch (i->kind) {
  8748. case Token_context:
  8749. v = lb_find_or_generate_context_ptr(p);
  8750. break;
  8751. }
  8752. GB_ASSERT(v.addr.value != nullptr);
  8753. return v;
  8754. case_end;
  8755. case_ast_node(i, Ident, expr);
  8756. if (is_blank_ident(expr)) {
  8757. lbAddr val = {};
  8758. return val;
  8759. }
  8760. String name = i->token.string;
  8761. Entity *e = entity_of_node(expr);
  8762. return lb_build_addr_from_entity(p, e, expr);
  8763. case_end;
  8764. case_ast_node(se, SelectorExpr, expr);
  8765. Ast *sel = unparen_expr(se->selector);
  8766. if (sel->kind == Ast_Ident) {
  8767. String selector = sel->Ident.token.string;
  8768. TypeAndValue tav = type_and_value_of_expr(se->expr);
  8769. if (tav.mode == Addressing_Invalid) {
  8770. // NOTE(bill): Imports
  8771. Entity *imp = entity_of_node(se->expr);
  8772. if (imp != nullptr) {
  8773. GB_ASSERT(imp->kind == Entity_ImportName);
  8774. }
  8775. return lb_build_addr(p, unparen_expr(se->selector));
  8776. }
  8777. Type *type = base_type(tav.type);
  8778. if (tav.mode == Addressing_Type) { // Addressing_Type
  8779. Selection sel = lookup_field(type, selector, true);
  8780. Entity *e = sel.entity;
  8781. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  8782. GB_ASSERT(e->flags & EntityFlag_TypeField);
  8783. String name = e->token.string;
  8784. /*if (name == "names") {
  8785. lbValue ti_ptr = lb_type_info(m, type);
  8786. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  8787. lbValue names_ptr = nullptr;
  8788. if (is_type_enum(type)) {
  8789. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  8790. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  8791. } else if (type->kind == Type_Struct) {
  8792. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  8793. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  8794. }
  8795. return ir_addr(names_ptr);
  8796. } else */{
  8797. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  8798. }
  8799. GB_PANIC("Unreachable");
  8800. }
  8801. Selection sel = lookup_field(type, selector, false);
  8802. GB_ASSERT(sel.entity != nullptr);
  8803. if (sel.entity->type->kind == Type_BitFieldValue) {
  8804. lbAddr addr = lb_build_addr(p, se->expr);
  8805. Type *bft = type_deref(lb_addr_type(addr));
  8806. if (sel.index.count == 1) {
  8807. GB_ASSERT(is_type_bit_field(bft));
  8808. i32 index = sel.index[0];
  8809. return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index);
  8810. } else {
  8811. Selection s = sel;
  8812. s.index.count--;
  8813. i32 index = s.index[s.index.count-1];
  8814. lbValue a = lb_addr_get_ptr(p, addr);
  8815. a = lb_emit_deep_field_gep(p, a, s);
  8816. return lb_addr_bit_field(a, index);
  8817. }
  8818. } else {
  8819. lbAddr addr = lb_build_addr(p, se->expr);
  8820. if (addr.kind == lbAddr_Map) {
  8821. lbValue v = lb_addr_load(p, addr);
  8822. lbValue a = lb_address_from_load_or_generate_local(p, v);
  8823. a = lb_emit_deep_field_gep(p, a, sel);
  8824. return lb_addr(a);
  8825. } else if (addr.kind == lbAddr_Context) {
  8826. GB_ASSERT(sel.index.count > 0);
  8827. if (addr.ctx.sel.index.count >= 0) {
  8828. sel = selection_combine(addr.ctx.sel, sel);
  8829. }
  8830. addr.ctx.sel = sel;
  8831. addr.kind = lbAddr_Context;
  8832. return addr;
  8833. } else if (addr.kind == lbAddr_SoaVariable) {
  8834. lbValue index = addr.soa.index;
  8835. i32 first_index = sel.index[0];
  8836. Selection sub_sel = sel;
  8837. sub_sel.index.data += 1;
  8838. sub_sel.index.count -= 1;
  8839. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  8840. Type *t = base_type(type_deref(addr.addr.type));
  8841. GB_ASSERT(is_type_soa_struct(t));
  8842. // TODO(bill): Bounds check
  8843. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  8844. lbValue len = lb_soa_struct_len(p, addr.addr);
  8845. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  8846. }
  8847. lbValue item = {};
  8848. if (t->Struct.soa_kind == StructSoa_Fixed) {
  8849. item = lb_emit_array_ep(p, arr, index);
  8850. } else {
  8851. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  8852. }
  8853. if (sub_sel.index.count > 0) {
  8854. item = lb_emit_deep_field_gep(p, item, sub_sel);
  8855. }
  8856. return lb_addr(item);
  8857. }
  8858. lbValue a = lb_addr_get_ptr(p, addr);
  8859. a = lb_emit_deep_field_gep(p, a, sel);
  8860. return lb_addr(a);
  8861. }
  8862. } else {
  8863. GB_PANIC("Unsupported selector expression");
  8864. }
  8865. case_end;
  8866. case_ast_node(se, SelectorCallExpr, expr);
  8867. GB_ASSERT(se->modified_call);
  8868. TypeAndValue tav = type_and_value_of_expr(expr);
  8869. GB_ASSERT(tav.mode != Addressing_Invalid);
  8870. return lb_build_addr(p, se->call);
  8871. case_end;
  8872. case_ast_node(ta, TypeAssertion, expr);
  8873. TokenPos pos = ast_token(expr).pos;
  8874. lbValue e = lb_build_expr(p, ta->expr);
  8875. Type *t = type_deref(e.type);
  8876. if (is_type_union(t)) {
  8877. Type *type = type_of_expr(expr);
  8878. lbAddr v = lb_add_local_generated(p, type, false);
  8879. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  8880. return v;
  8881. } else if (is_type_any(t)) {
  8882. Type *type = type_of_expr(expr);
  8883. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  8884. } else {
  8885. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8886. }
  8887. case_end;
  8888. case_ast_node(ue, UnaryExpr, expr);
  8889. switch (ue->op.kind) {
  8890. case Token_And: {
  8891. return lb_build_addr(p, ue->expr);
  8892. }
  8893. default:
  8894. GB_PANIC("Invalid unary expression for lb_build_addr");
  8895. }
  8896. case_end;
  8897. case_ast_node(be, BinaryExpr, expr);
  8898. lbValue v = lb_build_expr(p, expr);
  8899. Type *t = v.type;
  8900. if (is_type_pointer(t)) {
  8901. return lb_addr(v);
  8902. }
  8903. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  8904. case_end;
  8905. case_ast_node(ie, IndexExpr, expr);
  8906. Type *t = base_type(type_of_expr(ie->expr));
  8907. bool deref = is_type_pointer(t);
  8908. t = base_type(type_deref(t));
  8909. if (is_type_soa_struct(t)) {
  8910. // SOA STRUCTURES!!!!
  8911. lbValue val = lb_build_addr_ptr(p, ie->expr);
  8912. if (deref) {
  8913. val = lb_emit_load(p, val);
  8914. }
  8915. lbValue index = lb_build_expr(p, ie->index);
  8916. return lb_addr_soa_variable(val, index, ie->index);
  8917. }
  8918. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  8919. // SOA Structures for slices/dynamic arrays
  8920. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  8921. lbValue field = lb_build_expr(p, ie->expr);
  8922. lbValue index = lb_build_expr(p, ie->index);
  8923. if (!build_context.no_bounds_check) {
  8924. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  8925. // GB_ASSERT(LLVMIsALoadInst(field.value));
  8926. // lbValue a = {};
  8927. // a.value = LLVMGetOperand(field.value, 0);
  8928. // a.type = alloc_type_pointer(field.type);
  8929. // irInstr *b = &a->Instr;
  8930. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  8931. // lbValue base_struct = b->StructElementPtr.address;
  8932. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  8933. // lbValue len = ir_soa_struct_len(p, base_struct);
  8934. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8935. }
  8936. lbValue val = lb_emit_ptr_offset(p, field, index);
  8937. return lb_addr(val);
  8938. }
  8939. if (!is_type_indexable(t)) {
  8940. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8941. if (found != nullptr) {
  8942. if (found->kind == TypeAtomOp_index_get) {
  8943. return lb_build_addr(p, found->node);
  8944. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  8945. return lb_addr(lb_build_expr(p, found->node));
  8946. } else if (found->kind == TypeAtomOp_index_set) {
  8947. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  8948. if (deref) {
  8949. ptr = lb_emit_load(p, ptr);
  8950. }
  8951. lbAddr addr = {lbAddr_AtomOp_index_set};
  8952. addr.addr = ptr;
  8953. addr.index_set.index = lb_build_expr(p, ie->index);
  8954. addr.index_set.node = found->node;
  8955. return addr;
  8956. }
  8957. }
  8958. }
  8959. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  8960. if (is_type_map(t)) {
  8961. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  8962. if (deref) {
  8963. map_val = lb_emit_load(p, map_val);
  8964. }
  8965. lbValue key = lb_build_expr(p, ie->index);
  8966. key = lb_emit_conv(p, key, t->Map.key);
  8967. Type *result_type = type_of_expr(expr);
  8968. return lb_addr_map(map_val, key, t, result_type);
  8969. }
  8970. switch (t->kind) {
  8971. case Type_Array: {
  8972. lbValue array = {};
  8973. array = lb_build_addr_ptr(p, ie->expr);
  8974. if (deref) {
  8975. array = lb_emit_load(p, array);
  8976. }
  8977. lbValue index = lb_build_expr(p, ie->index);
  8978. index = lb_emit_conv(p, index, t_int);
  8979. lbValue elem = lb_emit_array_ep(p, array, index);
  8980. auto index_tv = type_and_value_of_expr(ie->index);
  8981. if (index_tv.mode != Addressing_Constant) {
  8982. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  8983. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8984. }
  8985. return lb_addr(elem);
  8986. }
  8987. case Type_EnumeratedArray: {
  8988. lbValue array = {};
  8989. array = lb_build_addr_ptr(p, ie->expr);
  8990. if (deref) {
  8991. array = lb_emit_load(p, array);
  8992. }
  8993. Type *index_type = t->EnumeratedArray.index;
  8994. auto index_tv = type_and_value_of_expr(ie->index);
  8995. lbValue index = {};
  8996. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  8997. if (index_tv.mode == Addressing_Constant) {
  8998. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  8999. index = lb_const_value(p->module, index_type, idx);
  9000. } else {
  9001. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9002. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  9003. }
  9004. } else {
  9005. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9006. }
  9007. lbValue elem = lb_emit_array_ep(p, array, index);
  9008. if (index_tv.mode != Addressing_Constant) {
  9009. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  9010. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9011. }
  9012. return lb_addr(elem);
  9013. }
  9014. case Type_Slice: {
  9015. lbValue slice = {};
  9016. slice = lb_build_expr(p, ie->expr);
  9017. if (deref) {
  9018. slice = lb_emit_load(p, slice);
  9019. }
  9020. lbValue elem = lb_slice_elem(p, slice);
  9021. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9022. lbValue len = lb_slice_len(p, slice);
  9023. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9024. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9025. return lb_addr(v);
  9026. }
  9027. case Type_RelativeSlice: {
  9028. lbAddr slice_addr = {};
  9029. if (deref) {
  9030. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  9031. } else {
  9032. slice_addr = lb_build_addr(p, ie->expr);
  9033. }
  9034. lbValue slice = lb_addr_load(p, slice_addr);
  9035. lbValue elem = lb_slice_elem(p, slice);
  9036. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9037. lbValue len = lb_slice_len(p, slice);
  9038. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9039. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9040. return lb_addr(v);
  9041. }
  9042. case Type_DynamicArray: {
  9043. lbValue dynamic_array = {};
  9044. dynamic_array = lb_build_expr(p, ie->expr);
  9045. if (deref) {
  9046. dynamic_array = lb_emit_load(p, dynamic_array);
  9047. }
  9048. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  9049. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  9050. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9051. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9052. lbValue v = lb_emit_ptr_offset(p, elem, index);
  9053. return lb_addr(v);
  9054. }
  9055. case Type_Basic: { // Basic_string
  9056. lbValue str;
  9057. lbValue elem;
  9058. lbValue len;
  9059. lbValue index;
  9060. str = lb_build_expr(p, ie->expr);
  9061. if (deref) {
  9062. str = lb_emit_load(p, str);
  9063. }
  9064. elem = lb_string_elem(p, str);
  9065. len = lb_string_len(p, str);
  9066. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  9067. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  9068. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  9069. }
  9070. }
  9071. case_end;
  9072. case_ast_node(se, SliceExpr, expr);
  9073. lbValue low = lb_const_int(p->module, t_int, 0);
  9074. lbValue high = {};
  9075. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  9076. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  9077. bool no_indices = se->low == nullptr && se->high == nullptr;
  9078. {
  9079. Type *type = base_type(type_of_expr(se->expr));
  9080. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  9081. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  9082. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  9083. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  9084. if (found) {
  9085. lbValue base = lb_build_expr(p, found->node);
  9086. Type *slice_type = base.type;
  9087. lbValue len = lb_slice_len(p, base);
  9088. if (high.value == nullptr) high = len;
  9089. if (!no_indices) {
  9090. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9091. }
  9092. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9093. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9094. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9095. lb_fill_slice(p, slice, elem, new_len);
  9096. return slice;
  9097. }
  9098. }
  9099. }
  9100. }
  9101. lbAddr addr = lb_build_addr(p, se->expr);
  9102. lbValue base = lb_addr_load(p, addr);
  9103. Type *type = base_type(base.type);
  9104. if (is_type_pointer(type)) {
  9105. type = base_type(type_deref(type));
  9106. addr = lb_addr(base);
  9107. base = lb_addr_load(p, addr);
  9108. }
  9109. switch (type->kind) {
  9110. case Type_Slice: {
  9111. Type *slice_type = type;
  9112. lbValue len = lb_slice_len(p, base);
  9113. if (high.value == nullptr) high = len;
  9114. if (!no_indices) {
  9115. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9116. }
  9117. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  9118. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9119. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9120. lb_fill_slice(p, slice, elem, new_len);
  9121. return slice;
  9122. }
  9123. case Type_RelativeSlice:
  9124. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  9125. break;
  9126. case Type_DynamicArray: {
  9127. Type *elem_type = type->DynamicArray.elem;
  9128. Type *slice_type = alloc_type_slice(elem_type);
  9129. lbValue len = lb_dynamic_array_len(p, base);
  9130. if (high.value == nullptr) high = len;
  9131. if (!no_indices) {
  9132. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9133. }
  9134. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  9135. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9136. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9137. lb_fill_slice(p, slice, elem, new_len);
  9138. return slice;
  9139. }
  9140. case Type_Array: {
  9141. Type *slice_type = alloc_type_slice(type->Array.elem);
  9142. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  9143. if (high.value == nullptr) high = len;
  9144. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  9145. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  9146. if (!low_const || !high_const) {
  9147. if (!no_indices) {
  9148. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9149. }
  9150. }
  9151. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  9152. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9153. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  9154. lb_fill_slice(p, slice, elem, new_len);
  9155. return slice;
  9156. }
  9157. case Type_Basic: {
  9158. GB_ASSERT(type == t_string);
  9159. lbValue len = lb_string_len(p, base);
  9160. if (high.value == nullptr) high = len;
  9161. if (!no_indices) {
  9162. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9163. }
  9164. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  9165. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9166. lbAddr str = lb_add_local_generated(p, t_string, false);
  9167. lb_fill_string(p, str, elem, new_len);
  9168. return str;
  9169. }
  9170. case Type_Struct:
  9171. if (is_type_soa_struct(type)) {
  9172. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  9173. if (high.value == nullptr) high = len;
  9174. if (!no_indices) {
  9175. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  9176. }
  9177. #if 1
  9178. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  9179. if (type->Struct.soa_kind == StructSoa_Fixed) {
  9180. i32 field_count = cast(i32)type->Struct.fields.count;
  9181. for (i32 i = 0; i < field_count; i++) {
  9182. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9183. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  9184. field_src = lb_emit_array_ep(p, field_src, low);
  9185. lb_emit_store(p, field_dst, field_src);
  9186. }
  9187. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9188. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9189. lb_emit_store(p, len_dst, new_len);
  9190. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  9191. if (no_indices) {
  9192. lb_addr_store(p, dst, base);
  9193. } else {
  9194. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  9195. for (i32 i = 0; i < field_count; i++) {
  9196. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9197. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9198. field_src = lb_emit_ptr_offset(p, field_src, low);
  9199. lb_emit_store(p, field_dst, field_src);
  9200. }
  9201. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9202. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9203. lb_emit_store(p, len_dst, new_len);
  9204. }
  9205. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9206. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9207. for (i32 i = 0; i < field_count; i++) {
  9208. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9209. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9210. field_src = lb_emit_ptr_offset(p, field_src, low);
  9211. lb_emit_store(p, field_dst, field_src);
  9212. }
  9213. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9214. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9215. lb_emit_store(p, len_dst, new_len);
  9216. }
  9217. return dst;
  9218. #endif
  9219. }
  9220. break;
  9221. }
  9222. GB_PANIC("Unknown slicable type");
  9223. case_end;
  9224. case_ast_node(de, DerefExpr, expr);
  9225. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  9226. lbAddr addr = lb_build_addr(p, de->expr);
  9227. addr.relative.deref = true;
  9228. return addr;
  9229. }
  9230. lbValue addr = lb_build_expr(p, de->expr);
  9231. return lb_addr(addr);
  9232. case_end;
  9233. case_ast_node(ce, CallExpr, expr);
  9234. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  9235. lbValue e = lb_build_expr(p, expr);
  9236. lbAddr v = lb_add_local_generated(p, e.type, false);
  9237. lb_addr_store(p, v, e);
  9238. return v;
  9239. case_end;
  9240. case_ast_node(cl, CompoundLit, expr);
  9241. Type *type = type_of_expr(expr);
  9242. Type *bt = base_type(type);
  9243. lbAddr v = lb_add_local_generated(p, type, true);
  9244. Type *et = nullptr;
  9245. switch (bt->kind) {
  9246. case Type_Array: et = bt->Array.elem; break;
  9247. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  9248. case Type_Slice: et = bt->Slice.elem; break;
  9249. case Type_BitSet: et = bt->BitSet.elem; break;
  9250. case Type_SimdVector: et = bt->SimdVector.elem; break;
  9251. }
  9252. String proc_name = {};
  9253. if (p->entity) {
  9254. proc_name = p->entity->token.string;
  9255. }
  9256. TokenPos pos = ast_token(expr).pos;
  9257. switch (bt->kind) {
  9258. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  9259. case Type_Struct: {
  9260. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  9261. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  9262. bool is_raw_union = is_type_raw_union(bt);
  9263. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  9264. TypeStruct *st = &bt->Struct;
  9265. if (cl->elems.count > 0) {
  9266. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9267. for_array(field_index, cl->elems) {
  9268. Ast *elem = cl->elems[field_index];
  9269. lbValue field_expr = {};
  9270. Entity *field = nullptr;
  9271. isize index = field_index;
  9272. if (elem->kind == Ast_FieldValue) {
  9273. ast_node(fv, FieldValue, elem);
  9274. String name = fv->field->Ident.token.string;
  9275. Selection sel = lookup_field(bt, name, false);
  9276. index = sel.index[0];
  9277. elem = fv->value;
  9278. TypeAndValue tav = type_and_value_of_expr(elem);
  9279. } else {
  9280. TypeAndValue tav = type_and_value_of_expr(elem);
  9281. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  9282. index = sel.index[0];
  9283. }
  9284. field = st->fields[index];
  9285. Type *ft = field->type;
  9286. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  9287. continue;
  9288. }
  9289. field_expr = lb_build_expr(p, elem);
  9290. Type *fet = field_expr.type;
  9291. GB_ASSERT(fet->kind != Type_Tuple);
  9292. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  9293. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  9294. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  9295. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9296. lb_emit_store_union_variant(p, gep, field_expr, fet);
  9297. } else {
  9298. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9299. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9300. lb_emit_store(p, gep, fv);
  9301. }
  9302. }
  9303. }
  9304. break;
  9305. }
  9306. case Type_Map: {
  9307. if (cl->elems.count == 0) {
  9308. break;
  9309. }
  9310. {
  9311. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9312. args[0] = lb_gen_map_header(p, v.addr, type);
  9313. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  9314. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  9315. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  9316. }
  9317. for_array(field_index, cl->elems) {
  9318. Ast *elem = cl->elems[field_index];
  9319. ast_node(fv, FieldValue, elem);
  9320. lbValue key = lb_build_expr(p, fv->field);
  9321. lbValue value = lb_build_expr(p, fv->value);
  9322. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  9323. }
  9324. break;
  9325. }
  9326. case Type_Array: {
  9327. if (cl->elems.count > 0) {
  9328. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9329. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9330. // NOTE(bill): Separate value, gep, store into their own chunks
  9331. for_array(i, cl->elems) {
  9332. Ast *elem = cl->elems[i];
  9333. if (elem->kind == Ast_FieldValue) {
  9334. ast_node(fv, FieldValue, elem);
  9335. if (lb_is_elem_const(fv->value, et)) {
  9336. continue;
  9337. }
  9338. if (is_ast_range(fv->field)) {
  9339. ast_node(ie, BinaryExpr, fv->field);
  9340. TypeAndValue lo_tav = ie->left->tav;
  9341. TypeAndValue hi_tav = ie->right->tav;
  9342. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9343. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9344. TokenKind op = ie->op.kind;
  9345. i64 lo = exact_value_to_i64(lo_tav.value);
  9346. i64 hi = exact_value_to_i64(hi_tav.value);
  9347. if (op == Token_Ellipsis) {
  9348. hi += 1;
  9349. }
  9350. lbValue value = lb_build_expr(p, fv->value);
  9351. for (i64 k = lo; k < hi; k++) {
  9352. lbCompoundLitElemTempData data = {};
  9353. data.value = value;
  9354. data.elem_index = cast(i32)k;
  9355. array_add(&temp_data, data);
  9356. }
  9357. } else {
  9358. auto tav = fv->field->tav;
  9359. GB_ASSERT(tav.mode == Addressing_Constant);
  9360. i64 index = exact_value_to_i64(tav.value);
  9361. lbValue value = lb_build_expr(p, fv->value);
  9362. lbCompoundLitElemTempData data = {};
  9363. data.value = lb_emit_conv(p, value, et);
  9364. data.expr = fv->value;
  9365. data.elem_index = cast(i32)index;
  9366. array_add(&temp_data, data);
  9367. }
  9368. } else {
  9369. if (lb_is_elem_const(elem, et)) {
  9370. continue;
  9371. }
  9372. lbCompoundLitElemTempData data = {};
  9373. data.expr = elem;
  9374. data.elem_index = cast(i32)i;
  9375. array_add(&temp_data, data);
  9376. }
  9377. }
  9378. for_array(i, temp_data) {
  9379. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  9380. }
  9381. for_array(i, temp_data) {
  9382. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9383. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9384. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9385. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9386. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9387. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9388. lbValue field_expr = temp_data[i].value;
  9389. Ast *expr = temp_data[i].expr;
  9390. p->return_ptr_hint_value = temp_data[i].gep;
  9391. p->return_ptr_hint_ast = unparen_expr(expr);
  9392. if (field_expr.value == nullptr) {
  9393. field_expr = lb_build_expr(p, expr);
  9394. }
  9395. Type *t = field_expr.type;
  9396. GB_ASSERT(t->kind != Type_Tuple);
  9397. lbValue ev = lb_emit_conv(p, field_expr, et);
  9398. if (!p->return_ptr_hint_used) {
  9399. temp_data[i].value = ev;
  9400. }
  9401. }
  9402. for_array(i, temp_data) {
  9403. if (temp_data[i].value.value != nullptr) {
  9404. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9405. }
  9406. }
  9407. }
  9408. break;
  9409. }
  9410. case Type_EnumeratedArray: {
  9411. if (cl->elems.count > 0) {
  9412. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9413. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9414. // NOTE(bill): Separate value, gep, store into their own chunks
  9415. for_array(i, cl->elems) {
  9416. Ast *elem = cl->elems[i];
  9417. if (elem->kind == Ast_FieldValue) {
  9418. ast_node(fv, FieldValue, elem);
  9419. if (lb_is_elem_const(fv->value, et)) {
  9420. continue;
  9421. }
  9422. if (is_ast_range(fv->field)) {
  9423. ast_node(ie, BinaryExpr, fv->field);
  9424. TypeAndValue lo_tav = ie->left->tav;
  9425. TypeAndValue hi_tav = ie->right->tav;
  9426. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9427. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9428. TokenKind op = ie->op.kind;
  9429. i64 lo = exact_value_to_i64(lo_tav.value);
  9430. i64 hi = exact_value_to_i64(hi_tav.value);
  9431. if (op == Token_Ellipsis) {
  9432. hi += 1;
  9433. }
  9434. lbValue value = lb_build_expr(p, fv->value);
  9435. for (i64 k = lo; k < hi; k++) {
  9436. lbCompoundLitElemTempData data = {};
  9437. data.value = value;
  9438. data.elem_index = cast(i32)k;
  9439. array_add(&temp_data, data);
  9440. }
  9441. } else {
  9442. auto tav = fv->field->tav;
  9443. GB_ASSERT(tav.mode == Addressing_Constant);
  9444. i64 index = exact_value_to_i64(tav.value);
  9445. lbValue value = lb_build_expr(p, fv->value);
  9446. lbCompoundLitElemTempData data = {};
  9447. data.value = lb_emit_conv(p, value, et);
  9448. data.expr = fv->value;
  9449. data.elem_index = cast(i32)index;
  9450. array_add(&temp_data, data);
  9451. }
  9452. } else {
  9453. if (lb_is_elem_const(elem, et)) {
  9454. continue;
  9455. }
  9456. lbCompoundLitElemTempData data = {};
  9457. data.expr = elem;
  9458. data.elem_index = cast(i32)i;
  9459. array_add(&temp_data, data);
  9460. }
  9461. }
  9462. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  9463. for_array(i, temp_data) {
  9464. i32 index = temp_data[i].elem_index - index_offset;
  9465. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  9466. }
  9467. for_array(i, temp_data) {
  9468. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9469. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9470. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9471. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9472. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9473. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9474. lbValue field_expr = temp_data[i].value;
  9475. Ast *expr = temp_data[i].expr;
  9476. p->return_ptr_hint_value = temp_data[i].gep;
  9477. p->return_ptr_hint_ast = unparen_expr(expr);
  9478. if (field_expr.value == nullptr) {
  9479. field_expr = lb_build_expr(p, expr);
  9480. }
  9481. Type *t = field_expr.type;
  9482. GB_ASSERT(t->kind != Type_Tuple);
  9483. lbValue ev = lb_emit_conv(p, field_expr, et);
  9484. if (!p->return_ptr_hint_used) {
  9485. temp_data[i].value = ev;
  9486. }
  9487. }
  9488. for_array(i, temp_data) {
  9489. if (temp_data[i].value.value != nullptr) {
  9490. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9491. }
  9492. }
  9493. }
  9494. break;
  9495. }
  9496. case Type_Slice: {
  9497. if (cl->elems.count > 0) {
  9498. Type *elem_type = bt->Slice.elem;
  9499. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  9500. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  9501. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  9502. lbValue data = lb_slice_elem(p, slice);
  9503. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9504. for_array(i, cl->elems) {
  9505. Ast *elem = cl->elems[i];
  9506. if (elem->kind == Ast_FieldValue) {
  9507. ast_node(fv, FieldValue, elem);
  9508. if (lb_is_elem_const(fv->value, et)) {
  9509. continue;
  9510. }
  9511. if (is_ast_range(fv->field)) {
  9512. ast_node(ie, BinaryExpr, fv->field);
  9513. TypeAndValue lo_tav = ie->left->tav;
  9514. TypeAndValue hi_tav = ie->right->tav;
  9515. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9516. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9517. TokenKind op = ie->op.kind;
  9518. i64 lo = exact_value_to_i64(lo_tav.value);
  9519. i64 hi = exact_value_to_i64(hi_tav.value);
  9520. if (op == Token_Ellipsis) {
  9521. hi += 1;
  9522. }
  9523. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9524. for (i64 k = lo; k < hi; k++) {
  9525. lbCompoundLitElemTempData data = {};
  9526. data.value = value;
  9527. data.elem_index = cast(i32)k;
  9528. array_add(&temp_data, data);
  9529. }
  9530. } else {
  9531. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9532. i64 index = exact_value_to_i64(fv->field->tav.value);
  9533. lbValue field_expr = lb_build_expr(p, fv->value);
  9534. GB_ASSERT(!is_type_tuple(field_expr.type));
  9535. lbValue ev = lb_emit_conv(p, field_expr, et);
  9536. lbCompoundLitElemTempData data = {};
  9537. data.value = ev;
  9538. data.elem_index = cast(i32)index;
  9539. array_add(&temp_data, data);
  9540. }
  9541. } else {
  9542. if (lb_is_elem_const(elem, et)) {
  9543. continue;
  9544. }
  9545. lbValue field_expr = lb_build_expr(p, elem);
  9546. GB_ASSERT(!is_type_tuple(field_expr.type));
  9547. lbValue ev = lb_emit_conv(p, field_expr, et);
  9548. lbCompoundLitElemTempData data = {};
  9549. data.value = ev;
  9550. data.elem_index = cast(i32)i;
  9551. array_add(&temp_data, data);
  9552. }
  9553. }
  9554. for_array(i, temp_data) {
  9555. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  9556. }
  9557. for_array(i, temp_data) {
  9558. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9559. }
  9560. {
  9561. lbValue count = {};
  9562. count.type = t_int;
  9563. if (lb_is_const(slice)) {
  9564. unsigned indices[1] = {1};
  9565. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  9566. } else {
  9567. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  9568. }
  9569. lb_fill_slice(p, v, data, count);
  9570. }
  9571. }
  9572. break;
  9573. }
  9574. case Type_DynamicArray: {
  9575. if (cl->elems.count == 0) {
  9576. break;
  9577. }
  9578. Type *et = bt->DynamicArray.elem;
  9579. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  9580. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  9581. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  9582. {
  9583. auto args = array_make<lbValue>(permanent_allocator(), 5);
  9584. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  9585. args[1] = size;
  9586. args[2] = align;
  9587. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  9588. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  9589. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  9590. }
  9591. lbValue items = lb_generate_local_array(p, et, item_count);
  9592. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  9593. for_array(i, cl->elems) {
  9594. Ast *elem = cl->elems[i];
  9595. if (elem->kind == Ast_FieldValue) {
  9596. ast_node(fv, FieldValue, elem);
  9597. if (is_ast_range(fv->field)) {
  9598. ast_node(ie, BinaryExpr, fv->field);
  9599. TypeAndValue lo_tav = ie->left->tav;
  9600. TypeAndValue hi_tav = ie->right->tav;
  9601. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9602. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9603. TokenKind op = ie->op.kind;
  9604. i64 lo = exact_value_to_i64(lo_tav.value);
  9605. i64 hi = exact_value_to_i64(hi_tav.value);
  9606. if (op == Token_Ellipsis) {
  9607. hi += 1;
  9608. }
  9609. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9610. for (i64 k = lo; k < hi; k++) {
  9611. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  9612. lb_emit_store(p, ep, value);
  9613. }
  9614. } else {
  9615. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9616. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  9617. lbValue ev = lb_build_expr(p, fv->value);
  9618. lbValue value = lb_emit_conv(p, ev, et);
  9619. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  9620. lb_emit_store(p, ep, value);
  9621. }
  9622. } else {
  9623. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  9624. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  9625. lb_emit_store(p, ep, value);
  9626. }
  9627. }
  9628. {
  9629. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9630. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  9631. args[1] = size;
  9632. args[2] = align;
  9633. args[3] = lb_emit_conv(p, items, t_rawptr);
  9634. args[4] = lb_const_int(p->module, t_int, item_count);
  9635. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  9636. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  9637. }
  9638. break;
  9639. }
  9640. case Type_Basic: {
  9641. GB_ASSERT(is_type_any(bt));
  9642. if (cl->elems.count > 0) {
  9643. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9644. String field_names[2] = {
  9645. str_lit("data"),
  9646. str_lit("id"),
  9647. };
  9648. Type *field_types[2] = {
  9649. t_rawptr,
  9650. t_typeid,
  9651. };
  9652. for_array(field_index, cl->elems) {
  9653. Ast *elem = cl->elems[field_index];
  9654. lbValue field_expr = {};
  9655. isize index = field_index;
  9656. if (elem->kind == Ast_FieldValue) {
  9657. ast_node(fv, FieldValue, elem);
  9658. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  9659. index = sel.index[0];
  9660. elem = fv->value;
  9661. } else {
  9662. TypeAndValue tav = type_and_value_of_expr(elem);
  9663. Selection sel = lookup_field(bt, field_names[field_index], false);
  9664. index = sel.index[0];
  9665. }
  9666. field_expr = lb_build_expr(p, elem);
  9667. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  9668. Type *ft = field_types[index];
  9669. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9670. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9671. lb_emit_store(p, gep, fv);
  9672. }
  9673. }
  9674. break;
  9675. }
  9676. case Type_BitSet: {
  9677. i64 sz = type_size_of(type);
  9678. if (cl->elems.count > 0 && sz > 0) {
  9679. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9680. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  9681. for_array(i, cl->elems) {
  9682. Ast *elem = cl->elems[i];
  9683. GB_ASSERT(elem->kind != Ast_FieldValue);
  9684. if (lb_is_elem_const(elem, et)) {
  9685. continue;
  9686. }
  9687. lbValue expr = lb_build_expr(p, elem);
  9688. GB_ASSERT(expr.type->kind != Type_Tuple);
  9689. Type *it = bit_set_to_int(bt);
  9690. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  9691. lbValue e = lb_emit_conv(p, expr, it);
  9692. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  9693. e = lb_emit_arith(p, Token_Shl, one, e, it);
  9694. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  9695. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  9696. new_value = lb_emit_transmute(p, new_value, type);
  9697. lb_addr_store(p, v, new_value);
  9698. }
  9699. }
  9700. break;
  9701. }
  9702. }
  9703. return v;
  9704. case_end;
  9705. case_ast_node(tc, TypeCast, expr);
  9706. Type *type = type_of_expr(expr);
  9707. lbValue x = lb_build_expr(p, tc->expr);
  9708. lbValue e = {};
  9709. switch (tc->token.kind) {
  9710. case Token_cast:
  9711. e = lb_emit_conv(p, x, type);
  9712. break;
  9713. case Token_transmute:
  9714. e = lb_emit_transmute(p, x, type);
  9715. break;
  9716. default:
  9717. GB_PANIC("Invalid AST TypeCast");
  9718. }
  9719. lbAddr v = lb_add_local_generated(p, type, false);
  9720. lb_addr_store(p, v, e);
  9721. return v;
  9722. case_end;
  9723. case_ast_node(ac, AutoCast, expr);
  9724. return lb_build_addr(p, ac->expr);
  9725. case_end;
  9726. }
  9727. TokenPos token_pos = ast_token(expr).pos;
  9728. GB_PANIC("Unexpected address expression\n"
  9729. "\tAst: %.*s @ "
  9730. "%.*s(%td:%td)\n",
  9731. LIT(ast_strings[expr->kind]),
  9732. LIT(token_pos.file), token_pos.line, token_pos.column);
  9733. return {};
  9734. }
  9735. void lb_init_module(lbModule *m, Checker *c) {
  9736. m->info = &c->info;
  9737. m->ctx = LLVMGetGlobalContext();
  9738. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  9739. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  9740. m->state_flags = 0;
  9741. m->state_flags |= StateFlag_bounds_check;
  9742. gb_mutex_init(&m->mutex);
  9743. gbAllocator a = heap_allocator();
  9744. map_init(&m->types, a);
  9745. map_init(&m->llvm_types, a);
  9746. map_init(&m->values, a);
  9747. string_map_init(&m->members, a);
  9748. map_init(&m->procedure_values, a);
  9749. string_map_init(&m->procedures, a);
  9750. string_map_init(&m->const_strings, a);
  9751. map_init(&m->anonymous_proc_lits, a);
  9752. map_init(&m->function_type_map, a);
  9753. map_init(&m->compare_procs, a);
  9754. array_init(&m->procedures_to_generate, a);
  9755. array_init(&m->foreign_library_paths, a);
  9756. map_init(&m->debug_values, a);
  9757. }
  9758. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  9759. if (global_error_collector.count != 0) {
  9760. return false;
  9761. }
  9762. isize tc = c->parser->total_token_count;
  9763. if (tc < 2) {
  9764. return false;
  9765. }
  9766. String init_fullpath = c->parser->init_fullpath;
  9767. if (build_context.out_filepath.len == 0) {
  9768. gen->output_name = remove_directory_from_path(init_fullpath);
  9769. gen->output_name = remove_extension_from_path(gen->output_name);
  9770. gen->output_name = string_trim_whitespace(gen->output_name);
  9771. if (gen->output_name.len == 0) {
  9772. gen->output_name = c->info.init_scope->pkg->name;
  9773. }
  9774. gen->output_base = gen->output_name;
  9775. } else {
  9776. gen->output_name = build_context.out_filepath;
  9777. gen->output_name = string_trim_whitespace(gen->output_name);
  9778. if (gen->output_name.len == 0) {
  9779. gen->output_name = c->info.init_scope->pkg->name;
  9780. }
  9781. isize pos = string_extension_position(gen->output_name);
  9782. if (pos < 0) {
  9783. gen->output_base = gen->output_name;
  9784. } else {
  9785. gen->output_base = substring(gen->output_name, 0, pos);
  9786. }
  9787. }
  9788. gbAllocator ha = heap_allocator();
  9789. array_init(&gen->output_object_paths, ha);
  9790. gen->output_base = path_to_full_path(ha, gen->output_base);
  9791. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  9792. output_file_path = gb_string_appendc(output_file_path, ".obj");
  9793. defer (gb_string_free(output_file_path));
  9794. gen->info = &c->info;
  9795. lb_init_module(&gen->module, c);
  9796. return true;
  9797. }
  9798. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  9799. GB_ASSERT(type != nullptr);
  9800. type = default_type(type);
  9801. isize max_len = 7+8+1;
  9802. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  9803. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  9804. m->global_generated_index++;
  9805. String name = make_string(str, len-1);
  9806. Scope *scope = nullptr;
  9807. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  9808. lbValue g = {};
  9809. g.type = alloc_type_pointer(type);
  9810. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  9811. if (value.value != nullptr) {
  9812. GB_ASSERT(LLVMIsConstant(value.value));
  9813. LLVMSetInitializer(g.value, value.value);
  9814. } else {
  9815. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  9816. }
  9817. lb_add_entity(m, e, g);
  9818. lb_add_member(m, name, g);
  9819. return lb_addr(g);
  9820. }
  9821. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  9822. AstPackage *p = m->info->runtime_package;
  9823. Entity *e = scope_lookup_current(p->scope, name);
  9824. lbValue *found = map_get(&m->values, hash_entity(e));
  9825. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  9826. lbValue value = *found;
  9827. return value;
  9828. }
  9829. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  9830. i32 index = cast(i32)lb_type_info_index(m->info, type);
  9831. GB_ASSERT(index >= 0);
  9832. // gb_printf_err("%d %s\n", index, type_to_string(type));
  9833. LLVMValueRef indices[2] = {
  9834. LLVMConstInt(lb_type(m, t_int), 0, false),
  9835. LLVMConstInt(lb_type(m, t_int), index, false),
  9836. };
  9837. lbValue res = {};
  9838. res.type = t_type_info_ptr;
  9839. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  9840. return res;
  9841. }
  9842. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  9843. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  9844. lb_global_type_info_member_types_index += cast(i32)count;
  9845. return offset;
  9846. }
  9847. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  9848. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  9849. lb_global_type_info_member_names_index += cast(i32)count;
  9850. return offset;
  9851. }
  9852. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  9853. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  9854. lb_global_type_info_member_offsets_index += cast(i32)count;
  9855. return offset;
  9856. }
  9857. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  9858. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  9859. lb_global_type_info_member_usings_index += cast(i32)count;
  9860. return offset;
  9861. }
  9862. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  9863. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  9864. lb_global_type_info_member_tags_index += cast(i32)count;
  9865. return offset;
  9866. }
  9867. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  9868. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  9869. return lb_addr_get_ptr(p, addr);
  9870. }
  9871. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  9872. Token token = {Token_Ident};
  9873. isize name_len = prefix.len + 1 + 20;
  9874. auto suffix_id = cast(unsigned long long)id;
  9875. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  9876. gb_snprintf(text, name_len,
  9877. "%.*s-%llu", LIT(prefix), suffix_id);
  9878. text[name_len] = 0;
  9879. String s = make_string_c(text);
  9880. Type *t = alloc_type_array(elem_type, count);
  9881. lbValue g = {};
  9882. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  9883. g.type = alloc_type_pointer(t);
  9884. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  9885. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  9886. string_map_set(&m->members, s, g);
  9887. return g;
  9888. }
  9889. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  9890. lbModule *m = p->module;
  9891. LLVMContextRef ctx = m->ctx;
  9892. CheckerInfo *info = m->info;
  9893. {
  9894. // NOTE(bill): Set the type_table slice with the global backing array
  9895. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  9896. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  9897. GB_ASSERT(is_type_array(type));
  9898. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  9899. LLVMValueRef values[2] = {
  9900. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  9901. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  9902. };
  9903. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  9904. LLVMSetInitializer(global_type_table.value, slice);
  9905. }
  9906. // Useful types
  9907. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  9908. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  9909. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  9910. Type *t_type_info_flags = type_info_flags_entity->type;
  9911. i32 type_info_member_types_index = 0;
  9912. i32 type_info_member_names_index = 0;
  9913. i32 type_info_member_offsets_index = 0;
  9914. for_array(type_info_type_index, info->type_info_types) {
  9915. Type *t = info->type_info_types[type_info_type_index];
  9916. t = default_type(t);
  9917. if (t == t_invalid) {
  9918. continue;
  9919. }
  9920. isize entry_index = lb_type_info_index(info, t, false);
  9921. if (entry_index <= 0) {
  9922. continue;
  9923. }
  9924. lbValue tag = {};
  9925. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  9926. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  9927. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  9928. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  9929. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  9930. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  9931. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  9932. switch (t->kind) {
  9933. case Type_Named: {
  9934. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  9935. LLVMValueRef vals[2] = {
  9936. lb_const_string(p->module, t->Named.type_name->token.string).value,
  9937. lb_get_type_info_ptr(m, t->Named.base).value,
  9938. };
  9939. lbValue res = {};
  9940. res.type = type_deref(tag.type);
  9941. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9942. lb_emit_store(p, tag, res);
  9943. break;
  9944. }
  9945. case Type_Basic:
  9946. switch (t->Basic.kind) {
  9947. case Basic_bool:
  9948. case Basic_b8:
  9949. case Basic_b16:
  9950. case Basic_b32:
  9951. case Basic_b64:
  9952. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  9953. break;
  9954. case Basic_i8:
  9955. case Basic_u8:
  9956. case Basic_i16:
  9957. case Basic_u16:
  9958. case Basic_i32:
  9959. case Basic_u32:
  9960. case Basic_i64:
  9961. case Basic_u64:
  9962. case Basic_i128:
  9963. case Basic_u128:
  9964. case Basic_i16le:
  9965. case Basic_u16le:
  9966. case Basic_i32le:
  9967. case Basic_u32le:
  9968. case Basic_i64le:
  9969. case Basic_u64le:
  9970. case Basic_i128le:
  9971. case Basic_u128le:
  9972. case Basic_i16be:
  9973. case Basic_u16be:
  9974. case Basic_i32be:
  9975. case Basic_u32be:
  9976. case Basic_i64be:
  9977. case Basic_u64be:
  9978. case Basic_i128be:
  9979. case Basic_u128be:
  9980. case Basic_int:
  9981. case Basic_uint:
  9982. case Basic_uintptr: {
  9983. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  9984. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  9985. // NOTE(bill): This is matches the runtime layout
  9986. u8 endianness_value = 0;
  9987. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9988. endianness_value = 1;
  9989. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9990. endianness_value = 2;
  9991. }
  9992. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9993. LLVMValueRef vals[2] = {
  9994. is_signed.value,
  9995. endianness.value,
  9996. };
  9997. lbValue res = {};
  9998. res.type = type_deref(tag.type);
  9999. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10000. lb_emit_store(p, tag, res);
  10001. break;
  10002. }
  10003. case Basic_rune:
  10004. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  10005. break;
  10006. // case Basic_f16:
  10007. case Basic_f32:
  10008. case Basic_f64:
  10009. case Basic_f32le:
  10010. case Basic_f64le:
  10011. case Basic_f32be:
  10012. case Basic_f64be:
  10013. {
  10014. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  10015. // NOTE(bill): This is matches the runtime layout
  10016. u8 endianness_value = 0;
  10017. if (t->Basic.flags & BasicFlag_EndianLittle) {
  10018. endianness_value = 1;
  10019. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  10020. endianness_value = 2;
  10021. }
  10022. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  10023. LLVMValueRef vals[1] = {
  10024. endianness.value,
  10025. };
  10026. lbValue res = {};
  10027. res.type = type_deref(tag.type);
  10028. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10029. lb_emit_store(p, tag, res);
  10030. }
  10031. break;
  10032. // case Basic_complex32:
  10033. case Basic_complex64:
  10034. case Basic_complex128:
  10035. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  10036. break;
  10037. case Basic_quaternion128:
  10038. case Basic_quaternion256:
  10039. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  10040. break;
  10041. case Basic_rawptr:
  10042. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10043. break;
  10044. case Basic_string:
  10045. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10046. break;
  10047. case Basic_cstring:
  10048. {
  10049. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  10050. LLVMValueRef vals[1] = {
  10051. lb_const_bool(m, t_bool, true).value,
  10052. };
  10053. lbValue res = {};
  10054. res.type = type_deref(tag.type);
  10055. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10056. lb_emit_store(p, tag, res);
  10057. }
  10058. break;
  10059. case Basic_any:
  10060. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  10061. break;
  10062. case Basic_typeid:
  10063. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  10064. break;
  10065. }
  10066. break;
  10067. case Type_Pointer: {
  10068. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  10069. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  10070. LLVMValueRef vals[1] = {
  10071. gep.value,
  10072. };
  10073. lbValue res = {};
  10074. res.type = type_deref(tag.type);
  10075. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10076. lb_emit_store(p, tag, res);
  10077. break;
  10078. }
  10079. case Type_Array: {
  10080. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  10081. i64 ez = type_size_of(t->Array.elem);
  10082. LLVMValueRef vals[3] = {
  10083. lb_get_type_info_ptr(m, t->Array.elem).value,
  10084. lb_const_int(m, t_int, ez).value,
  10085. lb_const_int(m, t_int, t->Array.count).value,
  10086. };
  10087. lbValue res = {};
  10088. res.type = type_deref(tag.type);
  10089. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10090. lb_emit_store(p, tag, res);
  10091. break;
  10092. }
  10093. case Type_EnumeratedArray: {
  10094. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  10095. LLVMValueRef vals[6] = {
  10096. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  10097. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  10098. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  10099. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  10100. // Unions
  10101. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10102. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  10103. };
  10104. lbValue res = {};
  10105. res.type = type_deref(tag.type);
  10106. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10107. lb_emit_store(p, tag, res);
  10108. // NOTE(bill): Union assignment
  10109. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  10110. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  10111. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  10112. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  10113. lb_emit_store(p, min_value, min_v);
  10114. lb_emit_store(p, max_value, max_v);
  10115. break;
  10116. }
  10117. case Type_DynamicArray: {
  10118. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  10119. LLVMValueRef vals[2] = {
  10120. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  10121. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  10122. };
  10123. lbValue res = {};
  10124. res.type = type_deref(tag.type);
  10125. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10126. lb_emit_store(p, tag, res);
  10127. break;
  10128. }
  10129. case Type_Slice: {
  10130. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  10131. LLVMValueRef vals[2] = {
  10132. lb_get_type_info_ptr(m, t->Slice.elem).value,
  10133. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  10134. };
  10135. lbValue res = {};
  10136. res.type = type_deref(tag.type);
  10137. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10138. lb_emit_store(p, tag, res);
  10139. break;
  10140. }
  10141. case Type_Proc: {
  10142. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  10143. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10144. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10145. if (t->Proc.params != nullptr) {
  10146. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  10147. }
  10148. if (t->Proc.results != nullptr) {
  10149. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  10150. }
  10151. LLVMValueRef vals[4] = {
  10152. params,
  10153. results,
  10154. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  10155. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  10156. };
  10157. lbValue res = {};
  10158. res.type = type_deref(tag.type);
  10159. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10160. lb_emit_store(p, tag, res);
  10161. break;
  10162. }
  10163. case Type_Tuple: {
  10164. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  10165. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  10166. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  10167. for_array(i, t->Tuple.variables) {
  10168. // NOTE(bill): offset is not used for tuples
  10169. Entity *f = t->Tuple.variables[i];
  10170. lbValue index = lb_const_int(m, t_int, i);
  10171. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10172. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  10173. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10174. if (f->token.string.len > 0) {
  10175. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10176. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10177. }
  10178. }
  10179. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  10180. LLVMValueRef types_slice = llvm_const_slice(memory_types, count);
  10181. LLVMValueRef names_slice = llvm_const_slice(memory_names, count);
  10182. LLVMValueRef vals[2] = {
  10183. types_slice,
  10184. names_slice,
  10185. };
  10186. lbValue res = {};
  10187. res.type = type_deref(tag.type);
  10188. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10189. lb_emit_store(p, tag, res);
  10190. break;
  10191. }
  10192. case Type_Enum:
  10193. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  10194. {
  10195. GB_ASSERT(t->Enum.base_type != nullptr);
  10196. // 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));
  10197. LLVMValueRef vals[3] = {};
  10198. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  10199. if (t->Enum.fields.count > 0) {
  10200. auto fields = t->Enum.fields;
  10201. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  10202. str_lit("$enum_names"), cast(i64)entry_index);
  10203. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  10204. str_lit("$enum_values"), cast(i64)entry_index);
  10205. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10206. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10207. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10208. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  10209. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  10210. for_array(i, fields) {
  10211. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  10212. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  10213. }
  10214. LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  10215. LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  10216. LLVMSetInitializer(name_array.value, name_init);
  10217. LLVMSetInitializer(value_array.value, value_init);
  10218. lbValue v_count = lb_const_int(m, t_int, fields.count);
  10219. vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count);
  10220. vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count);
  10221. } else {
  10222. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  10223. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  10224. }
  10225. lbValue res = {};
  10226. res.type = type_deref(tag.type);
  10227. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10228. lb_emit_store(p, tag, res);
  10229. }
  10230. break;
  10231. case Type_Union: {
  10232. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  10233. {
  10234. LLVMValueRef vals[6] = {};
  10235. isize variant_count = gb_max(0, t->Union.variants.count);
  10236. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  10237. // NOTE(bill): Zeroth is nil so ignore it
  10238. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10239. Type *vt = t->Union.variants[variant_index];
  10240. lbValue tip = lb_get_type_info_ptr(m, vt);
  10241. lbValue index = lb_const_int(m, t_int, variant_index);
  10242. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10243. lb_emit_store(p, type_info, lb_type_info(m, vt));
  10244. }
  10245. lbValue count = lb_const_int(m, t_int, variant_count);
  10246. vals[0] = llvm_const_slice(memory_types, count);
  10247. i64 tag_size = union_tag_size(t);
  10248. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10249. if (tag_size > 0) {
  10250. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  10251. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  10252. } else {
  10253. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  10254. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10255. }
  10256. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  10257. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  10258. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  10259. lbValue res = {};
  10260. res.type = type_deref(tag.type);
  10261. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10262. lb_emit_store(p, tag, res);
  10263. }
  10264. break;
  10265. }
  10266. case Type_Struct: {
  10267. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  10268. LLVMValueRef vals[12] = {};
  10269. {
  10270. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  10271. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  10272. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  10273. vals[5] = is_packed.value;
  10274. vals[6] = is_raw_union.value;
  10275. vals[7] = is_custom_align.value;
  10276. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  10277. vals[8] = lb_get_compare_proc_for_type(m, t).value;
  10278. }
  10279. if (t->Struct.soa_kind != StructSoa_None) {
  10280. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  10281. Type *kind_type = type_deref(kind.type);
  10282. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  10283. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  10284. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  10285. vals[9] = soa_kind.value;
  10286. vals[1] = soa_type.value;
  10287. vals[11] = soa_len.value;
  10288. }
  10289. }
  10290. isize count = t->Struct.fields.count;
  10291. if (count > 0) {
  10292. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  10293. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  10294. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  10295. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  10296. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  10297. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10298. for (isize source_index = 0; source_index < count; source_index++) {
  10299. // TODO(bill): Order fields in source order not layout order
  10300. Entity *f = t->Struct.fields[source_index];
  10301. lbValue tip = lb_get_type_info_ptr(m, f->type);
  10302. i64 foffset = 0;
  10303. if (!t->Struct.is_raw_union) {
  10304. foffset = t->Struct.offsets[f->Variable.field_index];
  10305. }
  10306. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10307. lbValue index = lb_const_int(m, t_int, source_index);
  10308. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10309. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  10310. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  10311. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10312. if (f->token.string.len > 0) {
  10313. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10314. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10315. }
  10316. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  10317. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  10318. if (t->Struct.tags.count > 0) {
  10319. String tag_string = t->Struct.tags[source_index];
  10320. if (tag_string.len > 0) {
  10321. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  10322. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  10323. }
  10324. }
  10325. }
  10326. lbValue cv = lb_const_int(m, t_int, count);
  10327. vals[0] = llvm_const_slice(memory_types, cv);
  10328. vals[1] = llvm_const_slice(memory_names, cv);
  10329. vals[2] = llvm_const_slice(memory_offsets, cv);
  10330. vals[3] = llvm_const_slice(memory_usings, cv);
  10331. vals[4] = llvm_const_slice(memory_tags, cv);
  10332. }
  10333. for (isize i = 0; i < gb_count_of(vals); i++) {
  10334. if (vals[i] == nullptr) {
  10335. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  10336. }
  10337. }
  10338. lbValue res = {};
  10339. res.type = type_deref(tag.type);
  10340. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10341. lb_emit_store(p, tag, res);
  10342. break;
  10343. }
  10344. case Type_Map: {
  10345. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  10346. init_map_internal_types(t);
  10347. LLVMValueRef vals[3] = {
  10348. lb_get_type_info_ptr(m, t->Map.key).value,
  10349. lb_get_type_info_ptr(m, t->Map.value).value,
  10350. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  10351. };
  10352. lbValue res = {};
  10353. res.type = type_deref(tag.type);
  10354. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10355. lb_emit_store(p, tag, res);
  10356. break;
  10357. }
  10358. case Type_BitField: {
  10359. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_field_ptr);
  10360. // names: []string;
  10361. // bits: []u32;
  10362. // offsets: []u32;
  10363. isize count = t->BitField.fields.count;
  10364. if (count > 0) {
  10365. auto fields = t->BitField.fields;
  10366. lbValue name_array = lb_generate_global_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index);
  10367. lbValue bit_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index);
  10368. lbValue offset_array = lb_generate_global_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index);
  10369. for (isize i = 0; i < count; i++) {
  10370. Entity *f = fields[i];
  10371. GB_ASSERT(f->type != nullptr);
  10372. GB_ASSERT(f->type->kind == Type_BitFieldValue);
  10373. lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i);
  10374. lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i);
  10375. lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i);
  10376. lb_emit_store(p, name_ep, lb_const_string(m, f->token.string));
  10377. lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits));
  10378. lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i]));
  10379. }
  10380. lbValue v_count = lb_const_int(m, t_int, count);
  10381. lbValue name_array_elem = lb_array_elem(p, name_array);
  10382. lbValue bit_array_elem = lb_array_elem(p, bit_array);
  10383. lbValue offset_array_elem = lb_array_elem(p, offset_array);
  10384. LLVMValueRef vals[3] = {
  10385. llvm_const_slice(name_array_elem, v_count),
  10386. llvm_const_slice(bit_array_elem, v_count),
  10387. llvm_const_slice(offset_array_elem, v_count),
  10388. };
  10389. lbValue res = {};
  10390. res.type = type_deref(tag.type);
  10391. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10392. lb_emit_store(p, tag, res);
  10393. }
  10394. break;
  10395. }
  10396. case Type_BitSet:
  10397. {
  10398. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  10399. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10400. LLVMValueRef vals[4] = {
  10401. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  10402. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  10403. lb_const_int(m, t_i64, t->BitSet.lower).value,
  10404. lb_const_int(m, t_i64, t->BitSet.upper).value,
  10405. };
  10406. if (t->BitSet.underlying != nullptr) {
  10407. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  10408. }
  10409. lbValue res = {};
  10410. res.type = type_deref(tag.type);
  10411. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10412. lb_emit_store(p, tag, res);
  10413. }
  10414. break;
  10415. case Type_Opaque:
  10416. {
  10417. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_opaque_ptr);
  10418. LLVMValueRef vals[1] = {
  10419. lb_get_type_info_ptr(m, t->Opaque.elem).value,
  10420. };
  10421. lbValue res = {};
  10422. res.type = type_deref(tag.type);
  10423. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10424. lb_emit_store(p, tag, res);
  10425. }
  10426. break;
  10427. case Type_SimdVector:
  10428. {
  10429. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  10430. LLVMValueRef vals[4] = {};
  10431. if (t->SimdVector.is_x86_mmx) {
  10432. vals[3] = lb_const_bool(m, t_bool, true).value;
  10433. } else {
  10434. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  10435. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  10436. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  10437. }
  10438. lbValue res = {};
  10439. res.type = type_deref(tag.type);
  10440. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10441. lb_emit_store(p, tag, res);
  10442. }
  10443. break;
  10444. case Type_RelativePointer:
  10445. {
  10446. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  10447. LLVMValueRef vals[2] = {
  10448. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  10449. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  10450. };
  10451. lbValue res = {};
  10452. res.type = type_deref(tag.type);
  10453. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10454. lb_emit_store(p, tag, res);
  10455. }
  10456. break;
  10457. case Type_RelativeSlice:
  10458. {
  10459. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  10460. LLVMValueRef vals[2] = {
  10461. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  10462. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  10463. };
  10464. lbValue res = {};
  10465. res.type = type_deref(tag.type);
  10466. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10467. lb_emit_store(p, tag, res);
  10468. }
  10469. break;
  10470. }
  10471. if (tag.value != nullptr) {
  10472. Type *tag_type = type_deref(tag.type);
  10473. GB_ASSERT(is_type_named(tag_type));
  10474. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  10475. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  10476. } else {
  10477. if (t != t_llvm_bool) {
  10478. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  10479. }
  10480. }
  10481. }
  10482. }
  10483. void lb_generate_code(lbGenerator *gen) {
  10484. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  10485. TIME_SECTION("LLVM Initializtion");
  10486. lbModule *m = &gen->module;
  10487. LLVMModuleRef mod = gen->module.mod;
  10488. CheckerInfo *info = gen->info;
  10489. auto *min_dep_set = &info->minimum_dependency_set;
  10490. LLVMInitializeAllTargetInfos();
  10491. LLVMInitializeAllTargets();
  10492. LLVMInitializeAllTargetMCs();
  10493. LLVMInitializeAllAsmPrinters();
  10494. LLVMInitializeAllAsmParsers();
  10495. LLVMInitializeAllDisassemblers();
  10496. LLVMInitializeNativeTarget();
  10497. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  10498. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  10499. LLVMSetTarget(mod, target_triple);
  10500. LLVMTargetRef target = {};
  10501. char *llvm_error = nullptr;
  10502. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  10503. GB_ASSERT(target != nullptr);
  10504. TIME_SECTION("LLVM Create Target Machine");
  10505. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  10506. if (build_context.metrics.arch == TargetArch_wasm32) {
  10507. code_mode = LLVMCodeModelJITDefault;
  10508. }
  10509. char const *host_cpu_name = LLVMGetHostCPUName();
  10510. char const *llvm_cpu = "generic";
  10511. char const *llvm_features = "";
  10512. if (build_context.microarch.len != 0) {
  10513. if (build_context.microarch == "native") {
  10514. llvm_cpu = host_cpu_name;
  10515. } else {
  10516. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  10517. }
  10518. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  10519. llvm_features = LLVMGetHostCPUFeatures();
  10520. }
  10521. }
  10522. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  10523. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  10524. switch (build_context.optimization_level) {
  10525. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  10526. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  10527. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  10528. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  10529. }
  10530. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  10531. defer (LLVMDisposeTargetMachine(target_machine));
  10532. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  10533. { // Debug Info
  10534. for_array(i, info->files.entries) {
  10535. AstFile *f = info->files.entries[i].value;
  10536. String fullpath = f->fullpath;
  10537. String filename = filename_from_path(fullpath);
  10538. String directory = directory_from_path(fullpath);
  10539. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  10540. cast(char const *)filename.text, filename.len,
  10541. cast(char const *)directory.text, directory.len);
  10542. map_set(&m->debug_values, hash_pointer(f), res);
  10543. f->llvm_metadata = res;
  10544. }
  10545. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  10546. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  10547. "odin", 4,
  10548. false, "", 0,
  10549. 1, "", 0,
  10550. LLVMDWARFEmissionFull, 0, true,
  10551. true
  10552. );
  10553. }
  10554. TIME_SECTION("LLVM Global Variables");
  10555. {
  10556. { // Add type info data
  10557. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  10558. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  10559. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  10560. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  10561. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10562. LLVMSetLinkage(g, LLVMInternalLinkage);
  10563. lbValue value = {};
  10564. value.value = g;
  10565. value.type = alloc_type_pointer(t);
  10566. lb_global_type_info_data = lb_addr(value);
  10567. }
  10568. { // Type info member buffer
  10569. // NOTE(bill): Removes need for heap allocation by making it global memory
  10570. isize count = 0;
  10571. for_array(entry_index, m->info->type_info_types) {
  10572. Type *t = m->info->type_info_types[entry_index];
  10573. isize index = lb_type_info_index(m->info, t, false);
  10574. if (index < 0) {
  10575. continue;
  10576. }
  10577. switch (t->kind) {
  10578. case Type_Union:
  10579. count += t->Union.variants.count;
  10580. break;
  10581. case Type_Struct:
  10582. count += t->Struct.fields.count;
  10583. break;
  10584. case Type_Tuple:
  10585. count += t->Tuple.variables.count;
  10586. break;
  10587. }
  10588. }
  10589. if (count > 0) {
  10590. {
  10591. char const *name = LB_TYPE_INFO_TYPES_NAME;
  10592. Type *t = alloc_type_array(t_type_info_ptr, count);
  10593. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10594. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10595. LLVMSetLinkage(g, LLVMInternalLinkage);
  10596. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  10597. }
  10598. {
  10599. char const *name = LB_TYPE_INFO_NAMES_NAME;
  10600. Type *t = alloc_type_array(t_string, count);
  10601. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10602. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10603. LLVMSetLinkage(g, LLVMInternalLinkage);
  10604. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  10605. }
  10606. {
  10607. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  10608. Type *t = alloc_type_array(t_uintptr, count);
  10609. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10610. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10611. LLVMSetLinkage(g, LLVMInternalLinkage);
  10612. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  10613. }
  10614. {
  10615. char const *name = LB_TYPE_INFO_USINGS_NAME;
  10616. Type *t = alloc_type_array(t_bool, count);
  10617. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10618. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10619. LLVMSetLinkage(g, LLVMInternalLinkage);
  10620. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  10621. }
  10622. {
  10623. char const *name = LB_TYPE_INFO_TAGS_NAME;
  10624. Type *t = alloc_type_array(t_string, count);
  10625. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10626. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10627. LLVMSetLinkage(g, LLVMInternalLinkage);
  10628. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  10629. }
  10630. }
  10631. }
  10632. }
  10633. isize global_variable_max_count = 0;
  10634. Entity *entry_point = info->entry_point;
  10635. bool has_dll_main = false;
  10636. bool has_win_main = false;
  10637. for_array(i, info->entities) {
  10638. Entity *e = info->entities[i];
  10639. String name = e->token.string;
  10640. bool is_global = e->pkg != nullptr;
  10641. if (e->kind == Entity_Variable) {
  10642. global_variable_max_count++;
  10643. } else if (e->kind == Entity_Procedure && !is_global) {
  10644. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10645. GB_ASSERT(e == entry_point);
  10646. // entry_point = e;
  10647. }
  10648. if (e->Procedure.is_export ||
  10649. (e->Procedure.link_name.len > 0) ||
  10650. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10651. if (!has_dll_main && name == "DllMain") {
  10652. has_dll_main = true;
  10653. } else if (!has_win_main && name == "WinMain") {
  10654. has_win_main = true;
  10655. }
  10656. }
  10657. }
  10658. }
  10659. struct GlobalVariable {
  10660. lbValue var;
  10661. lbValue init;
  10662. DeclInfo *decl;
  10663. };
  10664. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  10665. for_array(i, info->variable_init_order) {
  10666. DeclInfo *d = info->variable_init_order[i];
  10667. Entity *e = d->entity;
  10668. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10669. continue;
  10670. }
  10671. if (!ptr_set_exists(min_dep_set, e)) {
  10672. continue;
  10673. }
  10674. DeclInfo *decl = decl_info_of_entity(e);
  10675. if (decl == nullptr) {
  10676. continue;
  10677. }
  10678. GB_ASSERT(e->kind == Entity_Variable);
  10679. bool is_foreign = e->Variable.is_foreign;
  10680. bool is_export = e->Variable.is_export;
  10681. String name = lb_get_entity_name(m, e);
  10682. lbValue g = {};
  10683. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  10684. g.type = alloc_type_pointer(e->type);
  10685. if (e->Variable.thread_local_model != "") {
  10686. LLVMSetThreadLocal(g.value, true);
  10687. String m = e->Variable.thread_local_model;
  10688. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  10689. if (m == "default") {
  10690. mode = LLVMGeneralDynamicTLSModel;
  10691. } else if (m == "localdynamic") {
  10692. mode = LLVMLocalDynamicTLSModel;
  10693. } else if (m == "initialexec") {
  10694. mode = LLVMInitialExecTLSModel;
  10695. } else if (m == "localexec") {
  10696. mode = LLVMLocalExecTLSModel;
  10697. } else {
  10698. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  10699. }
  10700. LLVMSetThreadLocalMode(g.value, mode);
  10701. }
  10702. if (is_foreign) {
  10703. LLVMSetExternallyInitialized(g.value, true);
  10704. } else {
  10705. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  10706. }
  10707. if (is_export) {
  10708. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  10709. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  10710. }
  10711. GlobalVariable var = {};
  10712. var.var = g;
  10713. var.decl = decl;
  10714. if (decl->init_expr != nullptr && !is_type_any(e->type)) {
  10715. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10716. if (tav.mode != Addressing_Invalid) {
  10717. if (tav.value.kind != ExactValue_Invalid) {
  10718. ExactValue v = tav.value;
  10719. lbValue init = lb_const_value(m, tav.type, v);
  10720. LLVMSetInitializer(g.value, init.value);
  10721. }
  10722. }
  10723. }
  10724. array_add(&global_variables, var);
  10725. lb_add_entity(m, e, g);
  10726. lb_add_member(m, name, g);
  10727. }
  10728. TIME_SECTION("LLVM Global Procedures and Types");
  10729. for_array(i, info->entities) {
  10730. Entity *e = info->entities[i];
  10731. String name = e->token.string;
  10732. DeclInfo *decl = e->decl_info;
  10733. Scope * scope = e->scope;
  10734. if ((scope->flags & ScopeFlag_File) == 0) {
  10735. continue;
  10736. }
  10737. Scope *package_scope = scope->parent;
  10738. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10739. switch (e->kind) {
  10740. case Entity_Variable:
  10741. // NOTE(bill): Handled above as it requires a specific load order
  10742. continue;
  10743. case Entity_ProcGroup:
  10744. continue;
  10745. case Entity_TypeName:
  10746. case Entity_Procedure:
  10747. break;
  10748. }
  10749. bool polymorphic_struct = false;
  10750. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10751. Type *bt = base_type(e->type);
  10752. if (bt->kind == Type_Struct) {
  10753. polymorphic_struct = is_type_polymorphic(bt);
  10754. }
  10755. }
  10756. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  10757. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10758. continue;
  10759. }
  10760. String mangled_name = lb_get_entity_name(m, e);
  10761. switch (e->kind) {
  10762. case Entity_TypeName:
  10763. lb_type(m, e->type);
  10764. break;
  10765. case Entity_Procedure:
  10766. {
  10767. lbProcedure *p = lb_create_procedure(m, e);
  10768. array_add(&m->procedures_to_generate, p);
  10769. }
  10770. break;
  10771. }
  10772. }
  10773. TIME_SECTION("LLVM Registry Initializtion");
  10774. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  10775. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  10776. defer (LLVMDisposePassManager(default_function_pass_manager));
  10777. /*{
  10778. LLVMAddMemCpyOptPass(default_function_pass_manager);
  10779. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10780. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10781. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10782. LLVMAddConstantPropagationPass(default_function_pass_manager);
  10783. LLVMAddAggressiveDCEPass(default_function_pass_manager);
  10784. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager);
  10785. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10786. LLVMAddCFGSimplificationPass(default_function_pass_manager);
  10787. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager);
  10788. if (build_context.optimization_level >= 2) {
  10789. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager);
  10790. LLVMAddEarlyCSEPass(default_function_pass_manager);
  10791. LLVMAddEarlyCSEMemSSAPass(default_function_pass_manager);
  10792. LLVMAddLowerExpectIntrinsicPass(default_function_pass_manager);
  10793. LLVMAddAlignmentFromAssumptionsPass(default_function_pass_manager);
  10794. LLVMAddLoopRotatePass(default_function_pass_manager);
  10795. LLVMAddDeadStoreEliminationPass(default_function_pass_manager);
  10796. LLVMAddScalarizerPass(default_function_pass_manager);
  10797. LLVMAddReassociatePass(default_function_pass_manager);
  10798. LLVMAddAddDiscriminatorsPass(default_function_pass_manager);
  10799. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager);
  10800. LLVMAddCorrelatedValuePropagationPass(default_function_pass_manager);
  10801. LLVMAddSLPVectorizePass(default_function_pass_manager);
  10802. LLVMAddLoopVectorizePass(default_function_pass_manager);
  10803. }
  10804. }*/
  10805. if (build_context.optimization_level == 0 && false) {
  10806. auto dfpm = default_function_pass_manager;
  10807. LLVMAddMemCpyOptPass(dfpm);
  10808. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10809. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10810. LLVMAddAggressiveInstCombinerPass(dfpm);
  10811. LLVMAddConstantPropagationPass(dfpm);
  10812. LLVMAddAggressiveDCEPass(dfpm);
  10813. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10814. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10815. LLVMAddCFGSimplificationPass(dfpm);
  10816. LLVMAddScalarizerPass(dfpm);
  10817. } else {
  10818. auto dfpm = default_function_pass_manager;
  10819. LLVMAddMemCpyOptPass(dfpm);
  10820. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10821. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10822. LLVMAddAggressiveInstCombinerPass(dfpm);
  10823. LLVMAddConstantPropagationPass(dfpm);
  10824. LLVMAddAggressiveDCEPass(dfpm);
  10825. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10826. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10827. LLVMAddCFGSimplificationPass(dfpm);
  10828. // LLVMAddInstructionCombiningPass(dfpm);
  10829. LLVMAddSLPVectorizePass(dfpm);
  10830. LLVMAddLoopVectorizePass(dfpm);
  10831. LLVMAddEarlyCSEPass(dfpm);
  10832. LLVMAddEarlyCSEMemSSAPass(dfpm);
  10833. LLVMAddScalarizerPass(dfpm);
  10834. LLVMAddLoopIdiomPass(dfpm);
  10835. // LLVMAddAggressiveInstCombinerPass(dfpm);
  10836. // LLVMAddLowerExpectIntrinsicPass(dfpm);
  10837. // LLVMAddPartiallyInlineLibCallsPass(dfpm);
  10838. // LLVMAddAlignmentFromAssumptionsPass(dfpm);
  10839. // LLVMAddDeadStoreEliminationPass(dfpm);
  10840. // LLVMAddReassociatePass(dfpm);
  10841. // LLVMAddAddDiscriminatorsPass(dfpm);
  10842. // LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10843. // LLVMAddCorrelatedValuePropagationPass(dfpm);
  10844. // LLVMAddMemCpyOptPass(dfpm);
  10845. }
  10846. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  10847. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  10848. {
  10849. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10850. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10851. LLVMAddAggressiveInstCombinerPass(default_function_pass_manager_without_memcpy);
  10852. LLVMAddConstantPropagationPass(default_function_pass_manager_without_memcpy);
  10853. LLVMAddAggressiveDCEPass(default_function_pass_manager_without_memcpy);
  10854. LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy);
  10855. LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy);
  10856. LLVMAddCFGSimplificationPass(default_function_pass_manager_without_memcpy);
  10857. // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager_without_memcpy);
  10858. }
  10859. TIME_SECTION("LLVM Runtime Creation");
  10860. lbProcedure *startup_type_info = nullptr;
  10861. lbProcedure *startup_runtime = nullptr;
  10862. { // Startup Type Info
  10863. Type *params = alloc_type_tuple();
  10864. Type *results = alloc_type_tuple();
  10865. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10866. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  10867. p->is_startup = true;
  10868. startup_type_info = p;
  10869. lb_begin_procedure_body(p);
  10870. lb_setup_type_info_data(p);
  10871. lb_end_procedure_body(p);
  10872. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10873. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10874. LLVMDumpValue(p->value);
  10875. gb_printf_err("\n\n\n\n");
  10876. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10877. }
  10878. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10879. }
  10880. { // Startup Runtime
  10881. Type *params = alloc_type_tuple();
  10882. Type *results = alloc_type_tuple();
  10883. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10884. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  10885. p->is_startup = true;
  10886. startup_runtime = p;
  10887. lb_begin_procedure_body(p);
  10888. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  10889. for_array(i, global_variables) {
  10890. auto *var = &global_variables[i];
  10891. if (var->decl->init_expr != nullptr) {
  10892. lbValue init = lb_build_expr(p, var->decl->init_expr);
  10893. if (!lb_is_const(init)) {
  10894. var->init = init;
  10895. }
  10896. }
  10897. Entity *e = var->decl->entity;
  10898. GB_ASSERT(e->kind == Entity_Variable);
  10899. if (e->Variable.is_foreign) {
  10900. Entity *fl = e->Procedure.foreign_library;
  10901. lb_add_foreign_library_path(m, fl);
  10902. }
  10903. if (e->flags & EntityFlag_Static) {
  10904. LLVMSetLinkage(var->var.value, LLVMInternalLinkage);
  10905. }
  10906. if (var->init.value != nullptr) {
  10907. Type *t = type_deref(var->var.type);
  10908. if (is_type_any(t)) {
  10909. // NOTE(bill): Edge case for 'any' type
  10910. Type *var_type = default_type(var->init.type);
  10911. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  10912. lb_addr_store(p, g, var->init);
  10913. lbValue gp = lb_addr_get_ptr(p, g);
  10914. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  10915. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  10916. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  10917. lb_emit_store(p, ti, lb_type_info(m, var_type));
  10918. } else {
  10919. lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t));
  10920. }
  10921. }
  10922. }
  10923. lb_end_procedure_body(p);
  10924. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10925. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10926. LLVMDumpValue(p->value);
  10927. gb_printf_err("\n\n\n\n");
  10928. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10929. }
  10930. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10931. /*{
  10932. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  10933. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  10934. instr != last_instr;
  10935. instr = LLVMGetNextInstruction(instr)) {
  10936. if (LLVMIsAAllocaInst(instr)) {
  10937. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  10938. LLVMValueRef sz_val = LLVMSizeOf(type);
  10939. GB_ASSERT(LLVMIsConstant(sz_val));
  10940. gb_printf_err(">> 0x%p\n", sz_val);
  10941. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  10942. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  10943. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  10944. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  10945. gb_printf_err(">> %ll\n", sz);
  10946. }
  10947. }
  10948. }*/
  10949. }
  10950. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  10951. Type *params = alloc_type_tuple();
  10952. Type *results = alloc_type_tuple();
  10953. String name = str_lit("main");
  10954. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  10955. name = str_lit("mainCRTStartup");
  10956. } else {
  10957. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  10958. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  10959. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  10960. }
  10961. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  10962. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  10963. Type *proc_type = alloc_type_proc(nullptr,
  10964. params, params->Tuple.variables.count,
  10965. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  10966. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  10967. p->is_startup = true;
  10968. lb_begin_procedure_body(p);
  10969. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  10970. if (build_context.command_kind == Command_test) {
  10971. for_array(i, m->info->testing_procedures) {
  10972. Entity *e = m->info->testing_procedures[i];
  10973. lbValue *found = map_get(&m->values, hash_entity(e));
  10974. GB_ASSERT(found != nullptr);
  10975. lb_emit_call(p, *found, {});
  10976. }
  10977. } else {
  10978. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  10979. GB_ASSERT(found != nullptr);
  10980. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  10981. }
  10982. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  10983. lb_end_procedure_body(p);
  10984. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10985. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10986. LLVMDumpValue(p->value);
  10987. gb_printf_err("\n\n\n\n");
  10988. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10989. }
  10990. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10991. }
  10992. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  10993. TIME_SECTION("LLVM Procedure Generation");
  10994. for_array(i, m->procedures_to_generate) {
  10995. lbProcedure *p = m->procedures_to_generate[i];
  10996. if (p->is_done) {
  10997. continue;
  10998. }
  10999. if (p->body != nullptr) { // Build Procedure
  11000. m->curr_procedure = p;
  11001. lb_begin_procedure_body(p);
  11002. lb_build_stmt(p, p->body);
  11003. lb_end_procedure_body(p);
  11004. p->is_done = true;
  11005. m->curr_procedure = nullptr;
  11006. }
  11007. lb_end_procedure(p);
  11008. // Add Flags
  11009. if (p->body != nullptr) {
  11010. if (p->name == "memcpy" || p->name == "memmove" ||
  11011. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  11012. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  11013. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  11014. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  11015. }
  11016. }
  11017. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  11018. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  11019. LLVMDumpValue(p->value);
  11020. gb_printf_err("\n\n\n\n");
  11021. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11022. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11023. }
  11024. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  11025. gb_exit(1);
  11026. }
  11027. }
  11028. TIME_SECTION("LLVM Function Pass");
  11029. for_array(i, m->procedures_to_generate) {
  11030. lbProcedure *p = m->procedures_to_generate[i];
  11031. if (p->body != nullptr) { // Build Procedure
  11032. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  11033. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  11034. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  11035. } else {
  11036. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  11037. }
  11038. }
  11039. }
  11040. }
  11041. TIME_SECTION("LLVM Module Pass");
  11042. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  11043. defer (LLVMDisposePassManager(module_pass_manager));
  11044. LLVMAddAlwaysInlinerPass(module_pass_manager);
  11045. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  11046. LLVMAddAnalysisPasses(target_machine, module_pass_manager);
  11047. // if (build_context.optimization_level >= 2) {
  11048. // LLVMAddArgumentPromotionPass(module_pass_manager);
  11049. // LLVMAddConstantMergePass(module_pass_manager);
  11050. // LLVMAddGlobalDCEPass(module_pass_manager);
  11051. // LLVMAddDeadArgEliminationPass(module_pass_manager);
  11052. // }
  11053. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  11054. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  11055. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  11056. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  11057. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  11058. LLVMRunPassManager(module_pass_manager, mod);
  11059. llvm_error = nullptr;
  11060. defer (LLVMDisposeMessage(llvm_error));
  11061. String filepath_obj = {};
  11062. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  11063. if (build_context.build_mode == BuildMode_Assembly) {
  11064. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  11065. code_gen_file_type = LLVMAssemblyFile;
  11066. } else {
  11067. switch (build_context.metrics.os) {
  11068. case TargetOs_windows:
  11069. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  11070. break;
  11071. case TargetOs_darwin:
  11072. case TargetOs_linux:
  11073. case TargetOs_essence:
  11074. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  11075. break;
  11076. case TargetOs_js:
  11077. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  11078. break;
  11079. }
  11080. }
  11081. LLVMDIBuilderFinalize(m->debug_builder);
  11082. if (LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error)) {
  11083. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11084. gb_exit(1);
  11085. return;
  11086. }
  11087. llvm_error = nullptr;
  11088. if (build_context.keep_temp_files) {
  11089. TIME_SECTION("LLVM Print Module to File");
  11090. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  11091. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11092. gb_exit(1);
  11093. return;
  11094. }
  11095. }
  11096. TIME_SECTION("LLVM Object Generation");
  11097. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  11098. gb_printf_err("LLVM Error: %s\n", llvm_error);
  11099. gb_exit(1);
  11100. return;
  11101. }
  11102. array_add(&gen->output_object_paths, filepath_obj);
  11103. for_array(i, m->info->required_foreign_imports_through_force) {
  11104. Entity *e = m->info->required_foreign_imports_through_force[i];
  11105. lb_add_foreign_library_path(m, e);
  11106. }
  11107. #undef TIME_SECTION
  11108. }