llvm_backend.cpp 402 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001
  1. #include "llvm_backend.hpp"
  2. #include "llvm_abi.cpp"
  3. gb_global lbAddr lb_global_type_info_data = {};
  4. gb_global lbAddr lb_global_type_info_member_types = {};
  5. gb_global lbAddr lb_global_type_info_member_names = {};
  6. gb_global lbAddr lb_global_type_info_member_offsets = {};
  7. gb_global lbAddr lb_global_type_info_member_usings = {};
  8. gb_global lbAddr lb_global_type_info_member_tags = {};
  9. gb_global isize lb_global_type_info_data_index = 0;
  10. gb_global isize lb_global_type_info_member_types_index = 0;
  11. gb_global isize lb_global_type_info_member_names_index = 0;
  12. gb_global isize lb_global_type_info_member_offsets_index = 0;
  13. gb_global isize lb_global_type_info_member_usings_index = 0;
  14. gb_global isize lb_global_type_info_member_tags_index = 0;
  15. struct lbLoopData {
  16. lbAddr idx_addr;
  17. lbValue idx;
  18. lbBlock *body;
  19. lbBlock *done;
  20. lbBlock *loop;
  21. };
  22. struct lbCompoundLitElemTempData {
  23. Ast * expr;
  24. lbValue value;
  25. i32 elem_index;
  26. lbValue gep;
  27. };
  28. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32);
  29. void lb_loop_end(lbProcedure *p, lbLoopData const &data);
  30. LLVMValueRef llvm_zero(lbModule *m) {
  31. return LLVMConstInt(lb_type(m, t_int), 0, false);
  32. }
  33. LLVMValueRef llvm_one(lbModule *m) {
  34. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  35. }
  36. lbValue lb_zero(lbModule *m, Type *t) {
  37. lbValue v = {};
  38. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  39. v.type = t;
  40. return v;
  41. }
  42. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  43. lbValue v = lb_find_or_add_entity_string(m, str);
  44. unsigned indices[1] = {0};
  45. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  46. }
  47. bool lb_is_instr_terminating(LLVMValueRef instr) {
  48. if (instr != nullptr) {
  49. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  50. switch (op) {
  51. case LLVMRet:
  52. case LLVMBr:
  53. case LLVMSwitch:
  54. case LLVMIndirectBr:
  55. case LLVMInvoke:
  56. case LLVMUnreachable:
  57. case LLVMCallBr:
  58. return true;
  59. }
  60. }
  61. return false;
  62. }
  63. lbAddr lb_addr(lbValue addr) {
  64. lbAddr v = {lbAddr_Default, addr};
  65. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  66. GB_ASSERT(is_type_pointer(addr.type));
  67. v.kind = lbAddr_RelativePointer;
  68. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  69. GB_ASSERT(is_type_pointer(addr.type));
  70. v.kind = lbAddr_RelativeSlice;
  71. }
  72. return v;
  73. }
  74. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  75. lbAddr v = {lbAddr_Map, addr};
  76. v.map.key = map_key;
  77. v.map.type = map_type;
  78. v.map.result = map_result;
  79. return v;
  80. }
  81. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  82. lbAddr v = {lbAddr_SoaVariable, addr};
  83. v.soa.index = index;
  84. v.soa.index_expr = index_expr;
  85. return v;
  86. }
  87. Type *lb_addr_type(lbAddr const &addr) {
  88. if (addr.addr.value == nullptr) {
  89. return nullptr;
  90. }
  91. if (addr.kind == lbAddr_Map) {
  92. Type *t = base_type(addr.map.type);
  93. GB_ASSERT(is_type_map(t));
  94. return t->Map.value;
  95. }
  96. return type_deref(addr.addr.type);
  97. }
  98. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  99. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  100. }
  101. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  102. if (addr.addr.value == nullptr) {
  103. GB_PANIC("Illegal addr -> nullptr");
  104. return {};
  105. }
  106. switch (addr.kind) {
  107. case lbAddr_Map: {
  108. Type *map_type = base_type(addr.map.type);
  109. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  110. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  111. auto args = array_make<lbValue>(permanent_allocator(), 2);
  112. args[0] = h;
  113. args[1] = key;
  114. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  115. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  116. }
  117. case lbAddr_RelativePointer: {
  118. Type *rel_ptr = base_type(lb_addr_type(addr));
  119. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  120. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  121. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  122. offset = lb_emit_load(p, offset);
  123. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  124. offset = lb_emit_conv(p, offset, t_i64);
  125. }
  126. offset = lb_emit_conv(p, offset, t_uintptr);
  127. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  128. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  129. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  130. // NOTE(bill): nil check
  131. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  132. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  133. return final_ptr;
  134. }
  135. case lbAddr_Context:
  136. GB_PANIC("lbAddr_Context should be handled elsewhere");
  137. }
  138. return addr.addr;
  139. }
  140. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  141. lbAddr addr = lb_build_addr(p, expr);
  142. return lb_addr_get_ptr(p, addr);
  143. }
  144. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  145. if (build_context.no_bounds_check) {
  146. return;
  147. }
  148. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  149. return;
  150. }
  151. index = lb_emit_conv(p, index, t_int);
  152. len = lb_emit_conv(p, len, t_int);
  153. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  154. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  155. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  156. auto args = array_make<lbValue>(permanent_allocator(), 5);
  157. args[0] = file;
  158. args[1] = line;
  159. args[2] = column;
  160. args[3] = index;
  161. args[4] = len;
  162. lb_emit_runtime_call(p, "bounds_check_error", args);
  163. }
  164. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  165. if (build_context.no_bounds_check) {
  166. return;
  167. }
  168. if ((p->module->state_flags & StateFlag_no_bounds_check) != 0) {
  169. return;
  170. }
  171. lbValue file = lb_find_or_add_entity_string(p->module, token.pos.file);
  172. lbValue line = lb_const_int(p->module, t_int, token.pos.line);
  173. lbValue column = lb_const_int(p->module, t_int, token.pos.column);
  174. high = lb_emit_conv(p, high, t_int);
  175. if (!lower_value_used) {
  176. auto args = array_make<lbValue>(permanent_allocator(), 5);
  177. args[0] = file;
  178. args[1] = line;
  179. args[2] = column;
  180. args[3] = high;
  181. args[4] = len;
  182. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  183. } else {
  184. // No need to convert unless used
  185. low = lb_emit_conv(p, low, t_int);
  186. auto args = array_make<lbValue>(permanent_allocator(), 6);
  187. args[0] = file;
  188. args[1] = line;
  189. args[2] = column;
  190. args[3] = low;
  191. args[4] = high;
  192. args[5] = len;
  193. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  194. }
  195. }
  196. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  197. if (addr.addr.value == nullptr) {
  198. return;
  199. }
  200. GB_ASSERT(value.type != nullptr);
  201. if (is_type_untyped_undef(value.type)) {
  202. Type *t = lb_addr_type(addr);
  203. value.type = t;
  204. value.value = LLVMGetUndef(lb_type(p->module, t));
  205. } else if (is_type_untyped_nil(value.type)) {
  206. Type *t = lb_addr_type(addr);
  207. value.type = t;
  208. value.value = LLVMConstNull(lb_type(p->module, t));
  209. }
  210. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  211. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  212. }
  213. if (addr.kind == lbAddr_RelativePointer) {
  214. Type *rel_ptr = base_type(lb_addr_type(addr));
  215. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  216. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  217. GB_ASSERT(is_type_pointer(addr.addr.type));
  218. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  219. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  220. lbValue offset = {};
  221. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  222. offset.type = t_uintptr;
  223. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  224. offset = lb_emit_conv(p, offset, t_i64);
  225. }
  226. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  227. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  228. offset = lb_emit_select(p,
  229. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  230. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  231. offset
  232. );
  233. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  234. return;
  235. } else if (addr.kind == lbAddr_RelativeSlice) {
  236. Type *rel_ptr = base_type(lb_addr_type(addr));
  237. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  238. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  239. GB_ASSERT(is_type_pointer(addr.addr.type));
  240. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  241. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  242. lbValue offset = {};
  243. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  244. offset.type = t_uintptr;
  245. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  246. offset = lb_emit_conv(p, offset, t_i64);
  247. }
  248. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  249. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  250. offset = lb_emit_select(p,
  251. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  252. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  253. offset
  254. );
  255. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  256. lbValue len = lb_slice_len(p, value);
  257. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  258. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  259. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  260. return;
  261. } else if (addr.kind == lbAddr_AtomOp_index_set) {
  262. lbValue ptr = addr.addr;
  263. lbValue index = addr.index_set.index;
  264. Ast *node = addr.index_set.node;
  265. ast_node(ce, CallExpr, node);
  266. Type *proc_type = type_and_value_of_expr(ce->proc).type;
  267. proc_type = base_type(proc_type);
  268. GB_ASSERT(is_type_proc(proc_type));
  269. TypeProc *pt = &proc_type->Proc;
  270. isize arg_count = 3;
  271. isize param_count = 0;
  272. if (pt->params) {
  273. GB_ASSERT(pt->params->kind == Type_Tuple);
  274. param_count = pt->params->Tuple.variables.count;
  275. }
  276. auto args = array_make<lbValue>(permanent_allocator(), gb_max(arg_count, param_count));
  277. args[0] = ptr;
  278. args[1] = index;
  279. args[2] = value;
  280. isize arg_index = arg_count;
  281. if (arg_count < param_count) {
  282. lbModule *m = p->module;
  283. String proc_name = {};
  284. if (p->entity != nullptr) {
  285. proc_name = p->entity->token.string;
  286. }
  287. TokenPos pos = ast_token(ce->proc).pos;
  288. TypeTuple *param_tuple = &pt->params->Tuple;
  289. isize end = cast(isize)param_count;
  290. while (arg_index < end) {
  291. Entity *e = param_tuple->variables[arg_index];
  292. GB_ASSERT(e->kind == Entity_Variable);
  293. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  294. }
  295. }
  296. Entity *e = entity_from_expr(ce->proc);
  297. GB_ASSERT(e != nullptr);
  298. GB_ASSERT(is_type_polymorphic(e->type));
  299. {
  300. lbValue *found = nullptr;
  301. if (p->module != e->code_gen_module) {
  302. gb_mutex_lock(&p->module->mutex);
  303. }
  304. GB_ASSERT(e->code_gen_module != nullptr);
  305. found = map_get(&e->code_gen_module->values, hash_entity(e));
  306. if (p->module != e->code_gen_module) {
  307. gb_mutex_unlock(&p->module->mutex);
  308. }
  309. GB_ASSERT_MSG(found != nullptr, "%.*s", LIT(e->token.string));
  310. lb_emit_call(p, *found, args);
  311. }
  312. return;
  313. } else if (addr.kind == lbAddr_Map) {
  314. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  315. return;
  316. } else if (addr.kind == lbAddr_Context) {
  317. lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p));
  318. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  319. lb_addr_store(p, next_addr, old);
  320. lb_push_context_onto_stack(p, next_addr);
  321. lbValue next = lb_addr_get_ptr(p, next_addr);
  322. if (addr.ctx.sel.index.count > 0) {
  323. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  324. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  325. lb_emit_store(p, lhs, rhs);
  326. } else {
  327. lbValue lhs = next;
  328. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  329. lb_emit_store(p, lhs, rhs);
  330. }
  331. return;
  332. } else if (addr.kind == lbAddr_SoaVariable) {
  333. Type *t = type_deref(addr.addr.type);
  334. t = base_type(t);
  335. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  336. value = lb_emit_conv(p, value, t->Struct.soa_elem);
  337. lbValue index = addr.soa.index;
  338. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  339. Type *t = base_type(type_deref(addr.addr.type));
  340. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  341. i64 count = t->Struct.soa_count;
  342. lbValue len = lb_const_int(p->module, t_int, count);
  343. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  344. }
  345. for_array(i, t->Struct.fields) {
  346. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  347. dst = lb_emit_array_ep(p, dst, index);
  348. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  349. lb_emit_store(p, dst, src);
  350. }
  351. return;
  352. }
  353. GB_ASSERT(value.value != nullptr);
  354. value = lb_emit_conv(p, value, lb_addr_type(addr));
  355. if (lb_is_const_or_global(value)) {
  356. // NOTE(bill): Just bypass the actual storage and set the initializer
  357. if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  358. LLVMSetInitializer(addr.addr.value, value.value);
  359. return;
  360. }
  361. }
  362. lb_emit_store(p, addr.addr, value);
  363. }
  364. void lb_const_store(lbValue ptr, lbValue value) {
  365. GB_ASSERT(lb_is_const(ptr));
  366. GB_ASSERT(lb_is_const(value));
  367. GB_ASSERT(is_type_pointer(ptr.type));
  368. LLVMSetInitializer(ptr.value, value.value);
  369. }
  370. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  371. GB_ASSERT(value.value != nullptr);
  372. Type *a = type_deref(ptr.type);
  373. if (is_type_boolean(a)) {
  374. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  375. value = lb_emit_conv(p, value, a);
  376. }
  377. Type *ca = core_type(a);
  378. if (ca->kind == Type_Basic) {
  379. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  380. }
  381. if (is_type_proc(a)) {
  382. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  383. // stored as regular pointer with no procedure information
  384. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  385. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  386. LLVMBuildStore(p->builder, v, ptr.value);
  387. } else {
  388. Type *ca = core_type(a);
  389. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  390. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  391. } else {
  392. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  393. }
  394. LLVMBuildStore(p->builder, value.value, ptr.value);
  395. }
  396. }
  397. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  398. lbModule *m = p->module;
  399. GB_ASSERT(value.value != nullptr);
  400. Type *t = type_deref(value.type);
  401. LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, "");
  402. return lbValue{v, t};
  403. }
  404. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  405. GB_ASSERT(addr.addr.value != nullptr);
  406. if (addr.kind == lbAddr_RelativePointer) {
  407. Type *rel_ptr = base_type(lb_addr_type(addr));
  408. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  409. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  410. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  411. offset = lb_emit_load(p, offset);
  412. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  413. offset = lb_emit_conv(p, offset, t_i64);
  414. }
  415. offset = lb_emit_conv(p, offset, t_uintptr);
  416. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  417. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  418. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  419. // NOTE(bill): nil check
  420. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  421. lbValue final_ptr = {};
  422. final_ptr.type = absolute_ptr.type;
  423. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  424. return lb_emit_load(p, final_ptr);
  425. } else if (addr.kind == lbAddr_RelativeSlice) {
  426. Type *rel_ptr = base_type(lb_addr_type(addr));
  427. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  428. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  429. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  430. lbValue offset = lb_emit_load(p, offset_ptr);
  431. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  432. offset = lb_emit_conv(p, offset, t_i64);
  433. }
  434. offset = lb_emit_conv(p, offset, t_uintptr);
  435. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  436. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  437. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  438. Type *slice_elem = slice_type->Slice.elem;
  439. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  440. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  441. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  442. // NOTE(bill): nil check
  443. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  444. lbValue data = {};
  445. data.type = absolute_ptr.type;
  446. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  447. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  448. len = lb_emit_conv(p, len, t_int);
  449. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  450. lb_fill_slice(p, slice, data, len);
  451. return lb_addr_load(p, slice);
  452. } else if (addr.kind == lbAddr_Map) {
  453. Type *map_type = base_type(addr.map.type);
  454. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  455. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  456. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  457. auto args = array_make<lbValue>(permanent_allocator(), 2);
  458. args[0] = h;
  459. args[1] = key;
  460. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  461. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  462. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  463. lbBlock *then = lb_create_block(p, "map.get.then");
  464. lbBlock *done = lb_create_block(p, "map.get.done");
  465. lb_emit_if(p, ok, then, done);
  466. lb_start_block(p, then);
  467. {
  468. // TODO(bill): mem copy it instead?
  469. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  470. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  471. lb_emit_store(p, gep0, lb_emit_load(p, value));
  472. }
  473. lb_emit_jump(p, done);
  474. lb_start_block(p, done);
  475. if (is_type_tuple(addr.map.result)) {
  476. return lb_addr_load(p, v);
  477. } else {
  478. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  479. return lb_emit_load(p, single);
  480. }
  481. } else if (addr.kind == lbAddr_Context) {
  482. lbValue a = addr.addr;
  483. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  484. if (addr.ctx.sel.index.count > 0) {
  485. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  486. return lb_emit_load(p, b);
  487. } else {
  488. return lb_emit_load(p, a);
  489. }
  490. } else if (addr.kind == lbAddr_SoaVariable) {
  491. Type *t = type_deref(addr.addr.type);
  492. t = base_type(t);
  493. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  494. Type *elem = t->Struct.soa_elem;
  495. lbValue len = {};
  496. if (t->Struct.soa_kind == StructSoa_Fixed) {
  497. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  498. } else {
  499. lbValue v = lb_emit_load(p, addr.addr);
  500. len = lb_soa_struct_len(p, v);
  501. }
  502. lbAddr res = lb_add_local_generated(p, elem, true);
  503. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  504. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  505. }
  506. if (t->Struct.soa_kind == StructSoa_Fixed) {
  507. for_array(i, t->Struct.fields) {
  508. Entity *field = t->Struct.fields[i];
  509. Type *base_type = field->type;
  510. GB_ASSERT(base_type->kind == Type_Array);
  511. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  512. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  513. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  514. lbValue src = lb_emit_load(p, src_ptr);
  515. lb_emit_store(p, dst, src);
  516. }
  517. } else {
  518. isize field_count = t->Struct.fields.count;
  519. if (t->Struct.soa_kind == StructSoa_Slice) {
  520. field_count -= 1;
  521. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  522. field_count -= 3;
  523. }
  524. for (isize i = 0; i < field_count; i++) {
  525. Entity *field = t->Struct.fields[i];
  526. Type *base_type = field->type;
  527. GB_ASSERT(base_type->kind == Type_Pointer);
  528. Type *elem = base_type->Pointer.elem;
  529. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  530. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  531. src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index);
  532. lbValue src = lb_emit_load(p, src_ptr);
  533. src = lb_emit_load(p, src);
  534. lb_emit_store(p, dst, src);
  535. }
  536. }
  537. return lb_addr_load(p, res);
  538. }
  539. if (is_type_proc(addr.addr.type)) {
  540. return addr.addr;
  541. }
  542. return lb_emit_load(p, addr.addr);
  543. }
  544. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  545. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  546. }
  547. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  548. Type *t = u.type;
  549. GB_ASSERT_MSG(is_type_pointer(t) &&
  550. is_type_union(type_deref(t)), "%s", type_to_string(t));
  551. Type *ut = type_deref(t);
  552. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  553. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  554. GB_ASSERT(type_size_of(ut) > 0);
  555. Type *tag_type = union_tag_type(ut);
  556. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  557. unsigned element_count = LLVMCountStructElementTypes(uvt);
  558. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  559. lbValue tag_ptr = {};
  560. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  561. tag_ptr.type = alloc_type_pointer(tag_type);
  562. return tag_ptr;
  563. }
  564. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  565. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  566. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  567. return lb_emit_load(p, tag_ptr);
  568. }
  569. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  570. Type *t = type_deref(parent.type);
  571. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  572. // No tag needed!
  573. } else {
  574. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  575. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  576. }
  577. }
  578. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  579. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  580. lb_emit_store(p, underlying, variant);
  581. lb_emit_store_union_variant_tag(p, parent, variant_type);
  582. }
  583. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  584. unsigned field_count = LLVMCountStructElementTypes(src);
  585. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  586. LLVMGetStructElementTypes(src, fields);
  587. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  588. }
  589. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  590. switch (alignment) {
  591. case 1:
  592. return LLVMArrayType(lb_type(m, t_u8), 0);
  593. case 2:
  594. return LLVMArrayType(lb_type(m, t_u16), 0);
  595. case 4:
  596. return LLVMArrayType(lb_type(m, t_u32), 0);
  597. case 8:
  598. return LLVMArrayType(lb_type(m, t_u64), 0);
  599. case 16:
  600. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  601. default:
  602. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  603. break;
  604. }
  605. return nullptr;
  606. }
  607. bool lb_is_elem_const(Ast *elem, Type *elem_type) {
  608. if (!elem_type_can_be_constant(elem_type)) {
  609. return false;
  610. }
  611. if (elem->kind == Ast_FieldValue) {
  612. elem = elem->FieldValue.value;
  613. }
  614. TypeAndValue tav = type_and_value_of_expr(elem);
  615. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type));
  616. return tav.value.kind != ExactValue_Invalid;
  617. }
  618. String lb_mangle_name(lbModule *m, Entity *e) {
  619. String name = e->token.string;
  620. AstPackage *pkg = e->pkg;
  621. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  622. String pkgn = pkg->name;
  623. GB_ASSERT(!rune_is_digit(pkgn[0]));
  624. if (pkgn == "llvm") {
  625. pkgn = str_lit("llvm$");
  626. }
  627. isize max_len = pkgn.len + 1 + name.len + 1;
  628. bool require_suffix_id = is_type_polymorphic(e->type, true);
  629. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  630. require_suffix_id = true;
  631. } else if (is_blank_ident(e->token)) {
  632. require_suffix_id = true;
  633. }if (e->flags & EntityFlag_NotExported) {
  634. require_suffix_id = true;
  635. }
  636. if (require_suffix_id) {
  637. max_len += 21;
  638. }
  639. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  640. isize new_name_len = gb_snprintf(
  641. new_name, max_len,
  642. "%.*s.%.*s", LIT(pkgn), LIT(name)
  643. );
  644. if (require_suffix_id) {
  645. char *str = new_name + new_name_len-1;
  646. isize len = max_len-new_name_len;
  647. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  648. new_name_len += extra-1;
  649. }
  650. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  651. return mangled_name;
  652. }
  653. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  654. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  655. // and as a result, the declaration does not have time to determine what it should be
  656. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  657. if (e->TypeName.ir_mangled_name.len != 0) {
  658. return e->TypeName.ir_mangled_name;
  659. }
  660. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  661. if (p == nullptr) {
  662. Entity *proc = nullptr;
  663. if (e->parent_proc_decl != nullptr) {
  664. proc = e->parent_proc_decl->entity;
  665. } else {
  666. Scope *scope = e->scope;
  667. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  668. scope = scope->parent;
  669. }
  670. GB_ASSERT(scope != nullptr);
  671. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  672. proc = scope->procedure_entity;
  673. }
  674. GB_ASSERT(proc->kind == Entity_Procedure);
  675. if (proc->code_gen_procedure != nullptr) {
  676. p = proc->code_gen_procedure;
  677. }
  678. }
  679. // NOTE(bill): Generate a new name
  680. // parent_proc.name-guid
  681. String ts_name = e->token.string;
  682. if (p != nullptr) {
  683. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  684. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  685. u32 guid = ++p->module->nested_type_name_guid;
  686. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  687. String name = make_string(cast(u8 *)name_text, name_len-1);
  688. e->TypeName.ir_mangled_name = name;
  689. return name;
  690. } else {
  691. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  692. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  693. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  694. static u32 guid = 0;
  695. guid += 1;
  696. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  697. String name = make_string(cast(u8 *)name_text, name_len-1);
  698. e->TypeName.ir_mangled_name = name;
  699. return name;
  700. }
  701. }
  702. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  703. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  704. return e->TypeName.ir_mangled_name;
  705. }
  706. GB_ASSERT(e != nullptr);
  707. if (e->pkg == nullptr) {
  708. return e->token.string;
  709. }
  710. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  711. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  712. }
  713. String name = {};
  714. bool no_name_mangle = false;
  715. if (e->kind == Entity_Variable) {
  716. bool is_foreign = e->Variable.is_foreign;
  717. bool is_export = e->Variable.is_export;
  718. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  719. if (e->Variable.link_name.len > 0) {
  720. return e->Variable.link_name;
  721. }
  722. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  723. return e->Procedure.link_name;
  724. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  725. no_name_mangle = true;
  726. }
  727. if (!no_name_mangle) {
  728. name = lb_mangle_name(m, e);
  729. }
  730. if (name.len == 0) {
  731. name = e->token.string;
  732. }
  733. if (e->kind == Entity_TypeName) {
  734. e->TypeName.ir_mangled_name = name;
  735. } else if (e->kind == Entity_Procedure) {
  736. e->Procedure.link_name = name;
  737. }
  738. return name;
  739. }
  740. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  741. Type *original_type = type;
  742. LLVMContextRef ctx = m->ctx;
  743. i64 size = type_size_of(type); // Check size
  744. GB_ASSERT(type != t_invalid);
  745. switch (type->kind) {
  746. case Type_Basic:
  747. switch (type->Basic.kind) {
  748. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  749. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  750. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  751. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  752. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  753. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  754. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  755. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  756. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  757. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  758. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  759. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  760. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  761. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  762. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  763. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  764. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  765. // Basic_f16,
  766. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  767. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  768. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  769. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  770. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  771. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  772. // Basic_complex32,
  773. case Basic_complex64:
  774. {
  775. char const *name = "..complex64";
  776. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  777. if (type != nullptr) {
  778. return type;
  779. }
  780. type = LLVMStructCreateNamed(ctx, name);
  781. LLVMTypeRef fields[2] = {
  782. lb_type(m, t_f32),
  783. lb_type(m, t_f32),
  784. };
  785. LLVMStructSetBody(type, fields, 2, false);
  786. return type;
  787. }
  788. case Basic_complex128:
  789. {
  790. char const *name = "..complex128";
  791. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  792. if (type != nullptr) {
  793. return type;
  794. }
  795. type = LLVMStructCreateNamed(ctx, name);
  796. LLVMTypeRef fields[2] = {
  797. lb_type(m, t_f64),
  798. lb_type(m, t_f64),
  799. };
  800. LLVMStructSetBody(type, fields, 2, false);
  801. return type;
  802. }
  803. case Basic_quaternion128:
  804. {
  805. char const *name = "..quaternion128";
  806. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  807. if (type != nullptr) {
  808. return type;
  809. }
  810. type = LLVMStructCreateNamed(ctx, name);
  811. LLVMTypeRef fields[4] = {
  812. lb_type(m, t_f32),
  813. lb_type(m, t_f32),
  814. lb_type(m, t_f32),
  815. lb_type(m, t_f32),
  816. };
  817. LLVMStructSetBody(type, fields, 4, false);
  818. return type;
  819. }
  820. case Basic_quaternion256:
  821. {
  822. char const *name = "..quaternion256";
  823. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  824. if (type != nullptr) {
  825. return type;
  826. }
  827. type = LLVMStructCreateNamed(ctx, name);
  828. LLVMTypeRef fields[4] = {
  829. lb_type(m, t_f64),
  830. lb_type(m, t_f64),
  831. lb_type(m, t_f64),
  832. lb_type(m, t_f64),
  833. };
  834. LLVMStructSetBody(type, fields, 4, false);
  835. return type;
  836. }
  837. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  838. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  839. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  840. case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0);
  841. case Basic_string:
  842. {
  843. char const *name = "..string";
  844. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  845. if (type != nullptr) {
  846. return type;
  847. }
  848. type = LLVMStructCreateNamed(ctx, name);
  849. LLVMTypeRef fields[2] = {
  850. LLVMPointerType(lb_type(m, t_u8), 0),
  851. lb_type(m, t_int),
  852. };
  853. LLVMStructSetBody(type, fields, 2, false);
  854. return type;
  855. }
  856. case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0);
  857. case Basic_any:
  858. {
  859. char const *name = "..any";
  860. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  861. if (type != nullptr) {
  862. return type;
  863. }
  864. type = LLVMStructCreateNamed(ctx, name);
  865. LLVMTypeRef fields[2] = {
  866. lb_type(m, t_rawptr),
  867. lb_type(m, t_typeid),
  868. };
  869. LLVMStructSetBody(type, fields, 2, false);
  870. return type;
  871. }
  872. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  873. // Endian Specific Types
  874. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  875. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  876. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  877. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  878. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  879. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  880. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  881. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  882. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  883. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  884. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  885. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  886. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  887. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  888. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  889. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  890. // Untyped types
  891. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  892. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  893. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  894. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  895. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  896. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  897. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  898. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  899. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  900. }
  901. break;
  902. case Type_Named:
  903. {
  904. Type *base = base_type(type->Named.base);
  905. switch (base->kind) {
  906. case Type_Basic:
  907. return lb_type_internal(m, base);
  908. case Type_Named:
  909. case Type_Generic:
  910. GB_PANIC("INVALID TYPE");
  911. break;
  912. case Type_Pointer:
  913. case Type_Array:
  914. case Type_EnumeratedArray:
  915. case Type_Slice:
  916. case Type_DynamicArray:
  917. case Type_Map:
  918. case Type_Enum:
  919. case Type_BitSet:
  920. case Type_SimdVector:
  921. return lb_type_internal(m, base);
  922. // TODO(bill): Deal with this correctly. Can this be named?
  923. case Type_Proc:
  924. return lb_type_internal(m, base);
  925. case Type_Tuple:
  926. return lb_type_internal(m, base);
  927. }
  928. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  929. if (found) {
  930. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  931. if (kind == LLVMStructTypeKind) {
  932. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  933. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  934. if (llvm_type != nullptr) {
  935. return llvm_type;
  936. }
  937. llvm_type = LLVMStructCreateNamed(ctx, name);
  938. map_set(&m->types, hash_type(type), llvm_type);
  939. lb_clone_struct_type(llvm_type, *found);
  940. return llvm_type;
  941. }
  942. }
  943. switch (base->kind) {
  944. case Type_Struct:
  945. case Type_Union:
  946. {
  947. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  948. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  949. if (llvm_type != nullptr) {
  950. return llvm_type;
  951. }
  952. llvm_type = LLVMStructCreateNamed(ctx, name);
  953. map_set(&m->types, hash_type(type), llvm_type);
  954. lb_clone_struct_type(llvm_type, lb_type(m, base));
  955. return llvm_type;
  956. }
  957. }
  958. return lb_type_internal(m, base);
  959. }
  960. case Type_Pointer:
  961. return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  962. case Type_Array:
  963. return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  964. case Type_EnumeratedArray:
  965. return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  966. case Type_Slice:
  967. {
  968. LLVMTypeRef fields[2] = {
  969. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  970. lb_type(m, t_int), // len
  971. };
  972. return LLVMStructTypeInContext(ctx, fields, 2, false);
  973. }
  974. break;
  975. case Type_DynamicArray:
  976. {
  977. LLVMTypeRef fields[4] = {
  978. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  979. lb_type(m, t_int), // len
  980. lb_type(m, t_int), // cap
  981. lb_type(m, t_allocator), // allocator
  982. };
  983. return LLVMStructTypeInContext(ctx, fields, 4, false);
  984. }
  985. break;
  986. case Type_Map:
  987. return lb_type(m, type->Map.internal_type);
  988. case Type_Struct:
  989. {
  990. if (type->Struct.is_raw_union) {
  991. unsigned field_count = 2;
  992. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  993. i64 alignment = type_align_of(type);
  994. unsigned size_of_union = cast(unsigned)type_size_of(type);
  995. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  996. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  997. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  998. }
  999. isize offset = 0;
  1000. if (type->Struct.custom_align > 0) {
  1001. offset = 1;
  1002. }
  1003. m->internal_type_level += 1;
  1004. defer (m->internal_type_level -= 1);
  1005. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1006. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1007. for_array(i, type->Struct.fields) {
  1008. Entity *field = type->Struct.fields[i];
  1009. fields[i+offset] = lb_type(m, field->type);
  1010. }
  1011. if (type->Struct.custom_align > 0) {
  1012. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1013. }
  1014. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1015. }
  1016. break;
  1017. case Type_Union:
  1018. if (type->Union.variants.count == 0) {
  1019. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1020. } else {
  1021. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1022. // LLVM takes the first element's alignment as the entire alignment (like C)
  1023. i64 align = type_align_of(type);
  1024. i64 size = type_size_of(type);
  1025. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1026. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1027. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1028. }
  1029. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1030. LLVMTypeRef fields[3] = {};
  1031. unsigned field_count = 1;
  1032. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1033. if (is_type_union_maybe_pointer(type)) {
  1034. field_count += 1;
  1035. fields[1] = lb_type(m, type->Union.variants[0]);
  1036. } else {
  1037. field_count += 2;
  1038. if (block_size == align) {
  1039. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1040. } else {
  1041. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1042. }
  1043. fields[2] = lb_type(m, union_tag_type(type));
  1044. }
  1045. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1046. }
  1047. break;
  1048. case Type_Enum:
  1049. return lb_type(m, base_enum_type(type));
  1050. case Type_Tuple:
  1051. if (type->Tuple.variables.count == 1) {
  1052. return lb_type(m, type->Tuple.variables[0]->type);
  1053. } else {
  1054. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1055. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1056. for_array(i, type->Tuple.variables) {
  1057. Entity *field = type->Tuple.variables[i];
  1058. LLVMTypeRef param_type = nullptr;
  1059. param_type = lb_type(m, field->type);
  1060. fields[i] = param_type;
  1061. }
  1062. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1063. }
  1064. case Type_Proc:
  1065. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1066. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1067. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1068. } else {
  1069. unsigned param_count = 0;
  1070. if (type->Proc.calling_convention == ProcCC_Odin) {
  1071. param_count += 1;
  1072. }
  1073. if (type->Proc.param_count != 0) {
  1074. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1075. for_array(i, type->Proc.params->Tuple.variables) {
  1076. Entity *e = type->Proc.params->Tuple.variables[i];
  1077. if (e->kind != Entity_Variable) {
  1078. continue;
  1079. }
  1080. param_count += 1;
  1081. }
  1082. }
  1083. m->internal_type_level += 1;
  1084. defer (m->internal_type_level -= 1);
  1085. LLVMTypeRef ret = nullptr;
  1086. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1087. if (type->Proc.result_count != 0) {
  1088. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1089. ret = lb_type(m, single_ret);
  1090. if (ret != nullptr) {
  1091. if (is_type_boolean(single_ret) &&
  1092. is_calling_convention_none(type->Proc.calling_convention) &&
  1093. type_size_of(single_ret) <= 1) {
  1094. ret = LLVMInt1TypeInContext(m->ctx);
  1095. }
  1096. }
  1097. }
  1098. isize param_index = 0;
  1099. if (type->Proc.param_count != 0) {
  1100. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1101. for_array(i, type->Proc.params->Tuple.variables) {
  1102. Entity *e = type->Proc.params->Tuple.variables[i];
  1103. if (e->kind != Entity_Variable) {
  1104. continue;
  1105. }
  1106. Type *e_type = reduce_tuple_to_single_type(e->type);
  1107. LLVMTypeRef param_type = nullptr;
  1108. if (is_type_boolean(e_type) &&
  1109. type_size_of(e_type) <= 1) {
  1110. param_type = LLVMInt1TypeInContext(m->ctx);
  1111. } else {
  1112. if (is_type_proc(e_type)) {
  1113. param_type = lb_type(m, t_rawptr);
  1114. } else {
  1115. param_type = lb_type(m, e_type);
  1116. }
  1117. }
  1118. params[param_index++] = param_type;
  1119. }
  1120. }
  1121. if (param_index < param_count) {
  1122. params[param_index++] = lb_type(m, t_rawptr);
  1123. // params[param_index++] = lb_type(m, t_context_ptr);
  1124. }
  1125. GB_ASSERT(param_index == param_count);
  1126. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1127. map_set(&m->function_type_map, hash_type(type), ft);
  1128. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1129. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1130. // LLVMTypeRef new_ret = LLVMGetReturnType(new_abi_fn_type);
  1131. // LLVMTypeRef old_ret = LLVMGetReturnType(old_abi_fn_type);
  1132. // unsigned new_count = LLVMCountParamTypes(new_abi_fn_type);
  1133. // unsigned old_count = LLVMCountParamTypes(old_abi_fn_type);
  1134. // 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));
  1135. return new_abi_fn_ptr_type;
  1136. }
  1137. break;
  1138. case Type_BitSet:
  1139. {
  1140. Type *ut = bit_set_to_int(type);
  1141. return lb_type(m, ut);
  1142. }
  1143. case Type_SimdVector:
  1144. if (type->SimdVector.is_x86_mmx) {
  1145. return LLVMX86MMXTypeInContext(ctx);
  1146. }
  1147. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1148. case Type_RelativePointer:
  1149. return lb_type_internal(m, type->RelativePointer.base_integer);
  1150. case Type_RelativeSlice:
  1151. {
  1152. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1153. unsigned field_count = 2;
  1154. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1155. fields[0] = base_integer;
  1156. fields[1] = base_integer;
  1157. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1158. }
  1159. }
  1160. GB_PANIC("Invalid type %s", type_to_string(type));
  1161. return LLVMInt32TypeInContext(ctx);
  1162. }
  1163. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1164. type = default_type(type);
  1165. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1166. if (found) {
  1167. return *found;
  1168. }
  1169. LLVMTypeRef llvm_type = nullptr;
  1170. m->internal_type_level += 1;
  1171. llvm_type = lb_type_internal(m, type);
  1172. m->internal_type_level -= 1;
  1173. if (m->internal_type_level == 0) {
  1174. map_set(&m->types, hash_type(type), llvm_type);
  1175. if (is_type_named(type)) {
  1176. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1177. }
  1178. }
  1179. return llvm_type;
  1180. }
  1181. LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) {
  1182. Type *original_type = type;
  1183. LLVMContextRef ctx = m->ctx;
  1184. i64 size = type_size_of(type); // Check size
  1185. GB_ASSERT(type != t_invalid);
  1186. switch (type->kind) {
  1187. case Type_Basic:
  1188. switch (type->Basic.kind) {
  1189. case Basic_llvm_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "llvm bool", 9, 1, 0, LLVMDIFlagZero);
  1190. case Basic_bool: return LLVMDIBuilderCreateBasicType(m->debug_builder, "bool", 4, 8, 0, LLVMDIFlagZero);
  1191. case Basic_b8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b8", 2, 8, 0, LLVMDIFlagZero);
  1192. case Basic_b16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b16", 3, 16, 0, LLVMDIFlagZero);
  1193. case Basic_b32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b32", 3, 32, 0, LLVMDIFlagZero);
  1194. case Basic_b64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "b64", 3, 64, 0, LLVMDIFlagZero);
  1195. case Basic_i8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i8", 2, 8, 0, LLVMDIFlagZero);
  1196. case Basic_u8: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u8", 2, 8, 0, LLVMDIFlagZero);
  1197. case Basic_i16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16", 3, 16, 0, LLVMDIFlagZero);
  1198. case Basic_u16: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16", 3, 16, 0, LLVMDIFlagZero);
  1199. case Basic_i32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32", 3, 32, 0, LLVMDIFlagZero);
  1200. case Basic_u32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32", 3, 32, 0, LLVMDIFlagZero);
  1201. case Basic_i64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64", 3, 64, 0, LLVMDIFlagZero);
  1202. case Basic_u64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64", 3, 64, 0, LLVMDIFlagZero);
  1203. case Basic_i128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128", 4, 128, 0, LLVMDIFlagZero);
  1204. case Basic_u128: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128", 4, 128, 0, LLVMDIFlagZero);
  1205. case Basic_rune: return LLVMDIBuilderCreateBasicType(m->debug_builder, "rune", 4, 32, 0, LLVMDIFlagZero);
  1206. // Basic_f16,
  1207. case Basic_f32: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f32", 3, 32, 0, LLVMDIFlagZero);
  1208. case Basic_f64: return LLVMDIBuilderCreateBasicType(m->debug_builder, "f64", 3, 64, 0, LLVMDIFlagZero);
  1209. // Basic_complex32,
  1210. case Basic_complex64:
  1211. {
  1212. return nullptr;
  1213. // char const *name = "..complex64";
  1214. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1215. // if (type != nullptr) {
  1216. // return type;
  1217. // }
  1218. // type = LLVMStructCreateNamed(ctx, name);
  1219. // LLVMTypeRef fields[2] = {
  1220. // lb_type(m, t_f32),
  1221. // lb_type(m, t_f32),
  1222. // };
  1223. // LLVMStructSetBody(type, fields, 2, false);
  1224. // return type;
  1225. }
  1226. case Basic_complex128:
  1227. {
  1228. return nullptr;
  1229. // char const *name = "..complex128";
  1230. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1231. // if (type != nullptr) {
  1232. // return type;
  1233. // }
  1234. // type = LLVMStructCreateNamed(ctx, name);
  1235. // LLVMTypeRef fields[2] = {
  1236. // lb_type(m, t_f64),
  1237. // lb_type(m, t_f64),
  1238. // };
  1239. // LLVMStructSetBody(type, fields, 2, false);
  1240. // return type;
  1241. }
  1242. case Basic_quaternion128:
  1243. {
  1244. return nullptr;
  1245. // char const *name = "..quaternion128";
  1246. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1247. // if (type != nullptr) {
  1248. // return type;
  1249. // }
  1250. // type = LLVMStructCreateNamed(ctx, name);
  1251. // LLVMTypeRef fields[4] = {
  1252. // lb_type(m, t_f32),
  1253. // lb_type(m, t_f32),
  1254. // lb_type(m, t_f32),
  1255. // lb_type(m, t_f32),
  1256. // };
  1257. // LLVMStructSetBody(type, fields, 4, false);
  1258. // return type;
  1259. }
  1260. case Basic_quaternion256:
  1261. {
  1262. return nullptr;
  1263. // char const *name = "..quaternion256";
  1264. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1265. // if (type != nullptr) {
  1266. // return type;
  1267. // }
  1268. // type = LLVMStructCreateNamed(ctx, name);
  1269. // LLVMTypeRef fields[4] = {
  1270. // lb_type(m, t_f64),
  1271. // lb_type(m, t_f64),
  1272. // lb_type(m, t_f64),
  1273. // lb_type(m, t_f64),
  1274. // };
  1275. // LLVMStructSetBody(type, fields, 4, false);
  1276. // return type;
  1277. }
  1278. case Basic_int: return LLVMDIBuilderCreateBasicType(m->debug_builder, "int", 3, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1279. case Basic_uint: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uint", 4, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1280. case Basic_uintptr: return LLVMDIBuilderCreateBasicType(m->debug_builder, "uintptr", 7, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1281. case Basic_rawptr:
  1282. return nullptr;
  1283. // return LLVMPointerType(LLVMInt8Type(), 0);
  1284. case Basic_string:
  1285. {
  1286. return nullptr;
  1287. // char const *name = "..string";
  1288. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1289. // if (type != nullptr) {
  1290. // return type;
  1291. // }
  1292. // type = LLVMStructCreateNamed(ctx, name);
  1293. // LLVMTypeRef fields[2] = {
  1294. // LLVMPointerType(lb_type(m, t_u8), 0),
  1295. // lb_type(m, t_int),
  1296. // };
  1297. // LLVMStructSetBody(type, fields, 2, false);
  1298. // return type;
  1299. }
  1300. case Basic_cstring:
  1301. return nullptr;
  1302. // return LLVMPointerType(LLVMInt8Type(), 0);
  1303. case Basic_any:
  1304. {
  1305. return nullptr;
  1306. // char const *name = "..any";
  1307. // LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1308. // if (type != nullptr) {
  1309. // return type;
  1310. // }
  1311. // type = LLVMStructCreateNamed(ctx, name);
  1312. // LLVMTypeRef fields[2] = {
  1313. // lb_type(m, t_rawptr),
  1314. // lb_type(m, t_typeid),
  1315. // };
  1316. // LLVMStructSetBody(type, fields, 2, false);
  1317. // return type;
  1318. }
  1319. case Basic_typeid: return LLVMDIBuilderCreateBasicType(m->debug_builder, "typeid", 6, 8*cast(unsigned)build_context.word_size, 0, LLVMDIFlagZero);
  1320. // Endian Specific Types
  1321. case Basic_i16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1322. case Basic_u16le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16le", 5, 16, 0, LLVMDIFlagLittleEndian);
  1323. case Basic_i32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1324. case Basic_u32le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32le", 5, 32, 0, LLVMDIFlagLittleEndian);
  1325. case Basic_i64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1326. case Basic_u64le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64le", 5, 64, 0, LLVMDIFlagLittleEndian);
  1327. case Basic_i128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1328. case Basic_u128le: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128le", 6, 128, 0, LLVMDIFlagLittleEndian);
  1329. case Basic_i16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1330. case Basic_u16be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u16be", 5, 16, 0, LLVMDIFlagBigEndian);
  1331. case Basic_i32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1332. case Basic_u32be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u32be", 5, 32, 0, LLVMDIFlagBigEndian);
  1333. case Basic_i64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1334. case Basic_u64be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u64be", 5, 64, 0, LLVMDIFlagBigEndian);
  1335. case Basic_i128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "i128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1336. case Basic_u128be: return LLVMDIBuilderCreateBasicType(m->debug_builder, "u128be", 6, 128, 0, LLVMDIFlagBigEndian);
  1337. // Untyped types
  1338. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1339. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1340. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1341. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1342. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1343. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1344. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1345. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1346. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1347. }
  1348. break;
  1349. case Type_Named:
  1350. {
  1351. return nullptr;
  1352. // Type *base = base_type(type->Named.base);
  1353. // switch (base->kind) {
  1354. // case Type_Basic:
  1355. // return lb_type(m, base);
  1356. // case Type_Named:
  1357. // case Type_Generic:
  1358. // case Type_BitFieldValue:
  1359. // GB_PANIC("INVALID TYPE");
  1360. // break;
  1361. // case Type_Opaque:
  1362. // return lb_type(m, base->Opaque.elem);
  1363. // case Type_Pointer:
  1364. // case Type_Array:
  1365. // case Type_EnumeratedArray:
  1366. // case Type_Slice:
  1367. // case Type_DynamicArray:
  1368. // case Type_Map:
  1369. // case Type_Enum:
  1370. // case Type_BitSet:
  1371. // case Type_SimdVector:
  1372. // return lb_type(m, base);
  1373. // // TODO(bill): Deal with this correctly. Can this be named?
  1374. // case Type_Proc:
  1375. // return lb_type(m, base);
  1376. // case Type_Tuple:
  1377. // return lb_type(m, base);
  1378. // }
  1379. // LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1380. // if (found) {
  1381. // LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1382. // if (kind == LLVMStructTypeKind) {
  1383. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1384. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1385. // if (llvm_type != nullptr) {
  1386. // return llvm_type;
  1387. // }
  1388. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1389. // map_set(&m->types, hash_type(type), llvm_type);
  1390. // lb_clone_struct_type(llvm_type, *found);
  1391. // return llvm_type;
  1392. // }
  1393. // }
  1394. // switch (base->kind) {
  1395. // case Type_Struct:
  1396. // case Type_Union:
  1397. // case Type_BitField:
  1398. // {
  1399. // char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1400. // LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1401. // if (llvm_type != nullptr) {
  1402. // return llvm_type;
  1403. // }
  1404. // llvm_type = LLVMStructCreateNamed(ctx, name);
  1405. // map_set(&m->types, hash_type(type), llvm_type);
  1406. // lb_clone_struct_type(llvm_type, lb_type(m, base));
  1407. // return llvm_type;
  1408. // }
  1409. // }
  1410. // return lb_type(m, base);
  1411. }
  1412. case Type_Pointer:
  1413. return nullptr;
  1414. // return LLVMPointerType(lb_type(m, type_deref(type)), 0);
  1415. case Type_Array:
  1416. return nullptr;
  1417. // return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1418. case Type_EnumeratedArray:
  1419. return nullptr;
  1420. // return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1421. case Type_Slice:
  1422. {
  1423. return nullptr;
  1424. // LLVMTypeRef fields[2] = {
  1425. // LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1426. // lb_type(m, t_int), // len
  1427. // };
  1428. // return LLVMStructTypeInContext(ctx, fields, 2, false);
  1429. }
  1430. break;
  1431. case Type_DynamicArray:
  1432. {
  1433. return nullptr;
  1434. // LLVMTypeRef fields[4] = {
  1435. // LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1436. // lb_type(m, t_int), // len
  1437. // lb_type(m, t_int), // cap
  1438. // lb_type(m, t_allocator), // allocator
  1439. // };
  1440. // return LLVMStructTypeInContext(ctx, fields, 4, false);
  1441. }
  1442. break;
  1443. case Type_Map:
  1444. return nullptr;
  1445. // return lb_type(m, type->Map.internal_type);
  1446. case Type_Struct:
  1447. {
  1448. return nullptr;
  1449. // if (type->Struct.is_raw_union) {
  1450. // unsigned field_count = 2;
  1451. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1452. // i64 alignment = type_align_of(type);
  1453. // unsigned size_of_union = cast(unsigned)type_size_of(type);
  1454. // fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1455. // fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1456. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1457. // }
  1458. // isize offset = 0;
  1459. // if (type->Struct.custom_align > 0) {
  1460. // offset = 1;
  1461. // }
  1462. // unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1463. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1464. // GB_ASSERT(fields != nullptr);
  1465. // defer (gb_free(heap_allocator(), fields));
  1466. // for_array(i, type->Struct.fields) {
  1467. // Entity *field = type->Struct.fields[i];
  1468. // fields[i+offset] = lb_type(m, field->type);
  1469. // }
  1470. // if (type->Struct.custom_align > 0) {
  1471. // fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1472. // }
  1473. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1474. }
  1475. break;
  1476. case Type_Union:
  1477. return nullptr;
  1478. // if (type->Union.variants.count == 0) {
  1479. // return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1480. // } else {
  1481. // // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1482. // // LLVM takes the first element's alignment as the entire alignment (like C)
  1483. // i64 align = type_align_of(type);
  1484. // i64 size = type_size_of(type);
  1485. // if (is_type_union_maybe_pointer_original_alignment(type)) {
  1486. // LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1487. // return LLVMStructTypeInContext(ctx, fields, 1, false);
  1488. // }
  1489. // unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1490. // LLVMTypeRef fields[3] = {};
  1491. // unsigned field_count = 1;
  1492. // fields[0] = lb_alignment_prefix_type_hack(m, align);
  1493. // if (is_type_union_maybe_pointer(type)) {
  1494. // field_count += 1;
  1495. // fields[1] = lb_type(m, type->Union.variants[0]);
  1496. // } else {
  1497. // field_count += 2;
  1498. // if (block_size == align) {
  1499. // fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1500. // } else {
  1501. // fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1502. // }
  1503. // fields[2] = lb_type(m, union_tag_type(type));
  1504. // }
  1505. // return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1506. // }
  1507. // break;
  1508. case Type_Enum:
  1509. return nullptr;
  1510. // return lb_type(m, base_enum_type(type));
  1511. case Type_Tuple:
  1512. return nullptr;
  1513. // if (type->Tuple.variables.count == 1) {
  1514. // return lb_type(m, type->Tuple.variables[0]->type);
  1515. // } else {
  1516. // unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1517. // LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1518. // defer (gb_free(heap_allocator(), fields));
  1519. // for_array(i, type->Tuple.variables) {
  1520. // Entity *field = type->Tuple.variables[i];
  1521. // fields[i] = lb_type(m, field->type);
  1522. // }
  1523. // return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1524. // }
  1525. case Type_Proc:
  1526. {
  1527. return nullptr;
  1528. // set_procedure_abi_types(type);
  1529. // LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx);
  1530. // isize offset = 0;
  1531. // if (type->Proc.return_by_pointer) {
  1532. // offset = 1;
  1533. // } else if (type->Proc.abi_compat_result_type != nullptr) {
  1534. // return_type = lb_type(m, type->Proc.abi_compat_result_type);
  1535. // }
  1536. // isize extra_param_count = offset;
  1537. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1538. // extra_param_count += 1;
  1539. // }
  1540. // isize param_count = type->Proc.abi_compat_params.count + extra_param_count;
  1541. // LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1542. // defer (gb_free(heap_allocator(), param_types));
  1543. // isize param_index = offset;
  1544. // for_array(i, type->Proc.abi_compat_params) {
  1545. // Type *param = type->Proc.abi_compat_params[i];
  1546. // if (param == nullptr) {
  1547. // continue;
  1548. // }
  1549. // param_types[param_index++] = lb_type(m, param);
  1550. // }
  1551. // if (type->Proc.return_by_pointer) {
  1552. // param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0);
  1553. // }
  1554. // if (type->Proc.calling_convention == ProcCC_Odin) {
  1555. // param_types[param_index++] = lb_type(m, t_context_ptr);
  1556. // }
  1557. // LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg);
  1558. // return LLVMPointerType(t, 0);
  1559. }
  1560. break;
  1561. case Type_BitSet:
  1562. return nullptr;
  1563. // return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)type_size_of(type));
  1564. case Type_SimdVector:
  1565. return nullptr;
  1566. // if (type->SimdVector.is_x86_mmx) {
  1567. // return LLVMX86MMXTypeInContext(ctx);
  1568. // }
  1569. // return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1570. }
  1571. GB_PANIC("Invalid type %s", type_to_string(type));
  1572. return nullptr;
  1573. }
  1574. LLVMMetadataRef lb_debug_type(lbModule *m, Type *type) {
  1575. LLVMTypeRef t = lb_type(m, type);
  1576. LLVMMetadataRef *found = map_get(&m->debug_values, hash_pointer(t));
  1577. if (found != nullptr) {
  1578. return *found;
  1579. }
  1580. LLVMMetadataRef dt = lb_debug_type_internal(m, type);
  1581. map_set(&m->debug_values, hash_pointer(t), dt);
  1582. return dt;
  1583. }
  1584. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1585. if (e != nullptr) {
  1586. map_set(&m->values, hash_entity(e), val);
  1587. }
  1588. }
  1589. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1590. if (name.len > 0) {
  1591. string_map_set(&m->members, name, val);
  1592. }
  1593. }
  1594. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1595. string_map_set(&m->members, key, val);
  1596. }
  1597. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1598. if (p->entity != nullptr) {
  1599. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1600. }
  1601. string_map_set(&m->procedures, p->name, p);
  1602. }
  1603. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  1604. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  1605. LLVMValueRef values[2] = {
  1606. str_elem.value,
  1607. str_len.value,
  1608. };
  1609. lbValue res = {};
  1610. res.type = t_string;
  1611. res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values));
  1612. return res;
  1613. } else {
  1614. lbAddr res = lb_add_local_generated(p, t_string, false);
  1615. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  1616. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  1617. return lb_addr_load(p, res);
  1618. }
  1619. }
  1620. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1621. String s = make_string_c(name);
  1622. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1623. // and the current LLVM C API does not expose this functionality yet.
  1624. // It is better to ignore the attributes for the time being
  1625. if (s == "byval") {
  1626. return nullptr;
  1627. } else if (s == "byref") {
  1628. return nullptr;
  1629. } else if (s == "preallocated") {
  1630. return nullptr;
  1631. } else if (s == "sret") {
  1632. return nullptr;
  1633. }
  1634. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1635. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1636. return LLVMCreateEnumAttribute(ctx, kind, value);
  1637. }
  1638. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1639. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1640. GB_ASSERT(attr != nullptr);
  1641. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1642. }
  1643. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1644. lb_add_proc_attribute_at_index(p, index, name, cast(u64)true);
  1645. }
  1646. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  1647. if (p->abi_function_type != nullptr) {
  1648. return;
  1649. }
  1650. auto hash = hash_type(p->type);
  1651. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  1652. if (ft_found == nullptr) {
  1653. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  1654. ft_found = map_get(&m->function_type_map, hash);
  1655. }
  1656. GB_ASSERT(ft_found != nullptr);
  1657. p->abi_function_type = *ft_found;
  1658. GB_ASSERT(p->abi_function_type != nullptr);
  1659. }
  1660. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) {
  1661. GB_ASSERT(entity != nullptr);
  1662. String link_name = lb_get_entity_name(m, entity);
  1663. {
  1664. StringHashKey key = string_hash_string(link_name);
  1665. lbValue *found = string_map_get(&m->members, key);
  1666. if (found) {
  1667. lb_add_entity(m, entity, *found);
  1668. lbProcedure **p_found = string_map_get(&m->procedures, key);
  1669. GB_ASSERT(p_found != nullptr);
  1670. return *p_found;
  1671. }
  1672. }
  1673. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1674. p->module = m;
  1675. entity->code_gen_module = m;
  1676. entity->code_gen_procedure = p;
  1677. p->entity = entity;
  1678. p->name = link_name;
  1679. DeclInfo *decl = entity->decl_info;
  1680. ast_node(pl, ProcLit, decl->proc_lit);
  1681. Type *pt = base_type(entity->type);
  1682. GB_ASSERT(pt->kind == Type_Proc);
  1683. set_procedure_abi_types(entity->type);
  1684. p->type = entity->type;
  1685. p->type_expr = decl->type_expr;
  1686. p->body = pl->body;
  1687. p->tags = pt->Proc.tags;
  1688. p->inlining = ProcInlining_none;
  1689. p->is_foreign = entity->Procedure.is_foreign;
  1690. p->is_export = entity->Procedure.is_export;
  1691. p->is_entry_point = false;
  1692. gbAllocator a = heap_allocator();
  1693. p->children.allocator = a;
  1694. p->params.allocator = a;
  1695. p->defer_stmts.allocator = a;
  1696. p->blocks.allocator = a;
  1697. p->branch_blocks.allocator = a;
  1698. p->context_stack.allocator = a;
  1699. if (p->is_foreign) {
  1700. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  1701. }
  1702. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1703. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1704. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1705. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1706. lb_ensure_abi_function_type(m, p);
  1707. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  1708. if (false) {
  1709. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1710. // TODO(bill): Clean up this logic
  1711. if (build_context.metrics.os != TargetOs_js) {
  1712. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1713. }
  1714. LLVMSetFunctionCallConv(p->value, cc_kind);
  1715. }
  1716. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1717. // // TODO(bill): Clean up this logic
  1718. // if (build_context.metrics.os != TargetOs_js) {
  1719. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1720. // }
  1721. // LLVMSetFunctionCallConv(p->value, cc_kind);
  1722. lbValue proc_value = {p->value, p->type};
  1723. lb_add_entity(m, entity, proc_value);
  1724. lb_add_member(m, p->name, proc_value);
  1725. lb_add_procedure_value(m, p);
  1726. if (p->is_export) {
  1727. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  1728. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  1729. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  1730. if (build_context.metrics.os == TargetOs_js) {
  1731. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  1732. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  1733. }
  1734. }
  1735. if (p->is_foreign) {
  1736. if (build_context.metrics.os == TargetOs_js) {
  1737. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  1738. char const *module_name = "env";
  1739. if (entity->Procedure.foreign_library != nullptr) {
  1740. Entity *foreign_library = entity->Procedure.foreign_library;
  1741. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1742. if (foreign_library->LibraryName.paths.count > 0) {
  1743. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  1744. }
  1745. }
  1746. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  1747. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  1748. }
  1749. }
  1750. // NOTE(bill): offset==0 is the return value
  1751. isize offset = 1;
  1752. if (pt->Proc.return_by_pointer) {
  1753. offset = 2;
  1754. }
  1755. isize parameter_index = 0;
  1756. if (pt->Proc.param_count) {
  1757. TypeTuple *params = &pt->Proc.params->Tuple;
  1758. for (isize i = 0; i < pt->Proc.param_count; i++) {
  1759. Entity *e = params->variables[i];
  1760. Type *original_type = e->type;
  1761. Type *abi_type = pt->Proc.abi_compat_params[i];
  1762. if (e->kind != Entity_Variable) continue;
  1763. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  1764. continue;
  1765. }
  1766. if (is_type_tuple(abi_type)) {
  1767. for_array(j, abi_type->Tuple.variables) {
  1768. Type *tft = abi_type->Tuple.variables[j]->type;
  1769. if (e->flags&EntityFlag_NoAlias) {
  1770. lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias");
  1771. }
  1772. }
  1773. parameter_index += abi_type->Tuple.variables.count;
  1774. } else {
  1775. if (e->flags&EntityFlag_NoAlias) {
  1776. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1777. }
  1778. parameter_index += 1;
  1779. }
  1780. }
  1781. }
  1782. { // Debug Information
  1783. unsigned line = cast(unsigned)entity->token.pos.line;
  1784. LLVMMetadataRef file = nullptr;
  1785. if (entity->file != nullptr) {
  1786. cast(LLVMMetadataRef)entity->file->llvm_metadata;
  1787. }
  1788. LLVMMetadataRef scope = nullptr;
  1789. LLVMMetadataRef type = nullptr;
  1790. // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero);
  1791. LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  1792. cast(char const *)entity->token.string.text, entity->token.string.len,
  1793. cast(char const *)p->name.text, p->name.len,
  1794. file, line, type,
  1795. true, p->body == nullptr,
  1796. line, LLVMDIFlagZero, false
  1797. );
  1798. GB_ASSERT(res != nullptr);
  1799. map_set(&m->debug_values, hash_pointer(p), res);
  1800. }
  1801. return p;
  1802. }
  1803. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  1804. {
  1805. lbValue *found = string_map_get(&m->members, link_name);
  1806. GB_ASSERT(found == nullptr);
  1807. }
  1808. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  1809. p->module = m;
  1810. p->name = link_name;
  1811. p->type = type;
  1812. p->type_expr = nullptr;
  1813. p->body = nullptr;
  1814. p->tags = 0;
  1815. p->inlining = ProcInlining_none;
  1816. p->is_foreign = false;
  1817. p->is_export = false;
  1818. p->is_entry_point = false;
  1819. gbAllocator a = permanent_allocator();
  1820. p->children.allocator = a;
  1821. p->params.allocator = a;
  1822. p->defer_stmts.allocator = a;
  1823. p->blocks.allocator = a;
  1824. p->branch_blocks.allocator = a;
  1825. p->context_stack.allocator = a;
  1826. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  1827. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  1828. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  1829. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  1830. Type *pt = p->type;
  1831. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  1832. // TODO(bill): Clean up this logic
  1833. if (build_context.metrics.os != TargetOs_js) {
  1834. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  1835. }
  1836. LLVMSetFunctionCallConv(p->value, cc_kind);
  1837. lbValue proc_value = {p->value, p->type};
  1838. lb_add_member(m, p->name, proc_value);
  1839. lb_add_procedure_value(m, p);
  1840. // NOTE(bill): offset==0 is the return value
  1841. isize offset = 1;
  1842. if (pt->Proc.return_by_pointer) {
  1843. lb_add_proc_attribute_at_index(p, 1, "sret");
  1844. lb_add_proc_attribute_at_index(p, 1, "noalias");
  1845. offset = 2;
  1846. }
  1847. isize parameter_index = 0;
  1848. if (pt->Proc.calling_convention == ProcCC_Odin) {
  1849. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  1850. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  1851. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  1852. }
  1853. return p;
  1854. }
  1855. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  1856. lbParamPasskind kind = lbParamPass_Value;
  1857. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  1858. if (is_type_pointer(abi_type)) {
  1859. GB_ASSERT(e->kind == Entity_Variable);
  1860. Type *av = core_type(type_deref(abi_type));
  1861. if (are_types_identical(av, core_type(e->type))) {
  1862. kind = lbParamPass_Pointer;
  1863. if (e->flags&EntityFlag_Value) {
  1864. kind = lbParamPass_ConstRef;
  1865. }
  1866. } else {
  1867. kind = lbParamPass_BitCast;
  1868. }
  1869. } else if (is_type_integer(abi_type)) {
  1870. kind = lbParamPass_Integer;
  1871. } else if (abi_type == t_llvm_bool) {
  1872. kind = lbParamPass_Value;
  1873. } else if (is_type_boolean(abi_type)) {
  1874. kind = lbParamPass_Integer;
  1875. } else if (is_type_simd_vector(abi_type)) {
  1876. kind = lbParamPass_BitCast;
  1877. } else if (is_type_float(abi_type)) {
  1878. kind = lbParamPass_BitCast;
  1879. } else if (is_type_tuple(abi_type)) {
  1880. kind = lbParamPass_Tuple;
  1881. } else if (is_type_proc(abi_type)) {
  1882. kind = lbParamPass_Value;
  1883. } else {
  1884. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  1885. }
  1886. }
  1887. if (kind_) *kind_ = kind;
  1888. lbValue res = {};
  1889. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  1890. res.type = abi_type;
  1891. return res;
  1892. }
  1893. lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) {
  1894. lbParamPasskind kind = lbParamPass_Value;
  1895. lbValue v = lb_value_param(p, e, abi_type, index, &kind);
  1896. array_add(&p->params, v);
  1897. lbValue res = {};
  1898. switch (kind) {
  1899. case lbParamPass_Value: {
  1900. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1901. lbValue x = v;
  1902. if (abi_type == t_llvm_bool) {
  1903. x = lb_emit_conv(p, x, t_bool);
  1904. }
  1905. lb_addr_store(p, l, x);
  1906. return x;
  1907. }
  1908. case lbParamPass_Pointer:
  1909. lb_add_entity(p->module, e, v);
  1910. return lb_emit_load(p, v);
  1911. case lbParamPass_Integer: {
  1912. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1913. lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type));
  1914. lb_emit_store(p, iptr, v);
  1915. return lb_addr_load(p, l);
  1916. }
  1917. case lbParamPass_ConstRef:
  1918. lb_add_entity(p->module, e, v);
  1919. return lb_emit_load(p, v);
  1920. case lbParamPass_BitCast: {
  1921. lbAddr l = lb_add_local(p, e->type, e, false, index);
  1922. lbValue x = lb_emit_transmute(p, v, e->type);
  1923. lb_addr_store(p, l, x);
  1924. return x;
  1925. }
  1926. case lbParamPass_Tuple: {
  1927. lbAddr l = lb_add_local(p, e->type, e, true, index);
  1928. Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type);
  1929. lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st));
  1930. if (abi_type->Tuple.variables.count > 0) {
  1931. array_pop(&p->params);
  1932. }
  1933. for_array(i, abi_type->Tuple.variables) {
  1934. Type *t = abi_type->Tuple.variables[i]->type;
  1935. GB_ASSERT(!is_type_tuple(t));
  1936. lbParamPasskind elem_kind = lbParamPass_Value;
  1937. lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind);
  1938. array_add(&p->params, elem);
  1939. lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i);
  1940. lb_emit_store(p, dst, elem);
  1941. }
  1942. return lb_addr_load(p, l);
  1943. }
  1944. }
  1945. GB_PANIC("Unreachable");
  1946. return {};
  1947. }
  1948. void lb_start_block(lbProcedure *p, lbBlock *b) {
  1949. GB_ASSERT(b != nullptr);
  1950. if (!b->appended) {
  1951. b->appended = true;
  1952. LLVMAppendExistingBasicBlock(p->value, b->block);
  1953. }
  1954. LLVMPositionBuilderAtEnd(p->builder, b->block);
  1955. p->curr_block = b;
  1956. }
  1957. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  1958. LLVMContextRef ctx = p->module->ctx;
  1959. LLVMTypeRef src_type = LLVMTypeOf(val);
  1960. if (src_type == dst_type) {
  1961. return val;
  1962. }
  1963. i64 src_size = lb_sizeof(src_type);
  1964. i64 dst_size = lb_sizeof(dst_type);
  1965. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  1966. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  1967. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  1968. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  1969. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  1970. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  1971. }
  1972. if (src_size != dst_size && (lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  1973. // Okay
  1974. } else {
  1975. GB_ASSERT_MSG(src_size == dst_size, "%s == %s", LLVMPrintTypeToString(src_type), LLVMPrintTypeToString(dst_type));
  1976. }
  1977. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  1978. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  1979. if (src_kind == dst_kind) {
  1980. if (src_kind == LLVMPointerTypeKind) {
  1981. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  1982. } else if (src_kind == LLVMArrayTypeKind) {
  1983. // ignore
  1984. } else if (src_kind != LLVMStructTypeKind) {
  1985. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  1986. }
  1987. } else {
  1988. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  1989. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  1990. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  1991. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  1992. }
  1993. }
  1994. if (LLVMIsALoadInst(val)) {
  1995. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  1996. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  1997. return LLVMBuildLoad(p->builder, val_ptr, "");
  1998. } else {
  1999. GB_ASSERT(p->decl_block != p->curr_block);
  2000. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2001. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  2002. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2003. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2004. max_align = gb_max(max_align, 4);
  2005. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  2006. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2007. LLVMBuildStore(p->builder, val, nptr);
  2008. return LLVMBuildLoad(p->builder, ptr, "");
  2009. }
  2010. }
  2011. void lb_begin_procedure_body(lbProcedure *p) {
  2012. DeclInfo *decl = decl_info_of_entity(p->entity);
  2013. if (decl != nullptr) {
  2014. for_array(i, decl->labels) {
  2015. BlockLabel bl = decl->labels[i];
  2016. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  2017. array_add(&p->branch_blocks, bb);
  2018. }
  2019. }
  2020. if (p->tags != 0) {
  2021. u64 in = p->tags;
  2022. u64 out = p->module->state_flags;
  2023. if (in & ProcTag_bounds_check) {
  2024. out |= StateFlag_bounds_check;
  2025. out &= ~StateFlag_no_bounds_check;
  2026. } else if (in & ProcTag_no_bounds_check) {
  2027. out |= StateFlag_no_bounds_check;
  2028. out &= ~StateFlag_bounds_check;
  2029. }
  2030. p->module->state_flags = out;
  2031. }
  2032. p->builder = LLVMCreateBuilder();
  2033. p->decl_block = lb_create_block(p, "decls", true);
  2034. p->entry_block = lb_create_block(p, "entry", true);
  2035. lb_start_block(p, p->entry_block);
  2036. GB_ASSERT(p->type != nullptr);
  2037. lb_ensure_abi_function_type(p->module, p);
  2038. {
  2039. lbFunctionType *ft = p->abi_function_type;
  2040. unsigned param_offset = 0;
  2041. lbValue return_ptr_value = {};
  2042. if (ft->ret.kind == lbArg_Indirect) {
  2043. // NOTE(bill): this must be parameter 0
  2044. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  2045. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false);
  2046. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  2047. return_ptr_value.value = LLVMGetParam(p->value, 0);
  2048. return_ptr_value.type = ptr_type;
  2049. p->return_ptr = lb_addr(return_ptr_value);
  2050. lb_add_entity(p->module, e, return_ptr_value);
  2051. param_offset += 1;
  2052. }
  2053. if (p->type->Proc.params != nullptr) {
  2054. TypeTuple *params = &p->type->Proc.params->Tuple;
  2055. unsigned param_index = 0;
  2056. for_array(i, params->variables) {
  2057. Entity *e = params->variables[i];
  2058. if (e->kind != Entity_Variable) {
  2059. continue;
  2060. }
  2061. lbArgType *arg_type = &ft->args[param_index];
  2062. if (arg_type->kind == lbArg_Ignore) {
  2063. continue;
  2064. } else if (arg_type->kind == lbArg_Direct) {
  2065. lbParamPasskind kind = lbParamPass_Value;
  2066. LLVMTypeRef param_type = lb_type(p->module, e->type);
  2067. if (param_type != arg_type->type) {
  2068. kind = lbParamPass_BitCast;
  2069. }
  2070. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  2071. value = OdinLLVMBuildTransmute(p, value, param_type);
  2072. lbValue param = {};
  2073. param.value = value;
  2074. param.type = e->type;
  2075. array_add(&p->params, param);
  2076. if (e->token.string.len != 0) {
  2077. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  2078. lb_addr_store(p, l, param);
  2079. }
  2080. param_index += 1;
  2081. } else if (arg_type->kind == lbArg_Indirect) {
  2082. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  2083. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  2084. lbValue param = {};
  2085. param.value = value;
  2086. param.type = e->type;
  2087. array_add(&p->params, param);
  2088. lbValue ptr = {};
  2089. ptr.value = value_ptr;
  2090. ptr.type = alloc_type_pointer(e->type);
  2091. lb_add_entity(p->module, e, ptr);
  2092. param_index += 1;
  2093. }
  2094. }
  2095. }
  2096. if (p->type->Proc.has_named_results) {
  2097. GB_ASSERT(p->type->Proc.result_count > 0);
  2098. TypeTuple *results = &p->type->Proc.results->Tuple;
  2099. for_array(i, results->variables) {
  2100. Entity *e = results->variables[i];
  2101. GB_ASSERT(e->kind == Entity_Variable);
  2102. if (e->token.string != "") {
  2103. GB_ASSERT(!is_blank_ident(e->token));
  2104. lbAddr res = {};
  2105. if (return_ptr_value.value) {
  2106. lbValue ptr = return_ptr_value;
  2107. if (results->variables.count != 1) {
  2108. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  2109. }
  2110. res = lb_addr(ptr);
  2111. lb_add_entity(p->module, e, ptr);
  2112. } else {
  2113. res = lb_add_local(p, e->type, e);
  2114. }
  2115. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  2116. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  2117. lb_addr_store(p, res, c);
  2118. }
  2119. }
  2120. }
  2121. }
  2122. }
  2123. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  2124. Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false);
  2125. e->flags |= EntityFlag_NoAlias;
  2126. lbValue param = {};
  2127. param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  2128. param.type = e->type;
  2129. lb_add_entity(p->module, e, param);
  2130. lbAddr ctx_addr = {};
  2131. ctx_addr.kind = lbAddr_Context;
  2132. ctx_addr.addr = param;
  2133. lbContextData ctx = {ctx_addr, p->scope_index};
  2134. array_add(&p->context_stack, ctx);
  2135. }
  2136. lb_start_block(p, p->entry_block);
  2137. }
  2138. void lb_end_procedure_body(lbProcedure *p) {
  2139. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2140. LLVMBuildBr(p->builder, p->entry_block->block);
  2141. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2142. if (p->type->Proc.result_count == 0) {
  2143. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2144. if (!lb_is_instr_terminating(instr)) {
  2145. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  2146. LLVMBuildRetVoid(p->builder);
  2147. }
  2148. } else {
  2149. if (p->curr_block->preds.count == 0) {
  2150. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  2151. if (instr == nullptr) {
  2152. // NOTE(bill): Remove dead trailing block
  2153. LLVMDeleteBasicBlock(p->curr_block->block);
  2154. }
  2155. }
  2156. }
  2157. p->curr_block = nullptr;
  2158. p->module->state_flags = 0;
  2159. }
  2160. void lb_end_procedure(lbProcedure *p) {
  2161. LLVMDisposeBuilder(p->builder);
  2162. }
  2163. void lb_add_edge(lbBlock *from, lbBlock *to) {
  2164. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  2165. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  2166. array_add(&from->succs, to);
  2167. array_add(&to->preds, from);
  2168. }
  2169. }
  2170. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  2171. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  2172. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  2173. b->appended = false;
  2174. if (append) {
  2175. b->appended = true;
  2176. LLVMAppendExistingBasicBlock(p->value, b->block);
  2177. }
  2178. b->scope = p->curr_scope;
  2179. b->scope_index = p->scope_index;
  2180. b->preds.allocator = heap_allocator();
  2181. b->succs.allocator = heap_allocator();
  2182. array_add(&p->blocks, b);
  2183. return b;
  2184. }
  2185. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2186. if (p->curr_block == nullptr) {
  2187. return;
  2188. }
  2189. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2190. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2191. return;
  2192. }
  2193. lb_add_edge(p->curr_block, target_block);
  2194. LLVMBuildBr(p->builder, target_block->block);
  2195. p->curr_block = nullptr;
  2196. }
  2197. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2198. lbBlock *b = p->curr_block;
  2199. if (b == nullptr) {
  2200. return;
  2201. }
  2202. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2203. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2204. return;
  2205. }
  2206. lb_add_edge(b, true_block);
  2207. lb_add_edge(b, false_block);
  2208. LLVMValueRef cv = cond.value;
  2209. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2210. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2211. }
  2212. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2213. GB_ASSERT(cond != nullptr);
  2214. GB_ASSERT(true_block != nullptr);
  2215. GB_ASSERT(false_block != nullptr);
  2216. switch (cond->kind) {
  2217. case_ast_node(pe, ParenExpr, cond);
  2218. return lb_build_cond(p, pe->expr, true_block, false_block);
  2219. case_end;
  2220. case_ast_node(ue, UnaryExpr, cond);
  2221. if (ue->op.kind == Token_Not) {
  2222. return lb_build_cond(p, ue->expr, false_block, true_block);
  2223. }
  2224. case_end;
  2225. case_ast_node(be, BinaryExpr, cond);
  2226. if (be->op.kind == Token_CmpAnd) {
  2227. lbBlock *block = lb_create_block(p, "cmp.and");
  2228. lb_build_cond(p, be->left, block, false_block);
  2229. lb_start_block(p, block);
  2230. return lb_build_cond(p, be->right, true_block, false_block);
  2231. } else if (be->op.kind == Token_CmpOr) {
  2232. lbBlock *block = lb_create_block(p, "cmp.or");
  2233. lb_build_cond(p, be->left, true_block, block);
  2234. lb_start_block(p, block);
  2235. return lb_build_cond(p, be->right, true_block, false_block);
  2236. }
  2237. case_end;
  2238. }
  2239. lbValue v = lb_build_expr(p, cond);
  2240. // v = lb_emit_conv(p, v, t_bool);
  2241. v = lb_emit_conv(p, v, t_llvm_bool);
  2242. lb_emit_if(p, v, true_block, false_block);
  2243. return v;
  2244. }
  2245. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) {
  2246. GB_ASSERT(p->decl_block != p->curr_block);
  2247. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2248. char const *name = "";
  2249. if (e != nullptr) {
  2250. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2251. }
  2252. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2253. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2254. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2255. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2256. LLVMSetAlignment(ptr, alignment);
  2257. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2258. if (zero_init) {
  2259. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2260. switch (kind) {
  2261. case LLVMStructTypeKind:
  2262. case LLVMArrayTypeKind:
  2263. {
  2264. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  2265. LLVMTypeRef type_i8 = LLVMInt8TypeInContext(p->module->ctx);
  2266. LLVMTypeRef type_i32 = LLVMInt32TypeInContext(p->module->ctx);
  2267. i32 sz = cast(i32)type_size_of(type);
  2268. LLVMBuildMemSet(p->builder, ptr, LLVMConstNull(type_i8), LLVMConstInt(type_i32, sz, false), alignment);
  2269. }
  2270. break;
  2271. default:
  2272. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  2273. }
  2274. }
  2275. lbValue val = {};
  2276. val.value = ptr;
  2277. val.type = alloc_type_pointer(type);
  2278. if (e != nullptr) {
  2279. lb_add_entity(p->module, e, val);
  2280. }
  2281. return lb_addr(val);
  2282. }
  2283. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2284. return lb_add_local(p, type, nullptr, zero_init);
  2285. }
  2286. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  2287. GB_ASSERT(pd->body != nullptr);
  2288. lbModule *m = p->module;
  2289. auto *min_dep_set = &m->info->minimum_dependency_set;
  2290. if (ptr_set_exists(min_dep_set, e) == false) {
  2291. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  2292. return;
  2293. }
  2294. // NOTE(bill): Generate a new name
  2295. // parent.name-guid
  2296. String original_name = e->token.string;
  2297. String pd_name = original_name;
  2298. if (e->Procedure.link_name.len > 0) {
  2299. pd_name = e->Procedure.link_name;
  2300. }
  2301. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  2302. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2303. i32 guid = cast(i32)p->children.count;
  2304. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  2305. String name = make_string(cast(u8 *)name_text, name_len-1);
  2306. set_procedure_abi_types(e->type);
  2307. e->Procedure.link_name = name;
  2308. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2309. e->code_gen_procedure = nested_proc;
  2310. lbValue value = {};
  2311. value.value = nested_proc->value;
  2312. value.type = nested_proc->type;
  2313. lb_add_entity(m, e, value);
  2314. array_add(&p->children, nested_proc);
  2315. array_add(&m->procedures_to_generate, nested_proc);
  2316. }
  2317. void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  2318. if (e == nullptr) {
  2319. return;
  2320. }
  2321. GB_ASSERT(e->kind == Entity_LibraryName);
  2322. GB_ASSERT(e->flags & EntityFlag_Used);
  2323. for_array(i, e->LibraryName.paths) {
  2324. String library_path = e->LibraryName.paths[i];
  2325. if (library_path.len == 0) {
  2326. continue;
  2327. }
  2328. bool ok = true;
  2329. for_array(path_index, m->foreign_library_paths) {
  2330. String path = m->foreign_library_paths[path_index];
  2331. #if defined(GB_SYSTEM_WINDOWS)
  2332. if (str_eq_ignore_case(path, library_path)) {
  2333. #else
  2334. if (str_eq(path, library_path)) {
  2335. #endif
  2336. ok = false;
  2337. break;
  2338. }
  2339. }
  2340. if (ok) {
  2341. array_add(&m->foreign_library_paths, library_path);
  2342. }
  2343. }
  2344. }
  2345. void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2346. if (vd == nullptr || vd->is_mutable) {
  2347. return;
  2348. }
  2349. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  2350. static i32 global_guid = 0;
  2351. for_array(i, vd->names) {
  2352. Ast *ident = vd->names[i];
  2353. GB_ASSERT(ident->kind == Ast_Ident);
  2354. Entity *e = entity_of_node(ident);
  2355. GB_ASSERT(e != nullptr);
  2356. if (e->kind != Entity_TypeName) {
  2357. continue;
  2358. }
  2359. bool polymorphic_struct = false;
  2360. if (e->type != nullptr && e->kind == Entity_TypeName) {
  2361. Type *bt = base_type(e->type);
  2362. if (bt->kind == Type_Struct) {
  2363. polymorphic_struct = bt->Struct.is_polymorphic;
  2364. }
  2365. }
  2366. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  2367. continue;
  2368. }
  2369. if (e->TypeName.ir_mangled_name.len != 0) {
  2370. // NOTE(bill): Already set
  2371. continue;
  2372. }
  2373. lb_set_nested_type_name_ir_mangled_name(e, p);
  2374. }
  2375. for_array(i, vd->names) {
  2376. Ast *ident = vd->names[i];
  2377. GB_ASSERT(ident->kind == Ast_Ident);
  2378. Entity *e = entity_of_node(ident);
  2379. GB_ASSERT(e != nullptr);
  2380. if (e->kind != Entity_Procedure) {
  2381. continue;
  2382. }
  2383. CheckerInfo *info = p->module->info;
  2384. DeclInfo *decl = decl_info_of_entity(e);
  2385. ast_node(pl, ProcLit, decl->proc_lit);
  2386. if (pl->body != nullptr) {
  2387. auto *found = map_get(&info->gen_procs, hash_pointer(ident));
  2388. if (found) {
  2389. auto procs = *found;
  2390. for_array(i, procs) {
  2391. Entity *e = procs[i];
  2392. if (!ptr_set_exists(min_dep_set, e)) {
  2393. continue;
  2394. }
  2395. DeclInfo *d = decl_info_of_entity(e);
  2396. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  2397. }
  2398. } else {
  2399. lb_build_nested_proc(p, pl, e);
  2400. }
  2401. } else {
  2402. // FFI - Foreign function interace
  2403. String original_name = e->token.string;
  2404. String name = original_name;
  2405. if (e->Procedure.is_foreign) {
  2406. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  2407. }
  2408. if (e->Procedure.link_name.len > 0) {
  2409. name = e->Procedure.link_name;
  2410. }
  2411. lbValue *prev_value = string_map_get(&p->module->members, name);
  2412. if (prev_value != nullptr) {
  2413. // NOTE(bill): Don't do mutliple declarations in the IR
  2414. return;
  2415. }
  2416. set_procedure_abi_types(e->type);
  2417. e->Procedure.link_name = name;
  2418. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  2419. lbValue value = {};
  2420. value.value = nested_proc->value;
  2421. value.type = nested_proc->type;
  2422. array_add(&p->module->procedures_to_generate, nested_proc);
  2423. if (p != nullptr) {
  2424. array_add(&p->children, nested_proc);
  2425. } else {
  2426. string_map_set(&p->module->members, name, value);
  2427. }
  2428. }
  2429. }
  2430. }
  2431. void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  2432. for_array(i, stmts) {
  2433. Ast *stmt = stmts[i];
  2434. switch (stmt->kind) {
  2435. case_ast_node(vd, ValueDecl, stmt);
  2436. lb_build_constant_value_decl(p, vd);
  2437. case_end;
  2438. case_ast_node(fb, ForeignBlockDecl, stmt);
  2439. ast_node(block, BlockStmt, fb->body);
  2440. lb_build_stmt_list(p, block->stmts);
  2441. case_end;
  2442. }
  2443. }
  2444. for_array(i, stmts) {
  2445. lb_build_stmt(p, stmts[i]);
  2446. }
  2447. }
  2448. lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  2449. GB_ASSERT(ident->kind == Ast_Ident);
  2450. Entity *e = entity_of_node(ident);
  2451. GB_ASSERT(e->kind == Entity_Label);
  2452. for_array(i, p->branch_blocks) {
  2453. lbBranchBlocks *b = &p->branch_blocks[i];
  2454. if (b->label == e->Label.node) {
  2455. return *b;
  2456. }
  2457. }
  2458. GB_PANIC("Unreachable");
  2459. lbBranchBlocks empty = {};
  2460. return empty;
  2461. }
  2462. lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  2463. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  2464. tl->prev = p->target_list;
  2465. tl->break_ = break_;
  2466. tl->continue_ = continue_;
  2467. tl->fallthrough_ = fallthrough_;
  2468. p->target_list = tl;
  2469. if (label != nullptr) { // Set label blocks
  2470. GB_ASSERT(label->kind == Ast_Label);
  2471. for_array(i, p->branch_blocks) {
  2472. lbBranchBlocks *b = &p->branch_blocks[i];
  2473. GB_ASSERT(b->label != nullptr && label != nullptr);
  2474. GB_ASSERT(b->label->kind == Ast_Label);
  2475. if (b->label == label) {
  2476. b->break_ = break_;
  2477. b->continue_ = continue_;
  2478. return tl;
  2479. }
  2480. }
  2481. GB_PANIC("Unreachable");
  2482. }
  2483. return tl;
  2484. }
  2485. void lb_pop_target_list(lbProcedure *p) {
  2486. p->target_list = p->target_list->prev;
  2487. }
  2488. void lb_open_scope(lbProcedure *p) {
  2489. p->scope_index += 1;
  2490. }
  2491. void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  2492. lb_emit_defer_stmts(p, kind, block);
  2493. GB_ASSERT(p->scope_index > 0);
  2494. // NOTE(bill): Remove `context`s made in that scope
  2495. while (p->context_stack.count > 0) {
  2496. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  2497. if (ctx->scope_index >= p->scope_index) {
  2498. array_pop(&p->context_stack);
  2499. } else {
  2500. break;
  2501. }
  2502. }
  2503. p->scope_index -= 1;
  2504. }
  2505. void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  2506. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  2507. GB_ASSERT(is_type_boolean(tv.type));
  2508. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  2509. if (tv.value.value_bool) {
  2510. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  2511. } else if (ws->else_stmt) {
  2512. switch (ws->else_stmt->kind) {
  2513. case Ast_BlockStmt:
  2514. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  2515. break;
  2516. case Ast_WhenStmt:
  2517. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  2518. break;
  2519. default:
  2520. GB_PANIC("Invalid 'else' statement in 'when' statement");
  2521. break;
  2522. }
  2523. }
  2524. }
  2525. void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  2526. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2527. lbModule *m = p->module;
  2528. lbValue count = {};
  2529. Type *expr_type = base_type(type_deref(expr.type));
  2530. switch (expr_type->kind) {
  2531. case Type_Array:
  2532. count = lb_const_int(m, t_int, expr_type->Array.count);
  2533. break;
  2534. }
  2535. lbValue val = {};
  2536. lbValue idx = {};
  2537. lbBlock *loop = nullptr;
  2538. lbBlock *done = nullptr;
  2539. lbBlock *body = nullptr;
  2540. lbAddr index = lb_add_local_generated(p, t_int, false);
  2541. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  2542. loop = lb_create_block(p, "for.index.loop");
  2543. lb_emit_jump(p, loop);
  2544. lb_start_block(p, loop);
  2545. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  2546. lb_addr_store(p, index, incr);
  2547. body = lb_create_block(p, "for.index.body");
  2548. done = lb_create_block(p, "for.index.done");
  2549. if (count.value == nullptr) {
  2550. GB_ASSERT(count_ptr.value != nullptr);
  2551. count = lb_emit_load(p, count_ptr);
  2552. }
  2553. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  2554. lb_emit_if(p, cond, body, done);
  2555. lb_start_block(p, body);
  2556. idx = lb_addr_load(p, index);
  2557. switch (expr_type->kind) {
  2558. case Type_Array: {
  2559. if (val_type != nullptr) {
  2560. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2561. }
  2562. break;
  2563. }
  2564. case Type_EnumeratedArray: {
  2565. if (val_type != nullptr) {
  2566. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  2567. // NOTE(bill): Override the idx value for the enumeration
  2568. Type *index_type = expr_type->EnumeratedArray.index;
  2569. if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  2570. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type);
  2571. }
  2572. }
  2573. break;
  2574. }
  2575. case Type_Slice: {
  2576. if (val_type != nullptr) {
  2577. lbValue elem = lb_slice_elem(p, expr);
  2578. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2579. }
  2580. break;
  2581. }
  2582. case Type_DynamicArray: {
  2583. if (val_type != nullptr) {
  2584. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  2585. elem = lb_emit_load(p, elem);
  2586. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  2587. }
  2588. break;
  2589. }
  2590. case Type_Map: {
  2591. lbValue entries = lb_map_entries_ptr(p, expr);
  2592. lbValue elem = lb_emit_struct_ep(p, entries, 0);
  2593. elem = lb_emit_load(p, elem);
  2594. lbValue entry = lb_emit_ptr_offset(p, elem, idx);
  2595. idx = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2));
  2596. val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 3));
  2597. break;
  2598. }
  2599. default:
  2600. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  2601. break;
  2602. }
  2603. if (val_) *val_ = val;
  2604. if (idx_) *idx_ = idx;
  2605. if (loop_) *loop_ = loop;
  2606. if (done_) *done_ = done;
  2607. }
  2608. void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  2609. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2610. lbModule *m = p->module;
  2611. lbValue count = lb_const_int(m, t_int, 0);
  2612. Type *expr_type = base_type(expr.type);
  2613. switch (expr_type->kind) {
  2614. case Type_Basic:
  2615. count = lb_string_len(p, expr);
  2616. break;
  2617. default:
  2618. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  2619. break;
  2620. }
  2621. lbValue val = {};
  2622. lbValue idx = {};
  2623. lbBlock *loop = nullptr;
  2624. lbBlock *done = nullptr;
  2625. lbBlock *body = nullptr;
  2626. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2627. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2628. loop = lb_create_block(p, "for.string.loop");
  2629. lb_emit_jump(p, loop);
  2630. lb_start_block(p, loop);
  2631. body = lb_create_block(p, "for.string.body");
  2632. done = lb_create_block(p, "for.string.done");
  2633. lbValue offset = lb_addr_load(p, offset_);
  2634. lbValue cond = lb_emit_comp(p, Token_Lt, offset, count);
  2635. lb_emit_if(p, cond, body, done);
  2636. lb_start_block(p, body);
  2637. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  2638. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  2639. auto args = array_make<lbValue>(permanent_allocator(), 1);
  2640. args[0] = lb_emit_string(p, str_elem, str_len);
  2641. lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  2642. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  2643. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  2644. idx = offset;
  2645. if (val_type != nullptr) {
  2646. val = lb_emit_struct_ev(p, rune_and_len, 0);
  2647. }
  2648. if (val_) *val_ = val;
  2649. if (idx_) *idx_ = idx;
  2650. if (loop_) *loop_ = loop;
  2651. if (done_) *done_ = done;
  2652. }
  2653. void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type,
  2654. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2655. lbModule *m = p->module;
  2656. // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration?
  2657. // If 'lower' is changed, should 'val' do so or is that not typical behaviour?
  2658. lbValue lower = lb_build_expr(p, node->left);
  2659. lbValue upper = {};
  2660. lbValue val = {};
  2661. lbValue idx = {};
  2662. lbBlock *loop = nullptr;
  2663. lbBlock *done = nullptr;
  2664. lbBlock *body = nullptr;
  2665. if (val_type == nullptr) {
  2666. val_type = lower.type;
  2667. }
  2668. lbAddr value = lb_add_local_generated(p, val_type, false);
  2669. lb_addr_store(p, value, lower);
  2670. lbAddr index = lb_add_local_generated(p, t_int, false);
  2671. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  2672. loop = lb_create_block(p, "for.interval.loop");
  2673. lb_emit_jump(p, loop);
  2674. lb_start_block(p, loop);
  2675. body = lb_create_block(p, "for.interval.body");
  2676. done = lb_create_block(p, "for.interval.done");
  2677. TokenKind op = Token_Lt;
  2678. switch (node->op.kind) {
  2679. case Token_Ellipsis: op = Token_LtEq; break;
  2680. case Token_RangeHalf: op = Token_Lt; break;
  2681. default: GB_PANIC("Invalid interval operator"); break;
  2682. }
  2683. upper = lb_build_expr(p, node->right);
  2684. lbValue curr_value = lb_addr_load(p, value);
  2685. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  2686. lb_emit_if(p, cond, body, done);
  2687. lb_start_block(p, body);
  2688. val = lb_addr_load(p, value);
  2689. idx = lb_addr_load(p, index);
  2690. lb_emit_increment(p, value.addr);
  2691. lb_emit_increment(p, index.addr);
  2692. if (val_) *val_ = val;
  2693. if (idx_) *idx_ = idx;
  2694. if (loop_) *loop_ = loop;
  2695. if (done_) *done_ = done;
  2696. }
  2697. void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  2698. lbModule *m = p->module;
  2699. Type *t = enum_type;
  2700. GB_ASSERT(is_type_enum(t));
  2701. Type *enum_ptr = alloc_type_pointer(t);
  2702. t = base_type(t);
  2703. Type *core_elem = core_type(t);
  2704. GB_ASSERT(t->kind == Type_Enum);
  2705. i64 enum_count = t->Enum.fields.count;
  2706. lbValue max_count = lb_const_int(m, t_int, enum_count);
  2707. lbValue ti = lb_type_info(m, t);
  2708. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  2709. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  2710. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  2711. lbValue values_data = lb_slice_elem(p, values);
  2712. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  2713. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  2714. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  2715. lb_emit_jump(p, loop);
  2716. lb_start_block(p, loop);
  2717. lbBlock *body = lb_create_block(p, "for.enum.body");
  2718. lbBlock *done = lb_create_block(p, "for.enum.done");
  2719. lbValue offset = lb_addr_load(p, offset_);
  2720. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  2721. lb_emit_if(p, cond, body, done);
  2722. lb_start_block(p, body);
  2723. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  2724. lb_emit_increment(p, offset_.addr);
  2725. lbValue val = {};
  2726. if (val_type != nullptr) {
  2727. GB_ASSERT(are_types_identical(enum_type, val_type));
  2728. if (is_type_integer(core_elem)) {
  2729. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  2730. val = lb_emit_conv(p, i, t);
  2731. } else {
  2732. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  2733. }
  2734. }
  2735. if (val_) *val_ = val;
  2736. if (idx_) *idx_ = offset;
  2737. if (loop_) *loop_ = loop;
  2738. if (done_) *done_ = done;
  2739. }
  2740. void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  2741. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  2742. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  2743. lb_emit_jump(p, loop);
  2744. lb_start_block(p, loop);
  2745. lbBlock *body = lb_create_block(p, "for.tuple.body");
  2746. lbBlock *done = lb_create_block(p, "for.tuple.done");
  2747. lbValue tuple_value = lb_build_expr(p, expr);
  2748. Type *tuple = tuple_value.type;
  2749. GB_ASSERT(tuple->kind == Type_Tuple);
  2750. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  2751. i32 cond_index = tuple_count-1;
  2752. lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index);
  2753. lb_emit_if(p, cond, body, done);
  2754. lb_start_block(p, body);
  2755. if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0);
  2756. if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1);
  2757. if (loop_) *loop_ = loop;
  2758. if (done_) *done_ = done;
  2759. }
  2760. void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) {
  2761. lb_open_scope(p);
  2762. Type *val0_type = nullptr;
  2763. Type *val1_type = nullptr;
  2764. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2765. val0_type = type_of_expr(rs->val0);
  2766. }
  2767. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2768. val1_type = type_of_expr(rs->val1);
  2769. }
  2770. if (val0_type != nullptr) {
  2771. Entity *e = entity_of_node(rs->val0);
  2772. lb_add_local(p, e->type, e, true);
  2773. }
  2774. if (val1_type != nullptr) {
  2775. Entity *e = entity_of_node(rs->val1);
  2776. lb_add_local(p, e->type, e, true);
  2777. }
  2778. lbValue val = {};
  2779. lbValue key = {};
  2780. lbBlock *loop = nullptr;
  2781. lbBlock *done = nullptr;
  2782. Ast *expr = unparen_expr(rs->expr);
  2783. bool is_map = false;
  2784. TypeAndValue tav = type_and_value_of_expr(expr);
  2785. if (is_ast_range(expr)) {
  2786. lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done);
  2787. } else if (tav.mode == Addressing_Type) {
  2788. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  2789. } else {
  2790. Type *expr_type = type_of_expr(expr);
  2791. Type *et = base_type(type_deref(expr_type));
  2792. switch (et->kind) {
  2793. case Type_Map: {
  2794. is_map = true;
  2795. lbValue map = lb_build_addr_ptr(p, expr);
  2796. if (is_type_pointer(type_deref(map.type))) {
  2797. map = lb_emit_load(p, map);
  2798. }
  2799. lbValue entries_ptr = lb_map_entries_ptr(p, map);
  2800. lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1);
  2801. lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done);
  2802. break;
  2803. }
  2804. case Type_Array: {
  2805. lbValue array = lb_build_addr_ptr(p, expr);
  2806. if (is_type_pointer(type_deref(array.type))) {
  2807. array = lb_emit_load(p, array);
  2808. }
  2809. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2810. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  2811. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2812. break;
  2813. }
  2814. case Type_EnumeratedArray: {
  2815. lbValue array = lb_build_addr_ptr(p, expr);
  2816. if (is_type_pointer(type_deref(array.type))) {
  2817. array = lb_emit_load(p, array);
  2818. }
  2819. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  2820. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  2821. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done);
  2822. break;
  2823. }
  2824. case Type_DynamicArray: {
  2825. lbValue count_ptr = {};
  2826. lbValue array = lb_build_addr_ptr(p, expr);
  2827. if (is_type_pointer(type_deref(array.type))) {
  2828. array = lb_emit_load(p, array);
  2829. }
  2830. count_ptr = lb_emit_struct_ep(p, array, 1);
  2831. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done);
  2832. break;
  2833. }
  2834. case Type_Slice: {
  2835. lbValue count_ptr = {};
  2836. lbValue slice = lb_build_expr(p, expr);
  2837. if (is_type_pointer(slice.type)) {
  2838. count_ptr = lb_emit_struct_ep(p, slice, 1);
  2839. slice = lb_emit_load(p, slice);
  2840. } else {
  2841. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  2842. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  2843. }
  2844. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done);
  2845. break;
  2846. }
  2847. case Type_Basic: {
  2848. lbValue string = lb_build_expr(p, expr);
  2849. if (is_type_pointer(string.type)) {
  2850. string = lb_emit_load(p, string);
  2851. }
  2852. if (is_type_untyped(expr_type)) {
  2853. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  2854. lb_addr_store(p, s, string);
  2855. string = lb_addr_load(p, s);
  2856. }
  2857. Type *t = base_type(string.type);
  2858. GB_ASSERT(!is_type_cstring(t));
  2859. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done);
  2860. break;
  2861. }
  2862. case Type_Tuple:
  2863. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  2864. break;
  2865. default:
  2866. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  2867. break;
  2868. }
  2869. }
  2870. if (is_map) {
  2871. if (val0_type) lb_store_range_stmt_val(p, rs->val0, key);
  2872. if (val1_type) lb_store_range_stmt_val(p, rs->val1, val);
  2873. } else {
  2874. if (val0_type) lb_store_range_stmt_val(p, rs->val0, val);
  2875. if (val1_type) lb_store_range_stmt_val(p, rs->val1, key);
  2876. }
  2877. lb_push_target_list(p, rs->label, done, loop, nullptr);
  2878. lb_build_stmt(p, rs->body);
  2879. lb_close_scope(p, lbDeferExit_Default, nullptr);
  2880. lb_pop_target_list(p);
  2881. lb_emit_jump(p, loop);
  2882. lb_start_block(p, done);
  2883. }
  2884. void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) {
  2885. lbModule *m = p->module;
  2886. lb_open_scope(p); // Open scope here
  2887. Type *val0_type = nullptr;
  2888. Type *val1_type = nullptr;
  2889. if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) {
  2890. val0_type = type_of_expr(rs->val0);
  2891. }
  2892. if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) {
  2893. val1_type = type_of_expr(rs->val1);
  2894. }
  2895. if (val0_type != nullptr) {
  2896. Entity *e = entity_of_node(rs->val0);
  2897. lb_add_local(p, e->type, e, true);
  2898. }
  2899. if (val1_type != nullptr) {
  2900. Entity *e = entity_of_node(rs->val1);
  2901. lb_add_local(p, e->type, e, true);
  2902. }
  2903. lbValue val = {};
  2904. lbValue key = {};
  2905. lbBlock *loop = nullptr;
  2906. lbBlock *done = nullptr;
  2907. Ast *expr = unparen_expr(rs->expr);
  2908. TypeAndValue tav = type_and_value_of_expr(expr);
  2909. if (is_ast_range(expr)) {
  2910. lbAddr val0_addr = {};
  2911. lbAddr val1_addr = {};
  2912. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2913. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2914. TokenKind op = expr->BinaryExpr.op.kind;
  2915. Ast *start_expr = expr->BinaryExpr.left;
  2916. Ast *end_expr = expr->BinaryExpr.right;
  2917. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  2918. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  2919. ExactValue start = start_expr->tav.value;
  2920. ExactValue end = end_expr->tav.value;
  2921. if (op == Token_Ellipsis) { // .. [start, end]
  2922. ExactValue index = exact_value_i64(0);
  2923. for (ExactValue val = start;
  2924. compare_exact_values(Token_LtEq, val, end);
  2925. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2926. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2927. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2928. lb_build_stmt(p, rs->body);
  2929. }
  2930. } else if (op == Token_RangeHalf) { // ..< [start, end)
  2931. ExactValue index = exact_value_i64(0);
  2932. for (ExactValue val = start;
  2933. compare_exact_values(Token_Lt, val, end);
  2934. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  2935. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  2936. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  2937. lb_build_stmt(p, rs->body);
  2938. }
  2939. }
  2940. } else if (tav.mode == Addressing_Type) {
  2941. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  2942. Type *et = type_deref(tav.type);
  2943. Type *bet = base_type(et);
  2944. lbAddr val0_addr = {};
  2945. lbAddr val1_addr = {};
  2946. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2947. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2948. for_array(i, bet->Enum.fields) {
  2949. Entity *field = bet->Enum.fields[i];
  2950. GB_ASSERT(field->kind == Entity_Constant);
  2951. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  2952. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2953. lb_build_stmt(p, rs->body);
  2954. }
  2955. } else {
  2956. lbAddr val0_addr = {};
  2957. lbAddr val1_addr = {};
  2958. if (val0_type) val0_addr = lb_build_addr(p, rs->val0);
  2959. if (val1_type) val1_addr = lb_build_addr(p, rs->val1);
  2960. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  2961. Type *t = base_type(expr->tav.type);
  2962. switch (t->kind) {
  2963. case Type_Basic:
  2964. GB_ASSERT(is_type_string(t));
  2965. {
  2966. ExactValue value = expr->tav.value;
  2967. GB_ASSERT(value.kind == ExactValue_String);
  2968. String str = value.value_string;
  2969. Rune codepoint = 0;
  2970. isize offset = 0;
  2971. do {
  2972. isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint);
  2973. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  2974. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  2975. lb_build_stmt(p, rs->body);
  2976. offset += width;
  2977. } while (offset < str.len);
  2978. }
  2979. break;
  2980. case Type_Array:
  2981. if (t->Array.count > 0) {
  2982. lbValue val = lb_build_expr(p, expr);
  2983. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2984. for (i64 i = 0; i < t->Array.count; i++) {
  2985. if (val0_type) {
  2986. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  2987. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  2988. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  2989. }
  2990. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  2991. lb_build_stmt(p, rs->body);
  2992. }
  2993. }
  2994. break;
  2995. case Type_EnumeratedArray:
  2996. if (t->EnumeratedArray.count > 0) {
  2997. lbValue val = lb_build_expr(p, expr);
  2998. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  2999. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  3000. if (val0_type) {
  3001. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  3002. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  3003. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  3004. }
  3005. if (val1_type) {
  3006. ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value);
  3007. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  3008. }
  3009. lb_build_stmt(p, rs->body);
  3010. }
  3011. }
  3012. break;
  3013. default:
  3014. GB_PANIC("Invalid '#unroll for' type");
  3015. break;
  3016. }
  3017. }
  3018. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3019. }
  3020. void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) {
  3021. if (ss->init != nullptr) {
  3022. lb_build_stmt(p, ss->init);
  3023. }
  3024. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  3025. if (ss->tag != nullptr) {
  3026. tag = lb_build_expr(p, ss->tag);
  3027. }
  3028. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  3029. ast_node(body, BlockStmt, ss->body);
  3030. Slice<Ast *> default_stmts = {};
  3031. lbBlock *default_fall = nullptr;
  3032. lbBlock *default_block = nullptr;
  3033. lbBlock *fall = nullptr;
  3034. isize case_count = body->stmts.count;
  3035. for_array(i, body->stmts) {
  3036. Ast *clause = body->stmts[i];
  3037. ast_node(cc, CaseClause, clause);
  3038. lbBlock *body = fall;
  3039. if (body == nullptr) {
  3040. body = lb_create_block(p, "switch.case.body");
  3041. }
  3042. fall = done;
  3043. if (i+1 < case_count) {
  3044. fall = lb_create_block(p, "switch.fall.body");
  3045. }
  3046. if (cc->list.count == 0) {
  3047. // default case
  3048. default_stmts = cc->stmts;
  3049. default_fall = fall;
  3050. default_block = body;
  3051. continue;
  3052. }
  3053. lbBlock *next_cond = nullptr;
  3054. for_array(j, cc->list) {
  3055. Ast *expr = unparen_expr(cc->list[j]);
  3056. next_cond = lb_create_block(p, "switch.case.next");
  3057. lbValue cond = lb_const_bool(p->module, t_llvm_bool, false);
  3058. if (is_ast_range(expr)) {
  3059. ast_node(ie, BinaryExpr, expr);
  3060. TokenKind op = Token_Invalid;
  3061. switch (ie->op.kind) {
  3062. case Token_Ellipsis: op = Token_LtEq; break;
  3063. case Token_RangeHalf: op = Token_Lt; break;
  3064. default: GB_PANIC("Invalid interval operator"); break;
  3065. }
  3066. lbValue lhs = lb_build_expr(p, ie->left);
  3067. lbValue rhs = lb_build_expr(p, ie->right);
  3068. // TODO(bill): do short circuit here
  3069. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  3070. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  3071. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  3072. } else {
  3073. if (expr->tav.mode == Addressing_Type) {
  3074. GB_ASSERT(is_type_typeid(tag.type));
  3075. lbValue e = lb_typeid(p->module, expr->tav.type);
  3076. e = lb_emit_conv(p, e, tag.type);
  3077. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  3078. } else {
  3079. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  3080. }
  3081. }
  3082. lb_emit_if(p, cond, body, next_cond);
  3083. lb_start_block(p, next_cond);
  3084. }
  3085. lb_start_block(p, body);
  3086. lb_push_target_list(p, ss->label, done, nullptr, fall);
  3087. lb_open_scope(p);
  3088. lb_build_stmt_list(p, cc->stmts);
  3089. lb_close_scope(p, lbDeferExit_Default, body);
  3090. lb_pop_target_list(p);
  3091. lb_emit_jump(p, done);
  3092. lb_start_block(p, next_cond);
  3093. }
  3094. if (default_block != nullptr) {
  3095. lb_emit_jump(p, default_block);
  3096. lb_start_block(p, default_block);
  3097. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  3098. lb_open_scope(p);
  3099. lb_build_stmt_list(p, default_stmts);
  3100. lb_close_scope(p, lbDeferExit_Default, default_block);
  3101. lb_pop_target_list(p);
  3102. }
  3103. lb_emit_jump(p, done);
  3104. lb_start_block(p, done);
  3105. }
  3106. void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  3107. Entity *e = implicit_entity_of_node(clause);
  3108. GB_ASSERT(e != nullptr);
  3109. if (e->flags & EntityFlag_Value) {
  3110. // by value
  3111. GB_ASSERT(are_types_identical(e->type, value.type));
  3112. lbAddr x = lb_add_local(p, e->type, e, false);
  3113. lb_addr_store(p, x, value);
  3114. } else {
  3115. // by reference
  3116. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  3117. lb_add_entity(p->module, e, value);
  3118. }
  3119. }
  3120. lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  3121. Entity *e = entity_of_node(stmt_val);
  3122. if (e == nullptr) {
  3123. return {};
  3124. }
  3125. if ((e->flags & EntityFlag_Value) == 0) {
  3126. if (LLVMIsALoadInst(value.value)) {
  3127. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  3128. lb_add_entity(p->module, e, ptr);
  3129. return lb_addr(ptr);
  3130. }
  3131. }
  3132. // by value
  3133. lbAddr addr = lb_add_local(p, e->type, e, false);
  3134. lb_addr_store(p, addr, value);
  3135. return addr;
  3136. }
  3137. void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  3138. ast_node(cc, CaseClause, clause);
  3139. lb_push_target_list(p, label, done, nullptr, nullptr);
  3140. lb_open_scope(p);
  3141. lb_build_stmt_list(p, cc->stmts);
  3142. lb_close_scope(p, lbDeferExit_Default, body);
  3143. lb_pop_target_list(p);
  3144. lb_emit_jump(p, done);
  3145. }
  3146. void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  3147. lbModule *m = p->module;
  3148. ast_node(as, AssignStmt, ss->tag);
  3149. GB_ASSERT(as->lhs.count == 1);
  3150. GB_ASSERT(as->rhs.count == 1);
  3151. lbValue parent = lb_build_expr(p, as->rhs[0]);
  3152. bool is_parent_ptr = is_type_pointer(parent.type);
  3153. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  3154. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  3155. lbValue parent_value = parent;
  3156. lbValue parent_ptr = parent;
  3157. if (!is_parent_ptr) {
  3158. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  3159. }
  3160. lbValue tag_index = {};
  3161. lbValue union_data = {};
  3162. if (switch_kind == TypeSwitch_Union) {
  3163. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  3164. tag_index = lb_emit_load(p, tag_ptr);
  3165. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  3166. }
  3167. lbBlock *start_block = lb_create_block(p, "typeswitch.case.first");
  3168. lb_emit_jump(p, start_block);
  3169. lb_start_block(p, start_block);
  3170. // NOTE(bill): Append this later
  3171. lbBlock *done = lb_create_block(p, "typeswitch.done");
  3172. Ast *default_ = nullptr;
  3173. ast_node(body, BlockStmt, ss->body);
  3174. gb_local_persist i32 weird_count = 0;
  3175. for_array(i, body->stmts) {
  3176. Ast *clause = body->stmts[i];
  3177. ast_node(cc, CaseClause, clause);
  3178. if (cc->list.count == 0) {
  3179. default_ = clause;
  3180. continue;
  3181. }
  3182. lbBlock *body = lb_create_block(p, "typeswitch.body");
  3183. lbBlock *next = nullptr;
  3184. Type *case_type = nullptr;
  3185. for_array(type_index, cc->list) {
  3186. next = lb_create_block(p, "typeswitch.next");
  3187. case_type = type_of_expr(cc->list[type_index]);
  3188. lbValue cond = {};
  3189. if (switch_kind == TypeSwitch_Union) {
  3190. Type *ut = base_type(type_deref(parent.type));
  3191. lbValue variant_tag = lb_const_union_tag(m, ut, case_type);
  3192. cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag);
  3193. } else if (switch_kind == TypeSwitch_Any) {
  3194. lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  3195. lbValue case_typeid = lb_typeid(m, case_type);
  3196. cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid);
  3197. }
  3198. GB_ASSERT(cond.value != nullptr);
  3199. lb_emit_if(p, cond, body, next);
  3200. lb_start_block(p, next);
  3201. }
  3202. Entity *case_entity = implicit_entity_of_node(clause);
  3203. lbValue value = parent_value;
  3204. lb_start_block(p, body);
  3205. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  3206. if (cc->list.count == 1) {
  3207. lbValue data = {};
  3208. if (switch_kind == TypeSwitch_Union) {
  3209. data = union_data;
  3210. } else if (switch_kind == TypeSwitch_Any) {
  3211. lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  3212. data = any_data;
  3213. }
  3214. Type *ct = case_entity->type;
  3215. Type *ct_ptr = alloc_type_pointer(ct);
  3216. value = lb_emit_conv(p, data, ct_ptr);
  3217. if (!by_reference) {
  3218. value = lb_emit_load(p, value);
  3219. }
  3220. }
  3221. lb_store_type_case_implicit(p, clause, value);
  3222. lb_type_case_body(p, ss->label, clause, body, done);
  3223. lb_start_block(p, next);
  3224. }
  3225. if (default_ != nullptr) {
  3226. lb_store_type_case_implicit(p, default_, parent_value);
  3227. lb_type_case_body(p, ss->label, default_, p->curr_block, done);
  3228. } else {
  3229. lb_emit_jump(p, done);
  3230. }
  3231. lb_start_block(p, done);
  3232. }
  3233. lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) {
  3234. lbModule *m = p->module;
  3235. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  3236. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  3237. type = default_type(type);
  3238. lbValue short_circuit = {};
  3239. if (op == Token_CmpAnd) {
  3240. lb_build_cond(p, left, rhs, done);
  3241. short_circuit = lb_const_bool(m, type, false);
  3242. } else if (op == Token_CmpOr) {
  3243. lb_build_cond(p, left, done, rhs);
  3244. short_circuit = lb_const_bool(m, type, true);
  3245. }
  3246. if (rhs->preds.count == 0) {
  3247. lb_start_block(p, done);
  3248. return short_circuit;
  3249. }
  3250. if (done->preds.count == 0) {
  3251. lb_start_block(p, rhs);
  3252. return lb_build_expr(p, right);
  3253. }
  3254. Array<LLVMValueRef> incoming_values = {};
  3255. Array<LLVMBasicBlockRef> incoming_blocks = {};
  3256. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  3257. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  3258. for_array(i, done->preds) {
  3259. incoming_values[i] = short_circuit.value;
  3260. incoming_blocks[i] = done->preds[i]->block;
  3261. }
  3262. lb_start_block(p, rhs);
  3263. lbValue edge = lb_build_expr(p, right);
  3264. incoming_values[done->preds.count] = edge.value;
  3265. incoming_blocks[done->preds.count] = p->curr_block->block;
  3266. lb_emit_jump(p, done);
  3267. lb_start_block(p, done);
  3268. lbValue res = {};
  3269. res.type = type;
  3270. res.value = LLVMBuildPhi(p->builder, lb_type(m, type), "");
  3271. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  3272. LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  3273. return res;
  3274. }
  3275. void lb_build_stmt(lbProcedure *p, Ast *node) {
  3276. Ast *prev_stmt = p->curr_stmt;
  3277. defer (p->curr_stmt = prev_stmt);
  3278. p->curr_stmt = node;
  3279. if (p->curr_block != nullptr) {
  3280. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  3281. if (lb_is_instr_terminating(last_instr)) {
  3282. return;
  3283. }
  3284. }
  3285. u64 prev_state_flags = p->module->state_flags;
  3286. defer (p->module->state_flags = prev_state_flags);
  3287. if (node->state_flags != 0) {
  3288. u64 in = node->state_flags;
  3289. u64 out = p->module->state_flags;
  3290. if (in & StateFlag_bounds_check) {
  3291. out |= StateFlag_bounds_check;
  3292. out &= ~StateFlag_no_bounds_check;
  3293. } else if (in & StateFlag_no_bounds_check) {
  3294. out |= StateFlag_no_bounds_check;
  3295. out &= ~StateFlag_bounds_check;
  3296. }
  3297. p->module->state_flags = out;
  3298. }
  3299. switch (node->kind) {
  3300. case_ast_node(bs, EmptyStmt, node);
  3301. case_end;
  3302. case_ast_node(us, UsingStmt, node);
  3303. case_end;
  3304. case_ast_node(ws, WhenStmt, node);
  3305. lb_build_when_stmt(p, ws);
  3306. case_end;
  3307. case_ast_node(bs, BlockStmt, node);
  3308. if (bs->label != nullptr) {
  3309. lbBlock *done = lb_create_block(p, "block.done");
  3310. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  3311. tl->is_block = true;
  3312. lb_open_scope(p);
  3313. lb_build_stmt_list(p, bs->stmts);
  3314. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3315. lb_emit_jump(p, done);
  3316. lb_start_block(p, done);
  3317. } else {
  3318. lb_open_scope(p);
  3319. lb_build_stmt_list(p, bs->stmts);
  3320. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3321. }
  3322. case_end;
  3323. case_ast_node(vd, ValueDecl, node);
  3324. if (!vd->is_mutable) {
  3325. return;
  3326. }
  3327. bool is_static = false;
  3328. if (vd->names.count > 0) {
  3329. Entity *e = entity_of_node(vd->names[0]);
  3330. if (e->flags & EntityFlag_Static) {
  3331. // NOTE(bill): If one of the entities is static, they all are
  3332. is_static = true;
  3333. }
  3334. }
  3335. if (is_static) {
  3336. for_array(i, vd->names) {
  3337. lbValue value = {};
  3338. if (vd->values.count > 0) {
  3339. GB_ASSERT(vd->names.count == vd->values.count);
  3340. Ast *ast_value = vd->values[i];
  3341. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  3342. ast_value->tav.mode == Addressing_Invalid);
  3343. bool allow_local = false;
  3344. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  3345. }
  3346. Ast *ident = vd->names[i];
  3347. GB_ASSERT(!is_blank_ident(ident));
  3348. Entity *e = entity_of_node(ident);
  3349. GB_ASSERT(e->flags & EntityFlag_Static);
  3350. String name = e->token.string;
  3351. String mangled_name = {};
  3352. {
  3353. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  3354. str = gb_string_appendc(str, "-");
  3355. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  3356. mangled_name.text = cast(u8 *)str;
  3357. mangled_name.len = gb_string_length(str);
  3358. }
  3359. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  3360. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  3361. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  3362. if (value.value != nullptr) {
  3363. LLVMSetInitializer(global, value.value);
  3364. } else {
  3365. }
  3366. if (e->Variable.thread_local_model != "") {
  3367. LLVMSetThreadLocal(global, true);
  3368. String m = e->Variable.thread_local_model;
  3369. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  3370. if (m == "default") {
  3371. mode = LLVMGeneralDynamicTLSModel;
  3372. } else if (m == "localdynamic") {
  3373. mode = LLVMLocalDynamicTLSModel;
  3374. } else if (m == "initialexec") {
  3375. mode = LLVMInitialExecTLSModel;
  3376. } else if (m == "localexec") {
  3377. mode = LLVMLocalExecTLSModel;
  3378. } else {
  3379. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  3380. }
  3381. LLVMSetThreadLocalMode(global, mode);
  3382. } else {
  3383. LLVMSetLinkage(global, LLVMInternalLinkage);
  3384. }
  3385. lbValue global_val = {global, alloc_type_pointer(e->type)};
  3386. lb_add_entity(p->module, e, global_val);
  3387. lb_add_member(p->module, mangled_name, global_val);
  3388. }
  3389. return;
  3390. }
  3391. if (vd->values.count == 0) { // declared and zero-initialized
  3392. for_array(i, vd->names) {
  3393. Ast *name = vd->names[i];
  3394. if (!is_blank_ident(name)) {
  3395. Entity *e = entity_of_node(name);
  3396. lb_add_local(p, e->type, e, true);
  3397. }
  3398. }
  3399. } else { // Tuple(s)
  3400. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, vd->names.count);
  3401. auto inits = array_make<lbValue>(permanent_allocator(), 0, vd->names.count);
  3402. for_array(i, vd->names) {
  3403. Ast *name = vd->names[i];
  3404. lbAddr lval = {};
  3405. if (!is_blank_ident(name)) {
  3406. Entity *e = entity_of_node(name);
  3407. lval = lb_add_local(p, e->type, e, false);
  3408. }
  3409. array_add(&lvals, lval);
  3410. }
  3411. for_array(i, vd->values) {
  3412. lbValue init = lb_build_expr(p, vd->values[i]);
  3413. Type *t = init.type;
  3414. if (t->kind == Type_Tuple) {
  3415. for_array(i, t->Tuple.variables) {
  3416. Entity *e = t->Tuple.variables[i];
  3417. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3418. array_add(&inits, v);
  3419. }
  3420. } else {
  3421. array_add(&inits, init);
  3422. }
  3423. }
  3424. for_array(i, inits) {
  3425. lbAddr lval = lvals[i];
  3426. lbValue init = inits[i];
  3427. lb_addr_store(p, lval, init);
  3428. }
  3429. }
  3430. case_end;
  3431. case_ast_node(as, AssignStmt, node);
  3432. if (as->op.kind == Token_Eq) {
  3433. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  3434. for_array(i, as->lhs) {
  3435. Ast *lhs = as->lhs[i];
  3436. lbAddr lval = {};
  3437. if (!is_blank_ident(lhs)) {
  3438. lval = lb_build_addr(p, lhs);
  3439. }
  3440. array_add(&lvals, lval);
  3441. }
  3442. if (as->lhs.count == as->rhs.count) {
  3443. if (as->lhs.count == 1) {
  3444. lbAddr lval = lvals[0];
  3445. Ast *rhs = as->rhs[0];
  3446. lbValue init = lb_build_expr(p, rhs);
  3447. lb_addr_store(p, lvals[0], init);
  3448. } else {
  3449. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3450. for_array(i, as->rhs) {
  3451. lbValue init = lb_build_expr(p, as->rhs[i]);
  3452. array_add(&inits, init);
  3453. }
  3454. for_array(i, inits) {
  3455. lbAddr lval = lvals[i];
  3456. lbValue init = inits[i];
  3457. lb_addr_store(p, lval, init);
  3458. }
  3459. }
  3460. } else {
  3461. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  3462. for_array(i, as->rhs) {
  3463. lbValue init = lb_build_expr(p, as->rhs[i]);
  3464. Type *t = init.type;
  3465. // TODO(bill): refactor for code reuse as this is repeated a bit
  3466. if (t->kind == Type_Tuple) {
  3467. for_array(i, t->Tuple.variables) {
  3468. Entity *e = t->Tuple.variables[i];
  3469. lbValue v = lb_emit_struct_ev(p, init, cast(i32)i);
  3470. array_add(&inits, v);
  3471. }
  3472. } else {
  3473. array_add(&inits, init);
  3474. }
  3475. }
  3476. for_array(i, inits) {
  3477. lbAddr lval = lvals[i];
  3478. lbValue init = inits[i];
  3479. lb_addr_store(p, lval, init);
  3480. }
  3481. }
  3482. } else {
  3483. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  3484. // +=, -=, etc
  3485. i32 op = cast(i32)as->op.kind;
  3486. op += Token_Add - Token_AddEq; // Convert += to +
  3487. if (op == Token_CmpAnd || op == Token_CmpOr) {
  3488. Type *type = as->lhs[0]->tav.type;
  3489. lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type);
  3490. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3491. lb_addr_store(p, lhs, new_value);
  3492. } else {
  3493. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  3494. lbValue value = lb_build_expr(p, as->rhs[0]);
  3495. lbValue old_value = lb_addr_load(p, lhs);
  3496. Type *type = old_value.type;
  3497. lbValue change = lb_emit_conv(p, value, type);
  3498. lbValue new_value = lb_emit_arith(p, cast(TokenKind)op, old_value, change, type);
  3499. lb_addr_store(p, lhs, new_value);
  3500. }
  3501. return;
  3502. }
  3503. case_end;
  3504. case_ast_node(es, ExprStmt, node);
  3505. lb_build_expr(p, es->expr);
  3506. case_end;
  3507. case_ast_node(ds, DeferStmt, node);
  3508. isize scope_index = p->scope_index;
  3509. lb_add_defer_node(p, scope_index, ds->stmt);
  3510. case_end;
  3511. case_ast_node(rs, ReturnStmt, node);
  3512. lbValue res = {};
  3513. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  3514. isize return_count = p->type->Proc.result_count;
  3515. isize res_count = rs->results.count;
  3516. if (return_count == 0) {
  3517. // No return values
  3518. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3519. LLVMBuildRetVoid(p->builder);
  3520. return;
  3521. } else if (return_count == 1) {
  3522. Entity *e = tuple->variables[0];
  3523. if (res_count == 0) {
  3524. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3525. GB_ASSERT(found);
  3526. res = lb_emit_load(p, *found);
  3527. } else {
  3528. res = lb_build_expr(p, rs->results[0]);
  3529. res = lb_emit_conv(p, res, e->type);
  3530. }
  3531. if (p->type->Proc.has_named_results) {
  3532. // NOTE(bill): store the named values before returning
  3533. if (e->token.string != "") {
  3534. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3535. GB_ASSERT(found != nullptr);
  3536. lb_emit_store(p, *found, lb_emit_conv(p, res, e->type));
  3537. }
  3538. }
  3539. } else {
  3540. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  3541. if (res_count != 0) {
  3542. for (isize res_index = 0; res_index < res_count; res_index++) {
  3543. lbValue res = lb_build_expr(p, rs->results[res_index]);
  3544. Type *t = res.type;
  3545. if (t->kind == Type_Tuple) {
  3546. for_array(i, t->Tuple.variables) {
  3547. Entity *e = t->Tuple.variables[i];
  3548. lbValue v = lb_emit_struct_ev(p, res, cast(i32)i);
  3549. array_add(&results, v);
  3550. }
  3551. } else {
  3552. array_add(&results, res);
  3553. }
  3554. }
  3555. } else {
  3556. for (isize res_index = 0; res_index < return_count; res_index++) {
  3557. Entity *e = tuple->variables[res_index];
  3558. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3559. GB_ASSERT(found);
  3560. lbValue res = lb_emit_load(p, *found);
  3561. array_add(&results, res);
  3562. }
  3563. }
  3564. GB_ASSERT(results.count == return_count);
  3565. if (p->type->Proc.has_named_results) {
  3566. // NOTE(bill): store the named values before returning
  3567. for_array(i, p->type->Proc.results->Tuple.variables) {
  3568. Entity *e = p->type->Proc.results->Tuple.variables[i];
  3569. if (e->kind != Entity_Variable) {
  3570. continue;
  3571. }
  3572. if (e->token.string == "") {
  3573. continue;
  3574. }
  3575. lbValue *found = map_get(&p->module->values, hash_entity(e));
  3576. GB_ASSERT(found != nullptr);
  3577. lb_emit_store(p, *found, lb_emit_conv(p, results[i], e->type));
  3578. }
  3579. }
  3580. Type *ret_type = p->type->Proc.results;
  3581. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  3582. res = lb_add_local_generated(p, ret_type, false).addr;
  3583. for_array(i, results) {
  3584. Entity *e = tuple->variables[i];
  3585. lbValue field = lb_emit_struct_ep(p, res, cast(i32)i);
  3586. lbValue val = lb_emit_conv(p, results[i], e->type);
  3587. lb_emit_store(p, field, val);
  3588. }
  3589. res = lb_emit_load(p, res);
  3590. }
  3591. lb_ensure_abi_function_type(p->module, p);
  3592. if (p->abi_function_type->ret.kind == lbArg_Indirect) {
  3593. if (res.value != nullptr) {
  3594. LLVMBuildStore(p->builder, res.value, p->return_ptr.addr.value);
  3595. } else {
  3596. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  3597. }
  3598. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3599. LLVMBuildRetVoid(p->builder);
  3600. } else {
  3601. LLVMValueRef ret_val = res.value;
  3602. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  3603. if (p->abi_function_type->ret.cast_type != nullptr) {
  3604. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  3605. }
  3606. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  3607. LLVMBuildRet(p->builder, ret_val);
  3608. }
  3609. case_end;
  3610. case_ast_node(is, IfStmt, node);
  3611. lb_open_scope(p); // Scope #1
  3612. if (is->init != nullptr) {
  3613. // TODO(bill): Should this have a separate block to begin with?
  3614. #if 1
  3615. lbBlock *init = lb_create_block(p, "if.init");
  3616. lb_emit_jump(p, init);
  3617. lb_start_block(p, init);
  3618. #endif
  3619. lb_build_stmt(p, is->init);
  3620. }
  3621. lbBlock *then = lb_create_block(p, "if.then");
  3622. lbBlock *done = lb_create_block(p, "if.done");
  3623. lbBlock *else_ = done;
  3624. if (is->else_stmt != nullptr) {
  3625. else_ = lb_create_block(p, "if.else");
  3626. }
  3627. lb_build_cond(p, is->cond, then, else_);
  3628. lb_start_block(p, then);
  3629. if (is->label != nullptr) {
  3630. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  3631. tl->is_block = true;
  3632. }
  3633. lb_build_stmt(p, is->body);
  3634. lb_emit_jump(p, done);
  3635. if (is->else_stmt != nullptr) {
  3636. lb_start_block(p, else_);
  3637. lb_open_scope(p);
  3638. lb_build_stmt(p, is->else_stmt);
  3639. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3640. lb_emit_jump(p, done);
  3641. }
  3642. lb_start_block(p, done);
  3643. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3644. case_end;
  3645. case_ast_node(fs, ForStmt, node);
  3646. lb_open_scope(p); // Open Scope here
  3647. if (fs->init != nullptr) {
  3648. #if 1
  3649. lbBlock *init = lb_create_block(p, "for.init");
  3650. lb_emit_jump(p, init);
  3651. lb_start_block(p, init);
  3652. #endif
  3653. lb_build_stmt(p, fs->init);
  3654. }
  3655. lbBlock *body = lb_create_block(p, "for.body");
  3656. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  3657. lbBlock *loop = body;
  3658. if (fs->cond != nullptr) {
  3659. loop = lb_create_block(p, "for.loop");
  3660. }
  3661. lbBlock *post = loop;
  3662. if (fs->post != nullptr) {
  3663. post = lb_create_block(p, "for.post");
  3664. }
  3665. lb_emit_jump(p, loop);
  3666. lb_start_block(p, loop);
  3667. if (loop != body) {
  3668. lb_build_cond(p, fs->cond, body, done);
  3669. lb_start_block(p, body);
  3670. }
  3671. lb_push_target_list(p, fs->label, done, post, nullptr);
  3672. lb_build_stmt(p, fs->body);
  3673. lb_close_scope(p, lbDeferExit_Default, nullptr);
  3674. lb_pop_target_list(p);
  3675. lb_emit_jump(p, post);
  3676. if (fs->post != nullptr) {
  3677. lb_start_block(p, post);
  3678. lb_build_stmt(p, fs->post);
  3679. lb_emit_jump(p, loop);
  3680. }
  3681. lb_start_block(p, done);
  3682. case_end;
  3683. case_ast_node(rs, RangeStmt, node);
  3684. lb_build_range_stmt(p, rs);
  3685. case_end;
  3686. case_ast_node(rs, InlineRangeStmt, node);
  3687. lb_build_inline_range_stmt(p, rs);
  3688. case_end;
  3689. case_ast_node(ss, SwitchStmt, node);
  3690. lb_build_switch_stmt(p, ss);
  3691. case_end;
  3692. case_ast_node(ss, TypeSwitchStmt, node);
  3693. lb_build_type_switch_stmt(p, ss);
  3694. case_end;
  3695. case_ast_node(bs, BranchStmt, node);
  3696. lbBlock *block = nullptr;
  3697. if (bs->label != nullptr) {
  3698. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  3699. switch (bs->token.kind) {
  3700. case Token_break: block = bb.break_; break;
  3701. case Token_continue: block = bb.continue_; break;
  3702. case Token_fallthrough:
  3703. GB_PANIC("fallthrough cannot have a label");
  3704. break;
  3705. }
  3706. } else {
  3707. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  3708. if (t->is_block) {
  3709. continue;
  3710. }
  3711. switch (bs->token.kind) {
  3712. case Token_break: block = t->break_; break;
  3713. case Token_continue: block = t->continue_; break;
  3714. case Token_fallthrough: block = t->fallthrough_; break;
  3715. }
  3716. }
  3717. }
  3718. if (block != nullptr) {
  3719. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  3720. }
  3721. lb_emit_jump(p, block);
  3722. case_end;
  3723. }
  3724. }
  3725. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  3726. cond = lb_emit_conv(p, cond, t_llvm_bool);
  3727. lbValue res = {};
  3728. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  3729. res.type = x.type;
  3730. return res;
  3731. }
  3732. lbValue lb_const_nil(lbModule *m, Type *type) {
  3733. LLVMValueRef v = LLVMConstNull(lb_type(m, type));
  3734. return lbValue{v, type};
  3735. }
  3736. lbValue lb_const_undef(lbModule *m, Type *type) {
  3737. LLVMValueRef v = LLVMGetUndef(lb_type(m, type));
  3738. return lbValue{v, type};
  3739. }
  3740. lbValue lb_const_int(lbModule *m, Type *type, u64 value) {
  3741. lbValue res = {};
  3742. res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type));
  3743. res.type = type;
  3744. return res;
  3745. }
  3746. lbValue lb_const_string(lbModule *m, String const &value) {
  3747. return lb_const_value(m, t_string, exact_value_string(value));
  3748. }
  3749. lbValue lb_const_bool(lbModule *m, Type *type, bool value) {
  3750. lbValue res = {};
  3751. res.value = LLVMConstInt(lb_type(m, type), value, false);
  3752. res.type = type;
  3753. return res;
  3754. }
  3755. LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) {
  3756. GB_ASSERT(type_size_of(type) == 4);
  3757. u32 u = bit_cast<u32>(f);
  3758. if (is_type_different_to_arch_endianness(type)) {
  3759. u = gb_endian_swap32(u);
  3760. }
  3761. LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false);
  3762. return LLVMConstBitCast(i, lb_type(m, type));
  3763. }
  3764. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3765. x = lb_emit_conv(p, x, t);
  3766. y = lb_emit_conv(p, y, t);
  3767. if (is_type_float(t)) {
  3768. i64 sz = 8*type_size_of(t);
  3769. auto args = array_make<lbValue>(permanent_allocator(), 2);
  3770. args[0] = x;
  3771. args[1] = y;
  3772. switch (sz) {
  3773. case 32: return lb_emit_runtime_call(p, "min_f32", args);
  3774. case 64: return lb_emit_runtime_call(p, "min_f64", args);
  3775. }
  3776. GB_PANIC("Unknown float type");
  3777. }
  3778. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  3779. }
  3780. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  3781. x = lb_emit_conv(p, x, t);
  3782. y = lb_emit_conv(p, y, t);
  3783. if (is_type_float(t)) {
  3784. i64 sz = 8*type_size_of(t);
  3785. auto args = array_make<lbValue>(permanent_allocator(), 2);
  3786. args[0] = x;
  3787. args[1] = y;
  3788. switch (sz) {
  3789. case 32: return lb_emit_runtime_call(p, "max_f32", args);
  3790. case 64: return lb_emit_runtime_call(p, "max_f64", args);
  3791. }
  3792. GB_PANIC("Unknown float type");
  3793. }
  3794. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  3795. }
  3796. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  3797. lbValue z = {};
  3798. z = lb_emit_max(p, t, x, min);
  3799. z = lb_emit_min(p, t, z, max);
  3800. return z;
  3801. }
  3802. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  3803. StringHashKey key = string_hash_string(str);
  3804. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  3805. if (found != nullptr) {
  3806. return *found;
  3807. } else {
  3808. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  3809. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3810. cast(char const *)str.text,
  3811. cast(unsigned)str.len,
  3812. false);
  3813. isize max_len = 7+8+1;
  3814. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  3815. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3816. len -= 1;
  3817. m->global_array_index++;
  3818. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3819. LLVMSetInitializer(global_data, data);
  3820. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  3821. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3822. string_map_set(&m->const_strings, key, ptr);
  3823. return ptr;
  3824. }
  3825. }
  3826. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  3827. LLVMValueRef ptr = nullptr;
  3828. if (str.len != 0) {
  3829. ptr = lb_find_or_add_entity_string_ptr(m, str);
  3830. } else {
  3831. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  3832. }
  3833. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3834. LLVMValueRef values[2] = {ptr, str_len};
  3835. lbValue res = {};
  3836. res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2);
  3837. res.type = t_string;
  3838. return res;
  3839. }
  3840. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  3841. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  3842. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  3843. cast(char const *)str.text,
  3844. cast(unsigned)str.len,
  3845. false);
  3846. char *name = nullptr;
  3847. {
  3848. isize max_len = 7+8+1;
  3849. name = gb_alloc_array(permanent_allocator(), char, max_len);
  3850. isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index);
  3851. len -= 1;
  3852. m->global_array_index++;
  3853. }
  3854. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  3855. LLVMSetInitializer(global_data, data);
  3856. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  3857. LLVMValueRef ptr = nullptr;
  3858. if (str.len != 0) {
  3859. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  3860. } else {
  3861. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  3862. }
  3863. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  3864. LLVMValueRef values[2] = {ptr, len};
  3865. lbValue res = {};
  3866. res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2);
  3867. res.type = t_u8_slice;
  3868. return res;
  3869. }
  3870. isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) {
  3871. isize index = type_info_index(info, type, false);
  3872. if (index >= 0) {
  3873. auto *set = &info->minimum_dependency_type_info_set;
  3874. for_array(i, set->entries) {
  3875. if (set->entries[i].ptr == index) {
  3876. return i+1;
  3877. }
  3878. }
  3879. }
  3880. if (err_on_not_found) {
  3881. GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index);
  3882. }
  3883. return -1;
  3884. }
  3885. lbValue lb_typeid(lbModule *m, Type *type) {
  3886. type = default_type(type);
  3887. u64 id = cast(u64)lb_type_info_index(m->info, type);
  3888. GB_ASSERT(id >= 0);
  3889. u64 kind = Typeid_Invalid;
  3890. u64 named = is_type_named(type) && type->kind != Type_Basic;
  3891. u64 special = 0;
  3892. u64 reserved = 0;
  3893. Type *bt = base_type(type);
  3894. TypeKind tk = bt->kind;
  3895. switch (tk) {
  3896. case Type_Basic: {
  3897. u32 flags = bt->Basic.flags;
  3898. if (flags & BasicFlag_Boolean) kind = Typeid_Boolean;
  3899. if (flags & BasicFlag_Integer) kind = Typeid_Integer;
  3900. if (flags & BasicFlag_Unsigned) kind = Typeid_Integer;
  3901. if (flags & BasicFlag_Float) kind = Typeid_Float;
  3902. if (flags & BasicFlag_Complex) kind = Typeid_Complex;
  3903. if (flags & BasicFlag_Pointer) kind = Typeid_Pointer;
  3904. if (flags & BasicFlag_String) kind = Typeid_String;
  3905. if (flags & BasicFlag_Rune) kind = Typeid_Rune;
  3906. } break;
  3907. case Type_Pointer: kind = Typeid_Pointer; break;
  3908. case Type_Array: kind = Typeid_Array; break;
  3909. case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break;
  3910. case Type_Slice: kind = Typeid_Slice; break;
  3911. case Type_DynamicArray: kind = Typeid_Dynamic_Array; break;
  3912. case Type_Map: kind = Typeid_Map; break;
  3913. case Type_Struct: kind = Typeid_Struct; break;
  3914. case Type_Enum: kind = Typeid_Enum; break;
  3915. case Type_Union: kind = Typeid_Union; break;
  3916. case Type_Tuple: kind = Typeid_Tuple; break;
  3917. case Type_Proc: kind = Typeid_Procedure; break;
  3918. case Type_BitSet: kind = Typeid_Bit_Set; break;
  3919. case Type_SimdVector: kind = Typeid_Simd_Vector; break;
  3920. case Type_RelativePointer: kind = Typeid_Relative_Pointer; break;
  3921. case Type_RelativeSlice: kind = Typeid_Relative_Slice; break;
  3922. }
  3923. if (is_type_cstring(type)) {
  3924. special = 1;
  3925. } else if (is_type_integer(type) && !is_type_unsigned(type)) {
  3926. special = 1;
  3927. }
  3928. u64 data = 0;
  3929. if (build_context.word_size == 4) {
  3930. GB_ASSERT(id <= (1u<<24u));
  3931. data |= (id &~ (1u<<24)) << 0u; // index
  3932. data |= (kind &~ (1u<<5)) << 24u; // kind
  3933. data |= (named &~ (1u<<1)) << 29u; // kind
  3934. data |= (special &~ (1u<<1)) << 30u; // kind
  3935. data |= (reserved &~ (1u<<1)) << 31u; // kind
  3936. } else {
  3937. GB_ASSERT(build_context.word_size == 8);
  3938. GB_ASSERT(id <= (1ull<<56u));
  3939. data |= (id &~ (1ull<<56)) << 0ul; // index
  3940. data |= (kind &~ (1ull<<5)) << 56ull; // kind
  3941. data |= (named &~ (1ull<<1)) << 61ull; // kind
  3942. data |= (special &~ (1ull<<1)) << 62ull; // kind
  3943. data |= (reserved &~ (1ull<<1)) << 63ull; // kind
  3944. }
  3945. lbValue res = {};
  3946. res.value = LLVMConstInt(lb_type(m, t_typeid), data, false);
  3947. res.type = t_typeid;
  3948. return res;
  3949. }
  3950. lbValue lb_type_info(lbModule *m, Type *type) {
  3951. type = default_type(type);
  3952. isize index = lb_type_info_index(m->info, type);
  3953. GB_ASSERT(index >= 0);
  3954. LLVMTypeRef it = lb_type(m, t_int);
  3955. LLVMValueRef indices[2] = {
  3956. LLVMConstInt(it, 0, false),
  3957. LLVMConstInt(it, index, true),
  3958. };
  3959. lbValue value = {};
  3960. value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices));
  3961. value.type = t_type_info_ptr;
  3962. return value;
  3963. }
  3964. LLVMValueRef lb_build_constant_array_values(lbModule *m, Type *type, Type *elem_type, isize count, LLVMValueRef *values, bool allow_local) {
  3965. bool is_local = allow_local && m->curr_procedure != nullptr;
  3966. bool is_const = true;
  3967. if (is_local) {
  3968. for (isize i = 0; i < count; i++) {
  3969. GB_ASSERT(values[i] != nullptr);
  3970. if (!LLVMIsConstant(values[i])) {
  3971. is_const = false;
  3972. break;
  3973. }
  3974. }
  3975. }
  3976. if (!is_const) {
  3977. lbProcedure *p = m->curr_procedure;
  3978. GB_ASSERT(p != nullptr);
  3979. lbAddr v = lb_add_local_generated(p, type, false);
  3980. lbValue ptr = lb_addr_get_ptr(p, v);
  3981. for (isize i = 0; i < count; i++) {
  3982. lbValue elem = lb_emit_array_epi(p, ptr, i);
  3983. LLVMBuildStore(p->builder, values[i], elem.value);
  3984. }
  3985. return lb_addr_load(p, v).value;
  3986. }
  3987. return LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)count);
  3988. }
  3989. lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_local) {
  3990. LLVMContextRef ctx = m->ctx;
  3991. type = default_type(type);
  3992. Type *original_type = type;
  3993. lbValue res = {};
  3994. res.type = original_type;
  3995. type = core_type(type);
  3996. value = convert_exact_value_for_type(value, type);
  3997. if (value.kind == ExactValue_Typeid) {
  3998. return lb_typeid(m, value.value_typeid);
  3999. }
  4000. if (value.kind == ExactValue_Invalid) {
  4001. return lb_const_nil(m, type);
  4002. }
  4003. if (value.kind == ExactValue_Procedure) {
  4004. Ast *expr = unparen_expr(value.value_procedure);
  4005. if (expr->kind == Ast_ProcLit) {
  4006. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4007. }
  4008. Entity *e = entity_from_expr(expr);
  4009. e = strip_entity_wrapping(e);
  4010. GB_ASSERT(e != nullptr);
  4011. auto *found = map_get(&m->values, hash_entity(e));
  4012. if (found) {
  4013. return *found;
  4014. }
  4015. 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));
  4016. }
  4017. bool is_local = allow_local && m->curr_procedure != nullptr;
  4018. // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type));
  4019. if (is_type_slice(type)) {
  4020. if (value.kind == ExactValue_String) {
  4021. GB_ASSERT(is_type_u8_slice(type));
  4022. res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value;
  4023. return res;
  4024. } else {
  4025. ast_node(cl, CompoundLit, value.value_compound);
  4026. isize count = cl->elems.count;
  4027. if (count == 0) {
  4028. return lb_const_nil(m, type);
  4029. }
  4030. count = gb_max(cl->max_count, count);
  4031. Type *elem = base_type(type)->Slice.elem;
  4032. Type *t = alloc_type_array(elem, count);
  4033. lbValue backing_array = lb_const_value(m, t, value, allow_local);
  4034. LLVMValueRef array_data = nullptr;
  4035. if (is_local) {
  4036. // NOTE(bill, 2020-06-08): This is a bit of a hack but a "constant" slice needs
  4037. // its backing data on the stack
  4038. lbProcedure *p = m->curr_procedure;
  4039. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  4040. LLVMTypeRef llvm_type = lb_type(m, t);
  4041. array_data = LLVMBuildAlloca(p->builder, llvm_type, "");
  4042. LLVMSetAlignment(array_data, 16); // TODO(bill): Make this configurable
  4043. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  4044. LLVMBuildStore(p->builder, backing_array.value, array_data);
  4045. {
  4046. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4047. LLVMValueRef ptr = LLVMBuildInBoundsGEP(p->builder, array_data, indices, 2, "");
  4048. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4049. lbAddr slice = lb_add_local_generated(p, type, false);
  4050. lb_fill_slice(p, slice, {ptr, alloc_type_pointer(elem)}, {len, t_int});
  4051. return lb_addr_load(p, slice);
  4052. }
  4053. } else {
  4054. isize max_len = 7+8+1;
  4055. char *str = gb_alloc_array(permanent_allocator(), char, max_len);
  4056. isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index);
  4057. m->global_array_index++;
  4058. String name = make_string(cast(u8 *)str, len-1);
  4059. Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value);
  4060. array_data = LLVMAddGlobal(m->mod, lb_type(m, t), str);
  4061. LLVMSetInitializer(array_data, backing_array.value);
  4062. lbValue g = {};
  4063. g.value = array_data;
  4064. g.type = t;
  4065. lb_add_entity(m, e, g);
  4066. lb_add_member(m, name, g);
  4067. {
  4068. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  4069. LLVMValueRef ptr = LLVMConstInBoundsGEP(array_data, indices, 2);
  4070. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true);
  4071. LLVMValueRef values[2] = {ptr, len};
  4072. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4073. return res;
  4074. }
  4075. }
  4076. }
  4077. } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) {
  4078. if (is_type_rune_array(type) && value.kind == ExactValue_String) {
  4079. i64 count = type->Array.count;
  4080. Type *elem = type->Array.elem;
  4081. LLVMTypeRef et = lb_type(m, elem);
  4082. Rune rune;
  4083. isize offset = 0;
  4084. isize width = 1;
  4085. String s = value.value_string;
  4086. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4087. for (i64 i = 0; i < count && offset < s.len; i++) {
  4088. width = gb_utf8_decode(s.text+offset, s.len-offset, &rune);
  4089. offset += width;
  4090. elems[i] = LLVMConstInt(et, rune, true);
  4091. }
  4092. GB_ASSERT(offset == s.len);
  4093. res.value = LLVMConstArray(et, elems, cast(unsigned)count);
  4094. return res;
  4095. }
  4096. GB_PANIC("HERE!\n");
  4097. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4098. cast(char const *)value.value_string.text,
  4099. cast(unsigned)value.value_string.len,
  4100. false /*DontNullTerminate*/);
  4101. res.value = data;
  4102. return res;
  4103. } else if (is_type_u8_array(type) && value.kind == ExactValue_String) {
  4104. GB_ASSERT(type->Array.count == value.value_string.len);
  4105. LLVMValueRef data = LLVMConstStringInContext(ctx,
  4106. cast(char const *)value.value_string.text,
  4107. cast(unsigned)value.value_string.len,
  4108. true /*DontNullTerminate*/);
  4109. res.value = data;
  4110. return res;
  4111. } else if (is_type_array(type) &&
  4112. value.kind != ExactValue_Invalid &&
  4113. value.kind != ExactValue_String &&
  4114. value.kind != ExactValue_Compound) {
  4115. i64 count = type->Array.count;
  4116. Type *elem = type->Array.elem;
  4117. lbValue single_elem = lb_const_value(m, elem, value, allow_local);
  4118. LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, count);
  4119. for (i64 i = 0; i < count; i++) {
  4120. elems[i] = single_elem.value;
  4121. }
  4122. res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count);
  4123. return res;
  4124. }
  4125. switch (value.kind) {
  4126. case ExactValue_Invalid:
  4127. res.value = LLVMConstNull(lb_type(m, original_type));
  4128. return res;
  4129. case ExactValue_Bool:
  4130. res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false);
  4131. return res;
  4132. case ExactValue_String:
  4133. {
  4134. LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string);
  4135. lbValue res = {};
  4136. res.type = default_type(original_type);
  4137. if (is_type_cstring(res.type)) {
  4138. res.value = ptr;
  4139. } else {
  4140. if (value.value_string.len == 0) {
  4141. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  4142. }
  4143. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true);
  4144. LLVMValueRef values[2] = {ptr, str_len};
  4145. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4146. }
  4147. return res;
  4148. }
  4149. case ExactValue_Integer:
  4150. if (is_type_pointer(type)) {
  4151. LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer));
  4152. res.value = LLVMConstIntToPtr(i, lb_type(m, original_type));
  4153. } else {
  4154. unsigned len = cast(unsigned)value.value_integer.len;
  4155. if (len == 0) {
  4156. u64 word = 0;
  4157. res.value = LLVMConstNull(lb_type(m, original_type));
  4158. } else {
  4159. u64 *words = big_int_ptr(&value.value_integer);
  4160. if (is_type_different_to_arch_endianness(type)) {
  4161. // NOTE(bill): Swap byte order for different endianness
  4162. i64 sz = type_size_of(type);
  4163. isize byte_len = gb_size_of(u64)*len;
  4164. u8 *old_bytes = cast(u8 *)words;
  4165. // TODO(bill): Use a different allocator here for a temporary allocation
  4166. u8 *new_bytes = cast(u8 *)gb_alloc_align(permanent_allocator(), byte_len, gb_align_of(u64));
  4167. for (i64 i = 0; i < sz; i++) {
  4168. new_bytes[i] = old_bytes[sz-1-i];
  4169. }
  4170. words = cast(u64 *)new_bytes;
  4171. }
  4172. res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), len, words);
  4173. if (value.value_integer.neg) {
  4174. res.value = LLVMConstNeg(res.value);
  4175. }
  4176. }
  4177. }
  4178. return res;
  4179. case ExactValue_Float:
  4180. if (type_size_of(type) == 4) {
  4181. f32 f = cast(f32)value.value_float;
  4182. res.value = lb_const_f32(m, f, type);
  4183. return res;
  4184. }
  4185. if (is_type_different_to_arch_endianness(type)) {
  4186. u64 u = bit_cast<u64>(value.value_float);
  4187. u = gb_endian_swap64(u);
  4188. res.value = LLVMConstReal(lb_type(m, original_type), bit_cast<f64>(u));
  4189. } else {
  4190. res.value = LLVMConstReal(lb_type(m, original_type), value.value_float);
  4191. }
  4192. return res;
  4193. case ExactValue_Complex:
  4194. {
  4195. LLVMValueRef values[2] = {};
  4196. switch (8*type_size_of(type)) {
  4197. case 64:
  4198. values[0] = lb_const_f32(m, cast(f32)value.value_complex->real);
  4199. values[1] = lb_const_f32(m, cast(f32)value.value_complex->imag);
  4200. break;
  4201. case 128:
  4202. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->real);
  4203. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex->imag);
  4204. break;
  4205. }
  4206. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2);
  4207. return res;
  4208. }
  4209. break;
  4210. case ExactValue_Quaternion:
  4211. {
  4212. LLVMValueRef values[4] = {};
  4213. switch (8*type_size_of(type)) {
  4214. case 128:
  4215. // @QuaternionLayout
  4216. values[3] = lb_const_f32(m, cast(f32)value.value_quaternion->real);
  4217. values[0] = lb_const_f32(m, cast(f32)value.value_quaternion->imag);
  4218. values[1] = lb_const_f32(m, cast(f32)value.value_quaternion->jmag);
  4219. values[2] = lb_const_f32(m, cast(f32)value.value_quaternion->kmag);
  4220. break;
  4221. case 256:
  4222. // @QuaternionLayout
  4223. values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->real);
  4224. values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->imag);
  4225. values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->jmag);
  4226. values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion->kmag);
  4227. break;
  4228. }
  4229. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4);
  4230. return res;
  4231. }
  4232. break;
  4233. case ExactValue_Pointer:
  4234. res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type));
  4235. return res;
  4236. case ExactValue_Compound:
  4237. if (is_type_slice(type)) {
  4238. return lb_const_value(m, type, value, allow_local);
  4239. } else if (is_type_array(type)) {
  4240. ast_node(cl, CompoundLit, value.value_compound);
  4241. Type *elem_type = type->Array.elem;
  4242. isize elem_count = cl->elems.count;
  4243. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4244. return lb_const_nil(m, original_type);
  4245. }
  4246. if (cl->elems[0]->kind == Ast_FieldValue) {
  4247. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4248. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4249. isize value_index = 0;
  4250. for (i64 i = 0; i < type->Array.count; i++) {
  4251. bool found = false;
  4252. for (isize j = 0; j < elem_count; j++) {
  4253. Ast *elem = cl->elems[j];
  4254. ast_node(fv, FieldValue, elem);
  4255. if (is_ast_range(fv->field)) {
  4256. ast_node(ie, BinaryExpr, fv->field);
  4257. TypeAndValue lo_tav = ie->left->tav;
  4258. TypeAndValue hi_tav = ie->right->tav;
  4259. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4260. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4261. TokenKind op = ie->op.kind;
  4262. i64 lo = exact_value_to_i64(lo_tav.value);
  4263. i64 hi = exact_value_to_i64(hi_tav.value);
  4264. if (op == Token_Ellipsis) {
  4265. hi += 1;
  4266. }
  4267. if (lo == i) {
  4268. TypeAndValue tav = fv->value->tav;
  4269. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4270. for (i64 k = lo; k < hi; k++) {
  4271. values[value_index++] = val;
  4272. }
  4273. found = true;
  4274. i += (hi-lo-1);
  4275. break;
  4276. }
  4277. } else {
  4278. TypeAndValue index_tav = fv->field->tav;
  4279. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4280. i64 index = exact_value_to_i64(index_tav.value);
  4281. if (index == i) {
  4282. TypeAndValue tav = fv->value->tav;
  4283. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4284. values[value_index++] = val;
  4285. found = true;
  4286. break;
  4287. }
  4288. }
  4289. }
  4290. if (!found) {
  4291. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4292. }
  4293. }
  4294. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4295. return res;
  4296. } else {
  4297. GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count);
  4298. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->Array.count);
  4299. for (isize i = 0; i < elem_count; i++) {
  4300. TypeAndValue tav = cl->elems[i]->tav;
  4301. GB_ASSERT(tav.mode != Addressing_Invalid);
  4302. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4303. }
  4304. for (isize i = elem_count; i < type->Array.count; i++) {
  4305. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4306. }
  4307. res.value = lb_build_constant_array_values(m, type, elem_type, type->Array.count, values, allow_local);
  4308. return res;
  4309. }
  4310. } else if (is_type_enumerated_array(type)) {
  4311. ast_node(cl, CompoundLit, value.value_compound);
  4312. Type *elem_type = type->EnumeratedArray.elem;
  4313. isize elem_count = cl->elems.count;
  4314. if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) {
  4315. return lb_const_nil(m, original_type);
  4316. }
  4317. if (cl->elems[0]->kind == Ast_FieldValue) {
  4318. // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand
  4319. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4320. isize value_index = 0;
  4321. i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value);
  4322. i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value);
  4323. for (i64 i = total_lo; i <= total_hi; i++) {
  4324. bool found = false;
  4325. for (isize j = 0; j < elem_count; j++) {
  4326. Ast *elem = cl->elems[j];
  4327. ast_node(fv, FieldValue, elem);
  4328. if (is_ast_range(fv->field)) {
  4329. ast_node(ie, BinaryExpr, fv->field);
  4330. TypeAndValue lo_tav = ie->left->tav;
  4331. TypeAndValue hi_tav = ie->right->tav;
  4332. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  4333. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  4334. TokenKind op = ie->op.kind;
  4335. i64 lo = exact_value_to_i64(lo_tav.value);
  4336. i64 hi = exact_value_to_i64(hi_tav.value);
  4337. if (op == Token_Ellipsis) {
  4338. hi += 1;
  4339. }
  4340. if (lo == i) {
  4341. TypeAndValue tav = fv->value->tav;
  4342. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4343. for (i64 k = lo; k < hi; k++) {
  4344. values[value_index++] = val;
  4345. }
  4346. found = true;
  4347. i += (hi-lo-1);
  4348. break;
  4349. }
  4350. } else {
  4351. TypeAndValue index_tav = fv->field->tav;
  4352. GB_ASSERT(index_tav.mode == Addressing_Constant);
  4353. i64 index = exact_value_to_i64(index_tav.value);
  4354. if (index == i) {
  4355. TypeAndValue tav = fv->value->tav;
  4356. LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4357. values[value_index++] = val;
  4358. found = true;
  4359. break;
  4360. }
  4361. }
  4362. }
  4363. if (!found) {
  4364. values[value_index++] = LLVMConstNull(lb_type(m, elem_type));
  4365. }
  4366. }
  4367. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4368. return res;
  4369. } else {
  4370. GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count);
  4371. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, type->EnumeratedArray.count);
  4372. for (isize i = 0; i < elem_count; i++) {
  4373. TypeAndValue tav = cl->elems[i]->tav;
  4374. GB_ASSERT(tav.mode != Addressing_Invalid);
  4375. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4376. }
  4377. for (isize i = elem_count; i < type->EnumeratedArray.count; i++) {
  4378. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4379. }
  4380. res.value = lb_build_constant_array_values(m, type, elem_type, type->EnumeratedArray.count, values, allow_local);
  4381. return res;
  4382. }
  4383. } else if (is_type_simd_vector(type)) {
  4384. ast_node(cl, CompoundLit, value.value_compound);
  4385. Type *elem_type = type->SimdVector.elem;
  4386. isize elem_count = cl->elems.count;
  4387. if (elem_count == 0) {
  4388. return lb_const_nil(m, original_type);
  4389. }
  4390. GB_ASSERT(elem_type_can_be_constant(elem_type));
  4391. isize total_elem_count = type->SimdVector.count;
  4392. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, total_elem_count);
  4393. for (isize i = 0; i < elem_count; i++) {
  4394. TypeAndValue tav = cl->elems[i]->tav;
  4395. GB_ASSERT(tav.mode != Addressing_Invalid);
  4396. values[i] = lb_const_value(m, elem_type, tav.value, allow_local).value;
  4397. }
  4398. for (isize i = elem_count; i < type->SimdVector.count; i++) {
  4399. values[i] = LLVMConstNull(lb_type(m, elem_type));
  4400. }
  4401. res.value = LLVMConstVector(values, cast(unsigned)total_elem_count);
  4402. return res;
  4403. } else if (is_type_struct(type)) {
  4404. ast_node(cl, CompoundLit, value.value_compound);
  4405. if (cl->elems.count == 0) {
  4406. return lb_const_nil(m, original_type);
  4407. }
  4408. isize offset = 0;
  4409. if (type->Struct.custom_align > 0) {
  4410. offset = 1;
  4411. }
  4412. isize value_count = type->Struct.fields.count + offset;
  4413. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count);
  4414. bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count);
  4415. if (cl->elems.count > 0) {
  4416. if (cl->elems[0]->kind == Ast_FieldValue) {
  4417. isize elem_count = cl->elems.count;
  4418. for (isize i = 0; i < elem_count; i++) {
  4419. ast_node(fv, FieldValue, cl->elems[i]);
  4420. String name = fv->field->Ident.token.string;
  4421. TypeAndValue tav = fv->value->tav;
  4422. GB_ASSERT(tav.mode != Addressing_Invalid);
  4423. Selection sel = lookup_field(type, name, false);
  4424. Entity *f = type->Struct.fields[sel.index[0]];
  4425. if (elem_type_can_be_constant(f->type)) {
  4426. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value, allow_local).value;
  4427. visited[offset+f->Variable.field_index] = true;
  4428. }
  4429. }
  4430. } else {
  4431. for_array(i, cl->elems) {
  4432. Entity *f = type->Struct.fields[i];
  4433. TypeAndValue tav = cl->elems[i]->tav;
  4434. ExactValue val = {};
  4435. if (tav.mode != Addressing_Invalid) {
  4436. val = tav.value;
  4437. }
  4438. if (elem_type_can_be_constant(f->type)) {
  4439. values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val, allow_local).value;
  4440. visited[offset+f->Variable.field_index] = true;
  4441. }
  4442. }
  4443. }
  4444. }
  4445. for (isize i = 0; i < type->Struct.fields.count; i++) {
  4446. if (!visited[offset+i]) {
  4447. GB_ASSERT(values[offset+i] == nullptr);
  4448. values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value;
  4449. }
  4450. }
  4451. if (type->Struct.custom_align > 0) {
  4452. values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align));
  4453. }
  4454. res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count);
  4455. return res;
  4456. } else if (is_type_bit_set(type)) {
  4457. ast_node(cl, CompoundLit, value.value_compound);
  4458. if (cl->elems.count == 0) {
  4459. return lb_const_nil(m, original_type);
  4460. }
  4461. i64 sz = type_size_of(type);
  4462. if (sz == 0) {
  4463. return lb_const_nil(m, original_type);
  4464. }
  4465. u64 bits = 0;
  4466. for_array(i, cl->elems) {
  4467. Ast *e = cl->elems[i];
  4468. GB_ASSERT(e->kind != Ast_FieldValue);
  4469. TypeAndValue tav = e->tav;
  4470. if (tav.mode != Addressing_Constant) {
  4471. continue;
  4472. }
  4473. GB_ASSERT(tav.value.kind == ExactValue_Integer);
  4474. i64 v = big_int_to_i64(&tav.value.value_integer);
  4475. i64 lower = type->BitSet.lower;
  4476. bits |= 1ull<<cast(u64)(v-lower);
  4477. }
  4478. if (is_type_different_to_arch_endianness(type)) {
  4479. i64 size = type_size_of(type);
  4480. switch (size) {
  4481. case 2: bits = cast(u64)gb_endian_swap16(cast(u16)bits); break;
  4482. case 4: bits = cast(u64)gb_endian_swap32(cast(u32)bits); break;
  4483. case 8: bits = cast(u64)gb_endian_swap64(cast(u64)bits); break;
  4484. }
  4485. }
  4486. res.value = LLVMConstInt(lb_type(m, original_type), bits, false);
  4487. return res;
  4488. } else {
  4489. return lb_const_nil(m, original_type);
  4490. }
  4491. break;
  4492. case ExactValue_Procedure:
  4493. {
  4494. Ast *expr = value.value_procedure;
  4495. GB_ASSERT(expr != nullptr);
  4496. if (expr->kind == Ast_ProcLit) {
  4497. return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr);
  4498. }
  4499. }
  4500. break;
  4501. case ExactValue_Typeid:
  4502. return lb_typeid(m, value.value_typeid);
  4503. }
  4504. return lb_const_nil(m, original_type);
  4505. }
  4506. lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) {
  4507. lbModule *m = p->module;
  4508. LLVMValueRef fields[4] = {};
  4509. fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value;
  4510. fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value;
  4511. fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value;
  4512. fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value;
  4513. lbValue res = {};
  4514. res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, gb_count_of(fields));
  4515. res.type = t_source_code_location;
  4516. return res;
  4517. }
  4518. lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) {
  4519. String proc_name = {};
  4520. if (p->entity) {
  4521. proc_name = p->entity->token.string;
  4522. }
  4523. TokenPos pos = {};
  4524. if (node) {
  4525. pos = ast_token(node).pos;
  4526. }
  4527. return lb_emit_source_code_location(p, proc_name, pos);
  4528. }
  4529. lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  4530. switch (op) {
  4531. case Token_Add:
  4532. return x;
  4533. case Token_Not: // Boolean not
  4534. case Token_Xor: // Bitwise not
  4535. case Token_Sub: // Number negation
  4536. break;
  4537. case Token_Pointer:
  4538. GB_PANIC("This should be handled elsewhere");
  4539. break;
  4540. }
  4541. if (is_type_array(x.type)) {
  4542. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  4543. Type *tl = base_type(x.type);
  4544. lbValue val = lb_address_from_load_or_generate_local(p, x);
  4545. GB_ASSERT(is_type_array(type));
  4546. Type *elem_type = base_array_type(type);
  4547. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  4548. lbAddr res_addr = lb_add_local_generated(p, type, false);
  4549. lbValue res = lb_addr_get_ptr(p, res_addr);
  4550. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4551. i32 count = cast(i32)tl->Array.count;
  4552. if (inline_array_arith) {
  4553. // inline
  4554. for (i32 i = 0; i < count; i++) {
  4555. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  4556. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4557. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  4558. }
  4559. } else {
  4560. auto loop_data = lb_loop_start(p, count, t_i32);
  4561. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  4562. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  4563. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  4564. lb_loop_end(p, loop_data);
  4565. }
  4566. return lb_emit_load(p, res);
  4567. }
  4568. if (op == Token_Xor) {
  4569. lbValue cmp = {};
  4570. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  4571. cmp.type = x.type;
  4572. return lb_emit_conv(p, cmp, type);
  4573. }
  4574. if (op == Token_Not) {
  4575. lbValue cmp = {};
  4576. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  4577. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  4578. cmp.type = t_llvm_bool;
  4579. return lb_emit_conv(p, cmp, type);
  4580. }
  4581. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4582. Type *platform_type = integer_endian_type_to_platform_type(type);
  4583. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4584. lbValue res = {};
  4585. res.value = LLVMBuildNeg(p->builder, v.value, "");
  4586. res.type = platform_type;
  4587. return lb_emit_byte_swap(p, res, type);
  4588. }
  4589. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4590. Type *platform_type = integer_endian_type_to_platform_type(type);
  4591. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  4592. lbValue res = {};
  4593. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  4594. res.type = platform_type;
  4595. return lb_emit_byte_swap(p, res, type);
  4596. }
  4597. lbValue res = {};
  4598. switch (op) {
  4599. case Token_Not: // Boolean not
  4600. case Token_Xor: // Bitwise not
  4601. res.value = LLVMBuildNot(p->builder, x.value, "");
  4602. res.type = x.type;
  4603. return res;
  4604. case Token_Sub: // Number negation
  4605. if (is_type_integer(x.type)) {
  4606. res.value = LLVMBuildNeg(p->builder, x.value, "");
  4607. } else if (is_type_float(x.type)) {
  4608. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  4609. } else if (is_type_complex(x.type)) {
  4610. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4611. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4612. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4613. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4614. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4615. return lb_addr_load(p, addr);
  4616. } else if (is_type_quaternion(x.type)) {
  4617. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  4618. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  4619. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  4620. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  4621. lbAddr addr = lb_add_local_generated(p, x.type, false);
  4622. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP(p->builder, addr.addr.value, 0, ""));
  4623. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""));
  4624. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP(p->builder, addr.addr.value, 2, ""));
  4625. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP(p->builder, addr.addr.value, 3, ""));
  4626. return lb_addr_load(p, addr);
  4627. } else {
  4628. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  4629. }
  4630. res.type = x.type;
  4631. return res;
  4632. }
  4633. return res;
  4634. }
  4635. lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  4636. lbModule *m = p->module;
  4637. if (is_type_array(lhs.type) || is_type_array(rhs.type)) {
  4638. lhs = lb_emit_conv(p, lhs, type);
  4639. rhs = lb_emit_conv(p, rhs, type);
  4640. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  4641. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  4642. GB_ASSERT(is_type_array(type));
  4643. Type *elem_type = base_array_type(type);
  4644. lbAddr res = lb_add_local_generated(p, type, false);
  4645. i64 count = base_type(type)->Array.count;
  4646. bool inline_array_arith = type_size_of(type) <= build_context.max_align;
  4647. if (inline_array_arith) {
  4648. for (i64 i = 0; i < count; i++) {
  4649. lbValue a_ptr = lb_emit_array_epi(p, x, i);
  4650. lbValue b_ptr = lb_emit_array_epi(p, y, i);
  4651. lbValue dst_ptr = lb_emit_array_epi(p, res.addr, i);
  4652. lbValue a = lb_emit_load(p, a_ptr);
  4653. lbValue b = lb_emit_load(p, b_ptr);
  4654. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4655. lb_emit_store(p, dst_ptr, c);
  4656. }
  4657. } else {
  4658. auto loop_data = lb_loop_start(p, count, t_i32);
  4659. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  4660. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  4661. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  4662. lbValue a = lb_emit_load(p, a_ptr);
  4663. lbValue b = lb_emit_load(p, b_ptr);
  4664. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  4665. lb_emit_store(p, dst_ptr, c);
  4666. lb_loop_end(p, loop_data);
  4667. }
  4668. return lb_addr_load(p, res);
  4669. } else if (is_type_complex(type)) {
  4670. lhs = lb_emit_conv(p, lhs, type);
  4671. rhs = lb_emit_conv(p, rhs, type);
  4672. Type *ft = base_complex_elem_type(type);
  4673. if (op == Token_Quo) {
  4674. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4675. args[0] = lhs;
  4676. args[1] = rhs;
  4677. switch (type_size_of(ft)) {
  4678. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  4679. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  4680. default: GB_PANIC("Unknown float type"); break;
  4681. }
  4682. }
  4683. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4684. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  4685. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  4686. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  4687. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  4688. lbValue real = {};
  4689. lbValue imag = {};
  4690. switch (op) {
  4691. case Token_Add:
  4692. real = lb_emit_arith(p, Token_Add, a, c, ft);
  4693. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  4694. break;
  4695. case Token_Sub:
  4696. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  4697. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  4698. break;
  4699. case Token_Mul: {
  4700. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  4701. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  4702. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  4703. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  4704. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  4705. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  4706. break;
  4707. }
  4708. }
  4709. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  4710. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  4711. return lb_addr_load(p, res);
  4712. } else if (is_type_quaternion(type)) {
  4713. lhs = lb_emit_conv(p, lhs, type);
  4714. rhs = lb_emit_conv(p, rhs, type);
  4715. Type *ft = base_complex_elem_type(type);
  4716. if (op == Token_Add || op == Token_Sub) {
  4717. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  4718. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  4719. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  4720. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  4721. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  4722. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  4723. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  4724. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  4725. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  4726. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  4727. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  4728. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  4729. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  4730. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  4731. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  4732. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  4733. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  4734. return lb_addr_load(p, res);
  4735. } else if (op == Token_Mul) {
  4736. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4737. args[0] = lhs;
  4738. args[1] = rhs;
  4739. switch (8*type_size_of(ft)) {
  4740. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  4741. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  4742. default: GB_PANIC("Unknown float type"); break;
  4743. }
  4744. } else if (op == Token_Quo) {
  4745. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4746. args[0] = lhs;
  4747. args[1] = rhs;
  4748. switch (8*type_size_of(ft)) {
  4749. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  4750. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  4751. default: GB_PANIC("Unknown float type"); break;
  4752. }
  4753. }
  4754. }
  4755. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  4756. switch (op) {
  4757. case Token_AndNot:
  4758. case Token_And:
  4759. case Token_Or:
  4760. case Token_Xor:
  4761. goto handle_op;
  4762. }
  4763. Type *platform_type = integer_endian_type_to_platform_type(type);
  4764. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4765. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4766. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4767. return lb_emit_byte_swap(p, res, type);
  4768. }
  4769. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  4770. Type *platform_type = integer_endian_type_to_platform_type(type);
  4771. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  4772. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  4773. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  4774. return lb_emit_byte_swap(p, res, type);
  4775. }
  4776. handle_op:
  4777. lhs = lb_emit_conv(p, lhs, type);
  4778. rhs = lb_emit_conv(p, rhs, type);
  4779. lbValue res = {};
  4780. res.type = type;
  4781. switch (op) {
  4782. case Token_Add:
  4783. if (is_type_float(type)) {
  4784. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  4785. return res;
  4786. }
  4787. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  4788. return res;
  4789. case Token_Sub:
  4790. if (is_type_float(type)) {
  4791. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  4792. return res;
  4793. }
  4794. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  4795. return res;
  4796. case Token_Mul:
  4797. if (is_type_float(type)) {
  4798. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  4799. return res;
  4800. }
  4801. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  4802. return res;
  4803. case Token_Quo:
  4804. if (is_type_float(type)) {
  4805. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  4806. return res;
  4807. } else if (is_type_unsigned(type)) {
  4808. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  4809. return res;
  4810. }
  4811. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  4812. return res;
  4813. case Token_Mod:
  4814. if (is_type_float(type)) {
  4815. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  4816. return res;
  4817. } else if (is_type_unsigned(type)) {
  4818. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4819. return res;
  4820. }
  4821. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4822. return res;
  4823. case Token_ModMod:
  4824. if (is_type_unsigned(type)) {
  4825. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  4826. return res;
  4827. } else {
  4828. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  4829. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  4830. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  4831. res.value = c;
  4832. return res;
  4833. }
  4834. case Token_And:
  4835. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  4836. return res;
  4837. case Token_Or:
  4838. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  4839. return res;
  4840. case Token_Xor:
  4841. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  4842. return res;
  4843. case Token_Shl:
  4844. {
  4845. rhs = lb_emit_conv(p, rhs, lhs.type);
  4846. LLVMValueRef lhsval = lhs.value;
  4847. LLVMValueRef bits = rhs.value;
  4848. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  4849. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  4850. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  4851. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  4852. res.value = LLVMBuildSelect(p->builder, less_equal_width, res.value, zero, "");
  4853. return res;
  4854. }
  4855. case Token_Shr:
  4856. {
  4857. rhs = lb_emit_conv(p, rhs, lhs.type);
  4858. LLVMValueRef lhsval = lhs.value;
  4859. LLVMValueRef bits = rhs.value;
  4860. bool is_unsigned = is_type_unsigned(type);
  4861. LLVMValueRef max = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type) - 1, false);
  4862. LLVMValueRef less_equal_width = LLVMBuildICmp(p->builder, LLVMIntULE, bits, max, "");
  4863. bits = LLVMBuildSelect(p->builder, less_equal_width, bits, max, "");
  4864. if (is_unsigned) {
  4865. res.value = LLVMBuildLShr(p->builder, lhs.value, bits, "");
  4866. } else {
  4867. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  4868. }
  4869. return res;
  4870. }
  4871. case Token_AndNot:
  4872. {
  4873. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  4874. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  4875. return res;
  4876. }
  4877. break;
  4878. }
  4879. GB_PANIC("unhandled operator of lb_emit_arith");
  4880. return {};
  4881. }
  4882. lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  4883. ast_node(be, BinaryExpr, expr);
  4884. TypeAndValue tv = type_and_value_of_expr(expr);
  4885. switch (be->op.kind) {
  4886. case Token_Add:
  4887. case Token_Sub:
  4888. case Token_Mul:
  4889. case Token_Quo:
  4890. case Token_Mod:
  4891. case Token_ModMod:
  4892. case Token_And:
  4893. case Token_Or:
  4894. case Token_Xor:
  4895. case Token_AndNot:
  4896. case Token_Shl:
  4897. case Token_Shr: {
  4898. Type *type = default_type(tv.type);
  4899. lbValue left = lb_build_expr(p, be->left);
  4900. lbValue right = lb_build_expr(p, be->right);
  4901. return lb_emit_arith(p, be->op.kind, left, right, type);
  4902. }
  4903. case Token_CmpEq:
  4904. case Token_NotEq:
  4905. case Token_Lt:
  4906. case Token_LtEq:
  4907. case Token_Gt:
  4908. case Token_GtEq:
  4909. {
  4910. lbValue left = {};
  4911. lbValue right = {};
  4912. if (be->left->tav.mode == Addressing_Type) {
  4913. left = lb_typeid(p->module, be->left->tav.type);
  4914. }
  4915. if (be->right->tav.mode == Addressing_Type) {
  4916. right = lb_typeid(p->module, be->right->tav.type);
  4917. }
  4918. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  4919. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  4920. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  4921. Type *type = default_type(tv.type);
  4922. return lb_emit_conv(p, cmp, type);
  4923. }
  4924. case Token_CmpAnd:
  4925. case Token_CmpOr:
  4926. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  4927. case Token_in:
  4928. case Token_not_in:
  4929. {
  4930. lbValue left = lb_build_expr(p, be->left);
  4931. Type *type = default_type(tv.type);
  4932. lbValue right = lb_build_expr(p, be->right);
  4933. Type *rt = base_type(right.type);
  4934. switch (rt->kind) {
  4935. case Type_Map:
  4936. {
  4937. lbValue addr = lb_address_from_load_or_generate_local(p, right);
  4938. lbValue h = lb_gen_map_header(p, addr, rt);
  4939. lbValue key = lb_gen_map_hash(p, left, rt->Map.key);
  4940. auto args = array_make<lbValue>(permanent_allocator(), 2);
  4941. args[0] = h;
  4942. args[1] = key;
  4943. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  4944. if (be->op.kind == Token_in) {
  4945. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  4946. } else {
  4947. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  4948. }
  4949. }
  4950. break;
  4951. case Type_BitSet:
  4952. {
  4953. Type *key_type = rt->BitSet.elem;
  4954. GB_ASSERT(are_types_identical(left.type, key_type));
  4955. Type *it = bit_set_to_int(rt);
  4956. left = lb_emit_conv(p, left, it);
  4957. lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower));
  4958. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it);
  4959. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it);
  4960. bit = lb_emit_conv(p, bit, it);
  4961. lbValue old_value = lb_emit_transmute(p, right, it);
  4962. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  4963. if (be->op.kind == Token_in) {
  4964. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4965. } else {
  4966. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  4967. }
  4968. }
  4969. break;
  4970. default:
  4971. GB_PANIC("Invalid 'in' type");
  4972. }
  4973. break;
  4974. }
  4975. break;
  4976. default:
  4977. GB_PANIC("Invalid binary expression");
  4978. break;
  4979. }
  4980. return {};
  4981. }
  4982. String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) {
  4983. Type *prev_src = src;
  4984. // Type *prev_dst = dst;
  4985. src = base_type(type_deref(src));
  4986. // dst = base_type(type_deref(dst));
  4987. bool src_is_ptr = src != prev_src;
  4988. // bool dst_is_ptr = dst != prev_dst;
  4989. GB_ASSERT(is_type_struct(src) || is_type_union(src));
  4990. for_array(i, src->Struct.fields) {
  4991. Entity *f = src->Struct.fields[i];
  4992. if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) {
  4993. if (are_types_identical(dst, f->type)) {
  4994. return f->token.string;
  4995. }
  4996. if (src_is_ptr && is_type_pointer(dst)) {
  4997. if (are_types_identical(type_deref(dst), f->type)) {
  4998. return f->token.string;
  4999. }
  5000. }
  5001. if (is_type_struct(f->type)) {
  5002. String name = lookup_subtype_polymorphic_field(info, dst, f->type);
  5003. if (name.len > 0) {
  5004. return name;
  5005. }
  5006. }
  5007. }
  5008. }
  5009. return str_lit("");
  5010. }
  5011. lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) {
  5012. GB_ASSERT(is_type_pointer(value.type));
  5013. GB_ASSERT(is_type_pointer(t));
  5014. GB_ASSERT(lb_is_const(value));
  5015. lbValue res = {};
  5016. res.value = LLVMConstPointerCast(value.value, lb_type(m, t));
  5017. res.type = t;
  5018. return res;
  5019. }
  5020. lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  5021. lbModule *m = p->module;
  5022. t = reduce_tuple_to_single_type(t);
  5023. Type *src_type = value.type;
  5024. if (are_types_identical(t, src_type)) {
  5025. return value;
  5026. }
  5027. Type *src = core_type(src_type);
  5028. Type *dst = core_type(t);
  5029. GB_ASSERT(src != nullptr);
  5030. GB_ASSERT(dst != nullptr);
  5031. if (is_type_untyped_nil(src)) {
  5032. return lb_const_nil(m, t);
  5033. }
  5034. if (is_type_untyped_undef(src)) {
  5035. return lb_const_undef(m, t);
  5036. }
  5037. if (LLVMIsConstant(value.value)) {
  5038. if (is_type_any(dst)) {
  5039. Type *st = default_type(src_type);
  5040. lbAddr default_value = lb_add_local_generated(p, st, false);
  5041. lb_addr_store(p, default_value, value);
  5042. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  5043. lbValue id = lb_typeid(m, st);
  5044. lbAddr res = lb_add_local_generated(p, t, false);
  5045. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  5046. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  5047. lb_emit_store(p, a0, data);
  5048. lb_emit_store(p, a1, id);
  5049. return lb_addr_load(p, res);
  5050. } else if (dst->kind == Type_Basic) {
  5051. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  5052. String str = lb_get_const_string(m, value);
  5053. lbValue res = {};
  5054. res.type = t;
  5055. res.value = llvm_cstring(m, str);
  5056. return res;
  5057. }
  5058. // if (is_type_float(dst)) {
  5059. // return value;
  5060. // } else if (is_type_integer(dst)) {
  5061. // return value;
  5062. // }
  5063. // ExactValue ev = value->Constant.value;
  5064. // if (is_type_float(dst)) {
  5065. // ev = exact_value_to_float(ev);
  5066. // } else if (is_type_complex(dst)) {
  5067. // ev = exact_value_to_complex(ev);
  5068. // } else if (is_type_quaternion(dst)) {
  5069. // ev = exact_value_to_quaternion(ev);
  5070. // } else if (is_type_string(dst)) {
  5071. // // Handled elsewhere
  5072. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  5073. // } else if (is_type_integer(dst)) {
  5074. // ev = exact_value_to_integer(ev);
  5075. // } else if (is_type_pointer(dst)) {
  5076. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  5077. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  5078. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  5079. // }
  5080. // return lb_const_value(p->module, t, ev);
  5081. }
  5082. }
  5083. if (are_types_identical(src, dst)) {
  5084. if (!are_types_identical(src_type, t)) {
  5085. return lb_emit_transmute(p, value, t);
  5086. }
  5087. return value;
  5088. }
  5089. // bool <-> llvm bool
  5090. if (is_type_boolean(src) && dst == t_llvm_bool) {
  5091. lbValue res = {};
  5092. res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), "");
  5093. res.type = dst;
  5094. return res;
  5095. }
  5096. if (src == t_llvm_bool && is_type_boolean(dst)) {
  5097. lbValue res = {};
  5098. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  5099. res.type = dst;
  5100. return res;
  5101. }
  5102. // integer -> integer
  5103. if (is_type_integer(src) && is_type_integer(dst)) {
  5104. GB_ASSERT(src->kind == Type_Basic &&
  5105. dst->kind == Type_Basic);
  5106. i64 sz = type_size_of(default_type(src));
  5107. i64 dz = type_size_of(default_type(dst));
  5108. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  5109. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5110. value = lb_emit_byte_swap(p, value, platform_src_type);
  5111. }
  5112. LLVMOpcode op = LLVMTrunc;
  5113. if (dz < sz) {
  5114. op = LLVMTrunc;
  5115. } else if (dz == sz) {
  5116. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  5117. // NOTE(bill): Copy the value just for type correctness
  5118. op = LLVMBitCast;
  5119. } else if (dz > sz) {
  5120. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  5121. }
  5122. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  5123. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5124. lbValue res = {};
  5125. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  5126. res.type = t;
  5127. return lb_emit_byte_swap(p, res, t);
  5128. } else {
  5129. lbValue res = {};
  5130. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  5131. res.type = t;
  5132. return res;
  5133. }
  5134. }
  5135. // boolean -> boolean/integer
  5136. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  5137. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5138. lbValue res = {};
  5139. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, "");
  5140. res.type = t;
  5141. return res;
  5142. }
  5143. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  5144. return lb_emit_transmute(p, value, dst);
  5145. }
  5146. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  5147. return lb_emit_transmute(p, value, dst);
  5148. }
  5149. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  5150. return lb_emit_transmute(p, value, dst);
  5151. }
  5152. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  5153. return lb_emit_transmute(p, value, dst);
  5154. }
  5155. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  5156. lbValue c = lb_emit_conv(p, value, t_cstring);
  5157. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5158. args[0] = c;
  5159. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  5160. return lb_emit_conv(p, s, dst);
  5161. }
  5162. // integer -> boolean
  5163. if (is_type_integer(src) && is_type_boolean(dst)) {
  5164. lbValue res = {};
  5165. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  5166. res.type = t_llvm_bool;
  5167. return lb_emit_conv(p, res, t);
  5168. }
  5169. // float -> float
  5170. if (is_type_float(src) && is_type_float(dst)) {
  5171. i64 sz = type_size_of(src);
  5172. i64 dz = type_size_of(dst);
  5173. if (dz == sz) {
  5174. if (types_have_same_internal_endian(src, dst)) {
  5175. lbValue res = {};
  5176. res.type = t;
  5177. res.value = value.value;
  5178. return res;
  5179. } else {
  5180. return lb_emit_byte_swap(p, value, t);
  5181. }
  5182. }
  5183. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  5184. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  5185. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  5186. lbValue res = {};
  5187. res = lb_emit_conv(p, value, platform_src_type);
  5188. res = lb_emit_conv(p, res, platform_dst_type);
  5189. if (is_type_different_to_arch_endianness(dst)) {
  5190. res = lb_emit_byte_swap(p, res, t);
  5191. }
  5192. return lb_emit_conv(p, res, t);
  5193. }
  5194. lbValue res = {};
  5195. res.type = t;
  5196. if (dz >= sz) {
  5197. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  5198. } else {
  5199. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  5200. }
  5201. return res;
  5202. }
  5203. if (is_type_complex(src) && is_type_complex(dst)) {
  5204. Type *ft = base_complex_elem_type(dst);
  5205. lbAddr gen = lb_add_local_generated(p, dst, false);
  5206. lbValue gp = lb_addr_get_ptr(p, gen);
  5207. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5208. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5209. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5210. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  5211. return lb_addr_load(p, gen);
  5212. }
  5213. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  5214. // @QuaternionLayout
  5215. Type *ft = base_complex_elem_type(dst);
  5216. lbAddr gen = lb_add_local_generated(p, dst, false);
  5217. lbValue gp = lb_addr_get_ptr(p, gen);
  5218. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5219. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5220. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  5221. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  5222. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  5223. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  5224. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  5225. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  5226. return lb_addr_load(p, gen);
  5227. }
  5228. if (is_type_float(src) && is_type_complex(dst)) {
  5229. Type *ft = base_complex_elem_type(dst);
  5230. lbAddr gen = lb_add_local_generated(p, dst, true);
  5231. lbValue gp = lb_addr_get_ptr(p, gen);
  5232. lbValue real = lb_emit_conv(p, value, ft);
  5233. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  5234. return lb_addr_load(p, gen);
  5235. }
  5236. if (is_type_float(src) && is_type_quaternion(dst)) {
  5237. Type *ft = base_complex_elem_type(dst);
  5238. lbAddr gen = lb_add_local_generated(p, dst, true);
  5239. lbValue gp = lb_addr_get_ptr(p, gen);
  5240. lbValue real = lb_emit_conv(p, value, ft);
  5241. // @QuaternionLayout
  5242. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5243. return lb_addr_load(p, gen);
  5244. }
  5245. if (is_type_complex(src) && is_type_quaternion(dst)) {
  5246. Type *ft = base_complex_elem_type(dst);
  5247. lbAddr gen = lb_add_local_generated(p, dst, true);
  5248. lbValue gp = lb_addr_get_ptr(p, gen);
  5249. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  5250. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  5251. // @QuaternionLayout
  5252. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  5253. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  5254. return lb_addr_load(p, gen);
  5255. }
  5256. // float <-> integer
  5257. if (is_type_float(src) && is_type_integer(dst)) {
  5258. lbValue res = {};
  5259. res.type = t;
  5260. if (is_type_unsigned(dst)) {
  5261. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  5262. } else {
  5263. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  5264. }
  5265. return res;
  5266. }
  5267. if (is_type_integer(src) && is_type_float(dst)) {
  5268. lbValue res = {};
  5269. res.type = t;
  5270. if (is_type_unsigned(src)) {
  5271. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  5272. } else {
  5273. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  5274. }
  5275. return res;
  5276. }
  5277. // Pointer <-> uintptr
  5278. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5279. lbValue res = {};
  5280. res.type = t;
  5281. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5282. return res;
  5283. }
  5284. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5285. lbValue res = {};
  5286. res.type = t;
  5287. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5288. return res;
  5289. }
  5290. #if 1
  5291. if (is_type_union(dst)) {
  5292. for_array(i, dst->Union.variants) {
  5293. Type *vt = dst->Union.variants[i];
  5294. if (are_types_identical(vt, src_type)) {
  5295. lbAddr parent = lb_add_local_generated(p, t, true);
  5296. lb_emit_store_union_variant(p, parent.addr, value, vt);
  5297. return lb_addr_load(p, parent);
  5298. }
  5299. }
  5300. }
  5301. #endif
  5302. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  5303. // subtype polymorphism casting
  5304. if (check_is_assignable_to_using_subtype(src_type, t)) {
  5305. Type *st = type_deref(src_type);
  5306. Type *pst = st;
  5307. st = type_deref(st);
  5308. bool st_is_ptr = is_type_pointer(src_type);
  5309. st = base_type(st);
  5310. Type *dt = t;
  5311. bool dt_is_ptr = type_deref(dt) != dt;
  5312. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  5313. String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type);
  5314. if (field_name.len > 0) {
  5315. // NOTE(bill): It can be casted
  5316. Selection sel = lookup_field(st, field_name, false, true);
  5317. if (sel.entity != nullptr) {
  5318. if (st_is_ptr) {
  5319. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  5320. Type *rt = res.type;
  5321. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5322. res = lb_emit_load(p, res);
  5323. }
  5324. return res;
  5325. } else {
  5326. if (is_type_pointer(value.type)) {
  5327. Type *rt = value.type;
  5328. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  5329. value = lb_emit_load(p, value);
  5330. } else {
  5331. value = lb_emit_deep_field_gep(p, value, sel);
  5332. return lb_emit_load(p, value);
  5333. }
  5334. }
  5335. return lb_emit_deep_field_ev(p, value, sel);
  5336. }
  5337. } else {
  5338. GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name));
  5339. }
  5340. }
  5341. }
  5342. // Pointer <-> Pointer
  5343. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5344. lbValue res = {};
  5345. res.type = t;
  5346. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5347. return res;
  5348. }
  5349. // proc <-> proc
  5350. if (is_type_proc(src) && is_type_proc(dst)) {
  5351. lbValue res = {};
  5352. res.type = t;
  5353. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5354. return res;
  5355. }
  5356. // pointer -> proc
  5357. if (is_type_pointer(src) && is_type_proc(dst)) {
  5358. lbValue res = {};
  5359. res.type = t;
  5360. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5361. return res;
  5362. }
  5363. // proc -> pointer
  5364. if (is_type_proc(src) && is_type_pointer(dst)) {
  5365. lbValue res = {};
  5366. res.type = t;
  5367. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  5368. return res;
  5369. }
  5370. // []byte/[]u8 <-> string
  5371. if (is_type_u8_slice(src) && is_type_string(dst)) {
  5372. return lb_emit_transmute(p, value, t);
  5373. }
  5374. if (is_type_string(src) && is_type_u8_slice(dst)) {
  5375. return lb_emit_transmute(p, value, t);
  5376. }
  5377. if (is_type_array(dst)) {
  5378. Type *elem = dst->Array.elem;
  5379. lbValue e = lb_emit_conv(p, value, elem);
  5380. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  5381. lbAddr v = lb_add_local_generated(p, t, false);
  5382. isize index_count = cast(isize)dst->Array.count;
  5383. for (isize i = 0; i < index_count; i++) {
  5384. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  5385. lb_emit_store(p, elem, e);
  5386. }
  5387. return lb_addr_load(p, v);
  5388. }
  5389. if (is_type_any(dst)) {
  5390. if (is_type_untyped_nil(src)) {
  5391. return lb_const_nil(p->module, t);
  5392. }
  5393. if (is_type_untyped_undef(src)) {
  5394. return lb_const_undef(p->module, t);
  5395. }
  5396. lbAddr result = lb_add_local_generated(p, t, true);
  5397. Type *st = default_type(src_type);
  5398. lbValue data = lb_address_from_load_or_generate_local(p, value);
  5399. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  5400. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  5401. data = lb_emit_conv(p, data, t_rawptr);
  5402. lbValue id = lb_typeid(p->module, st);
  5403. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  5404. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  5405. lb_emit_store(p, any_data, data);
  5406. lb_emit_store(p, any_id, id);
  5407. return lb_addr_load(p, result);
  5408. }
  5409. i64 src_sz = type_size_of(src);
  5410. i64 dst_sz = type_size_of(dst);
  5411. if (src_sz == dst_sz) {
  5412. // bit_set <-> integer
  5413. if (is_type_integer(src) && is_type_bit_set(dst)) {
  5414. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  5415. res.type = dst;
  5416. return res;
  5417. }
  5418. if (is_type_bit_set(src) && is_type_integer(dst)) {
  5419. lbValue bs = value;
  5420. bs.type = bit_set_to_int(src);
  5421. return lb_emit_conv(p, bs, dst);
  5422. }
  5423. // typeid <-> integer
  5424. if (is_type_integer(src) && is_type_typeid(dst)) {
  5425. return lb_emit_transmute(p, value, dst);
  5426. }
  5427. if (is_type_typeid(src) && is_type_integer(dst)) {
  5428. return lb_emit_transmute(p, value, dst);
  5429. }
  5430. }
  5431. if (is_type_untyped(src)) {
  5432. if (is_type_string(src) && is_type_string(dst)) {
  5433. lbAddr result = lb_add_local_generated(p, t, false);
  5434. lb_addr_store(p, result, value);
  5435. return lb_addr_load(p, result);
  5436. }
  5437. }
  5438. gb_printf_err("%.*s\n", LIT(p->name));
  5439. gb_printf_err("lb_emit_conv: src -> dst\n");
  5440. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  5441. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  5442. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  5443. gb_printf_err("Not Identical %p != %p\n", src, dst);
  5444. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  5445. type_to_string(src_type), type_to_string(t),
  5446. LIT(p->name));
  5447. return {};
  5448. }
  5449. bool lb_is_type_aggregate(Type *t) {
  5450. t = base_type(t);
  5451. switch (t->kind) {
  5452. case Type_Basic:
  5453. switch (t->Basic.kind) {
  5454. case Basic_string:
  5455. case Basic_any:
  5456. return true;
  5457. // case Basic_complex32:
  5458. case Basic_complex64:
  5459. case Basic_complex128:
  5460. case Basic_quaternion128:
  5461. case Basic_quaternion256:
  5462. return true;
  5463. }
  5464. break;
  5465. case Type_Pointer:
  5466. return false;
  5467. case Type_Array:
  5468. case Type_Slice:
  5469. case Type_Struct:
  5470. case Type_Union:
  5471. case Type_Tuple:
  5472. case Type_DynamicArray:
  5473. case Type_Map:
  5474. case Type_SimdVector:
  5475. return true;
  5476. case Type_Named:
  5477. return lb_is_type_aggregate(t->Named.base);
  5478. }
  5479. return false;
  5480. }
  5481. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  5482. Type *src_type = value.type;
  5483. if (are_types_identical(t, src_type)) {
  5484. return value;
  5485. }
  5486. lbValue res = {};
  5487. res.type = t;
  5488. Type *src = base_type(src_type);
  5489. Type *dst = base_type(t);
  5490. lbModule *m = p->module;
  5491. i64 sz = type_size_of(src);
  5492. i64 dz = type_size_of(dst);
  5493. if (sz != dz) {
  5494. LLVMTypeRef s = lb_type(m, src);
  5495. LLVMTypeRef d = lb_type(m, dst);
  5496. i64 llvm_sz = lb_sizeof(s);
  5497. i64 llvm_dz = lb_sizeof(d);
  5498. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  5499. }
  5500. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  5501. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  5502. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  5503. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5504. return res;
  5505. }
  5506. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  5507. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5508. return res;
  5509. }
  5510. if (is_type_uintptr(src) && is_type_proc(dst)) {
  5511. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5512. return res;
  5513. }
  5514. if (is_type_proc(src) && is_type_uintptr(dst)) {
  5515. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5516. return res;
  5517. }
  5518. if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) {
  5519. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  5520. return res;
  5521. } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) {
  5522. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  5523. return res;
  5524. }
  5525. if (is_type_pointer(src) && is_type_pointer(dst)) {
  5526. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  5527. return res;
  5528. }
  5529. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  5530. lbValue s = lb_address_from_load_or_generate_local(p, value);
  5531. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  5532. return lb_emit_load(p, d);
  5533. }
  5534. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  5535. // GB_PANIC("lb_emit_transmute");
  5536. return res;
  5537. }
  5538. void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  5539. GB_ASSERT(addr.kind == lbAddr_Context);
  5540. GB_ASSERT(addr.ctx.sel.index.count == 0);
  5541. lbModule *m = p->module;
  5542. auto args = array_make<lbValue>(permanent_allocator(), 1);
  5543. args[0] = addr.addr;
  5544. lb_emit_runtime_call(p, "__init_context", args);
  5545. }
  5546. void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  5547. ctx.kind = lbAddr_Context;
  5548. lbContextData cd = {ctx, p->scope_index};
  5549. array_add(&p->context_stack, cd);
  5550. }
  5551. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  5552. if (p->context_stack.count > 0) {
  5553. return p->context_stack[p->context_stack.count-1].ctx;
  5554. }
  5555. Type *pt = base_type(p->type);
  5556. GB_ASSERT(pt->kind == Type_Proc);
  5557. {
  5558. lbAddr c = lb_add_local_generated(p, t_context, false);
  5559. c.kind = lbAddr_Context;
  5560. lb_emit_init_context(p, c);
  5561. lb_push_context_onto_stack(p, c);
  5562. return c;
  5563. }
  5564. }
  5565. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  5566. if (LLVMIsALoadInst(value.value)) {
  5567. lbValue res = {};
  5568. res.value = LLVMGetOperand(value.value, 0);
  5569. res.type = alloc_type_pointer(value.type);
  5570. return res;
  5571. }
  5572. GB_ASSERT(is_type_typed(value.type));
  5573. lbAddr res = lb_add_local_generated(p, value.type, false);
  5574. lb_addr_store(p, res, value);
  5575. return res.addr;
  5576. }
  5577. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  5578. if (LLVMIsALoadInst(value.value)) {
  5579. lbValue res = {};
  5580. res.value = LLVMGetOperand(value.value, 0);
  5581. res.type = alloc_type_pointer(value.type);
  5582. return res;
  5583. }
  5584. GB_PANIC("lb_address_from_load");
  5585. return {};
  5586. }
  5587. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  5588. i64 type_alignment = type_align_of(new_type);
  5589. if (alignment < type_alignment) {
  5590. alignment = type_alignment;
  5591. }
  5592. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  5593. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  5594. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  5595. lb_addr_store(p, ptr, val);
  5596. // ptr.kind = lbAddr_Context;
  5597. return ptr.addr;
  5598. }
  5599. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  5600. GB_ASSERT(is_type_pointer(s.type));
  5601. Type *t = base_type(type_deref(s.type));
  5602. Type *result_type = nullptr;
  5603. if (is_type_relative_pointer(t)) {
  5604. s = lb_addr_get_ptr(p, lb_addr(s));
  5605. }
  5606. if (is_type_struct(t)) {
  5607. result_type = get_struct_field_type(t, index);
  5608. } else if (is_type_union(t)) {
  5609. GB_ASSERT(index == -1);
  5610. return lb_emit_union_tag_ptr(p, s);
  5611. } else if (is_type_tuple(t)) {
  5612. GB_ASSERT(t->Tuple.variables.count > 0);
  5613. result_type = t->Tuple.variables[index]->type;
  5614. } else if (is_type_complex(t)) {
  5615. Type *ft = base_complex_elem_type(t);
  5616. switch (index) {
  5617. case 0: result_type = ft; break;
  5618. case 1: result_type = ft; break;
  5619. }
  5620. } else if (is_type_quaternion(t)) {
  5621. Type *ft = base_complex_elem_type(t);
  5622. switch (index) {
  5623. case 0: result_type = ft; break;
  5624. case 1: result_type = ft; break;
  5625. case 2: result_type = ft; break;
  5626. case 3: result_type = ft; break;
  5627. }
  5628. } else if (is_type_slice(t)) {
  5629. switch (index) {
  5630. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5631. case 1: result_type = t_int; break;
  5632. }
  5633. } else if (is_type_string(t)) {
  5634. switch (index) {
  5635. case 0: result_type = t_u8_ptr; break;
  5636. case 1: result_type = t_int; break;
  5637. }
  5638. } else if (is_type_any(t)) {
  5639. switch (index) {
  5640. case 0: result_type = t_rawptr; break;
  5641. case 1: result_type = t_typeid; break;
  5642. }
  5643. } else if (is_type_dynamic_array(t)) {
  5644. switch (index) {
  5645. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5646. case 1: result_type = t_int; break;
  5647. case 2: result_type = t_int; break;
  5648. case 3: result_type = t_allocator; break;
  5649. }
  5650. } else if (is_type_map(t)) {
  5651. init_map_internal_types(t);
  5652. Type *itp = alloc_type_pointer(t->Map.internal_type);
  5653. s = lb_emit_transmute(p, s, itp);
  5654. Type *gst = t->Map.internal_type;
  5655. GB_ASSERT(gst->kind == Type_Struct);
  5656. switch (index) {
  5657. case 0: result_type = get_struct_field_type(gst, 0); break;
  5658. case 1: result_type = get_struct_field_type(gst, 1); break;
  5659. }
  5660. } else if (is_type_array(t)) {
  5661. return lb_emit_array_epi(p, s, index);
  5662. } else if (is_type_relative_slice(t)) {
  5663. switch (index) {
  5664. case 0: result_type = t->RelativeSlice.base_integer; break;
  5665. case 1: result_type = t->RelativeSlice.base_integer; break;
  5666. }
  5667. } else {
  5668. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  5669. }
  5670. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  5671. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5672. index += 1;
  5673. }
  5674. if (lb_is_const(s)) {
  5675. lbModule *m = p->module;
  5676. lbValue res = {};
  5677. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  5678. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  5679. res.type = alloc_type_pointer(result_type);
  5680. return res;
  5681. } else {
  5682. lbValue res = {};
  5683. res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, "");
  5684. res.type = alloc_type_pointer(result_type);
  5685. return res;
  5686. }
  5687. }
  5688. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  5689. if (LLVMIsALoadInst(s.value)) {
  5690. lbValue res = {};
  5691. res.value = LLVMGetOperand(s.value, 0);
  5692. res.type = alloc_type_pointer(s.type);
  5693. lbValue ptr = lb_emit_struct_ep(p, res, index);
  5694. return lb_emit_load(p, ptr);
  5695. }
  5696. Type *t = base_type(s.type);
  5697. Type *result_type = nullptr;
  5698. switch (t->kind) {
  5699. case Type_Basic:
  5700. switch (t->Basic.kind) {
  5701. case Basic_string:
  5702. switch (index) {
  5703. case 0: result_type = t_u8_ptr; break;
  5704. case 1: result_type = t_int; break;
  5705. }
  5706. break;
  5707. case Basic_any:
  5708. switch (index) {
  5709. case 0: result_type = t_rawptr; break;
  5710. case 1: result_type = t_typeid; break;
  5711. }
  5712. break;
  5713. case Basic_complex64: case Basic_complex128:
  5714. {
  5715. Type *ft = base_complex_elem_type(t);
  5716. switch (index) {
  5717. case 0: result_type = ft; break;
  5718. case 1: result_type = ft; break;
  5719. }
  5720. break;
  5721. }
  5722. case Basic_quaternion128: case Basic_quaternion256:
  5723. {
  5724. Type *ft = base_complex_elem_type(t);
  5725. switch (index) {
  5726. case 0: result_type = ft; break;
  5727. case 1: result_type = ft; break;
  5728. case 2: result_type = ft; break;
  5729. case 3: result_type = ft; break;
  5730. }
  5731. break;
  5732. }
  5733. }
  5734. break;
  5735. case Type_Struct:
  5736. result_type = get_struct_field_type(t, index);
  5737. break;
  5738. case Type_Union:
  5739. GB_ASSERT(index == -1);
  5740. // return lb_emit_union_tag_value(p, s);
  5741. GB_PANIC("lb_emit_union_tag_value");
  5742. case Type_Tuple:
  5743. GB_ASSERT(t->Tuple.variables.count > 0);
  5744. result_type = t->Tuple.variables[index]->type;
  5745. if (t->Tuple.variables.count == 1) {
  5746. return s;
  5747. }
  5748. break;
  5749. case Type_Slice:
  5750. switch (index) {
  5751. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  5752. case 1: result_type = t_int; break;
  5753. }
  5754. break;
  5755. case Type_DynamicArray:
  5756. switch (index) {
  5757. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  5758. case 1: result_type = t_int; break;
  5759. case 2: result_type = t_int; break;
  5760. case 3: result_type = t_allocator; break;
  5761. }
  5762. break;
  5763. case Type_Map:
  5764. {
  5765. init_map_internal_types(t);
  5766. Type *gst = t->Map.generated_struct_type;
  5767. switch (index) {
  5768. case 0: result_type = get_struct_field_type(gst, 0); break;
  5769. case 1: result_type = get_struct_field_type(gst, 1); break;
  5770. }
  5771. }
  5772. break;
  5773. case Type_Array:
  5774. result_type = t->Array.elem;
  5775. break;
  5776. default:
  5777. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  5778. break;
  5779. }
  5780. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  5781. if (t->kind == Type_Struct && t->Struct.custom_align != 0) {
  5782. index += 1;
  5783. }
  5784. lbValue res = {};
  5785. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  5786. res.type = result_type;
  5787. return res;
  5788. }
  5789. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  5790. GB_ASSERT(sel.index.count > 0);
  5791. Type *type = type_deref(e.type);
  5792. for_array(i, sel.index) {
  5793. i32 index = cast(i32)sel.index[i];
  5794. if (is_type_pointer(type)) {
  5795. type = type_deref(type);
  5796. e = lb_emit_load(p, e);
  5797. }
  5798. type = core_type(type);
  5799. if (is_type_quaternion(type)) {
  5800. e = lb_emit_struct_ep(p, e, index);
  5801. } else if (is_type_raw_union(type)) {
  5802. type = get_struct_field_type(type, index);
  5803. GB_ASSERT(is_type_pointer(e.type));
  5804. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  5805. } else if (is_type_struct(type)) {
  5806. type = get_struct_field_type(type, index);
  5807. e = lb_emit_struct_ep(p, e, index);
  5808. } else if (type->kind == Type_Union) {
  5809. GB_ASSERT(index == -1);
  5810. type = t_type_info_ptr;
  5811. e = lb_emit_struct_ep(p, e, index);
  5812. } else if (type->kind == Type_Tuple) {
  5813. type = type->Tuple.variables[index]->type;
  5814. e = lb_emit_struct_ep(p, e, index);
  5815. } else if (type->kind == Type_Basic) {
  5816. switch (type->Basic.kind) {
  5817. case Basic_any: {
  5818. if (index == 0) {
  5819. type = t_rawptr;
  5820. } else if (index == 1) {
  5821. type = t_type_info_ptr;
  5822. }
  5823. e = lb_emit_struct_ep(p, e, index);
  5824. break;
  5825. }
  5826. case Basic_string:
  5827. e = lb_emit_struct_ep(p, e, index);
  5828. break;
  5829. default:
  5830. GB_PANIC("un-gep-able type %s", type_to_string(type));
  5831. break;
  5832. }
  5833. } else if (type->kind == Type_Slice) {
  5834. e = lb_emit_struct_ep(p, e, index);
  5835. } else if (type->kind == Type_DynamicArray) {
  5836. e = lb_emit_struct_ep(p, e, index);
  5837. } else if (type->kind == Type_Array) {
  5838. e = lb_emit_array_epi(p, e, index);
  5839. } else if (type->kind == Type_Map) {
  5840. e = lb_emit_struct_ep(p, e, index);
  5841. } else if (type->kind == Type_RelativePointer) {
  5842. e = lb_emit_struct_ep(p, e, index);
  5843. } else {
  5844. GB_PANIC("un-gep-able type %s", type_to_string(type));
  5845. }
  5846. }
  5847. return e;
  5848. }
  5849. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  5850. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  5851. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  5852. return lb_emit_load(p, res);
  5853. }
  5854. void lb_build_defer_stmt(lbProcedure *p, lbDefer d) {
  5855. // NOTE(bill): The prev block may defer injection before it's terminator
  5856. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  5857. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  5858. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  5859. return;
  5860. }
  5861. isize prev_context_stack_count = p->context_stack.count;
  5862. defer (p->context_stack.count = prev_context_stack_count);
  5863. p->context_stack.count = d.context_stack_count;
  5864. lbBlock *b = lb_create_block(p, "defer");
  5865. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  5866. lb_emit_jump(p, b);
  5867. }
  5868. lb_start_block(p, b);
  5869. if (d.kind == lbDefer_Node) {
  5870. lb_build_stmt(p, d.stmt);
  5871. } else if (d.kind == lbDefer_Instr) {
  5872. // NOTE(bill): Need to make a new copy
  5873. LLVMValueRef instr = LLVMInstructionClone(d.instr.value);
  5874. LLVMInsertIntoBuilder(p->builder, instr);
  5875. } else if (d.kind == lbDefer_Proc) {
  5876. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  5877. }
  5878. }
  5879. void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  5880. isize count = p->defer_stmts.count;
  5881. isize i = count;
  5882. while (i --> 0) {
  5883. lbDefer d = p->defer_stmts[i];
  5884. isize prev_context_stack_count = p->context_stack.count;
  5885. defer (p->context_stack.count = prev_context_stack_count);
  5886. p->context_stack.count = d.context_stack_count;
  5887. if (kind == lbDeferExit_Default) {
  5888. if (p->scope_index == d.scope_index &&
  5889. d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1?
  5890. lb_build_defer_stmt(p, d);
  5891. array_pop(&p->defer_stmts);
  5892. continue;
  5893. } else {
  5894. break;
  5895. }
  5896. } else if (kind == lbDeferExit_Return) {
  5897. lb_build_defer_stmt(p, d);
  5898. } else if (kind == lbDeferExit_Branch) {
  5899. GB_ASSERT(block != nullptr);
  5900. isize lower_limit = block->scope_index;
  5901. if (lower_limit < d.scope_index) {
  5902. lb_build_defer_stmt(p, d);
  5903. }
  5904. }
  5905. }
  5906. }
  5907. lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  5908. lbDefer d = {lbDefer_Node};
  5909. d.scope_index = scope_index;
  5910. d.context_stack_count = p->context_stack.count;
  5911. d.block = p->curr_block;
  5912. d.stmt = stmt;
  5913. array_add(&p->defer_stmts, d);
  5914. return d;
  5915. }
  5916. lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  5917. lbDefer d = {lbDefer_Proc};
  5918. d.scope_index = p->scope_index;
  5919. d.block = p->curr_block;
  5920. d.proc.deferred = deferred;
  5921. d.proc.result_as_args = result_as_args;
  5922. array_add(&p->defer_stmts, d);
  5923. return d;
  5924. }
  5925. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  5926. Array<lbValue> array = {};
  5927. Type *t = base_type(value.type);
  5928. if (t == nullptr) {
  5929. // Do nothing
  5930. } else if (is_type_tuple(t)) {
  5931. GB_ASSERT(t->kind == Type_Tuple);
  5932. auto *rt = &t->Tuple;
  5933. if (rt->variables.count > 0) {
  5934. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  5935. for_array(i, rt->variables) {
  5936. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  5937. array[i] = elem;
  5938. }
  5939. }
  5940. } else {
  5941. array = array_make<lbValue>(permanent_allocator(), 1);
  5942. array[0] = value;
  5943. }
  5944. return array;
  5945. }
  5946. 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) {
  5947. unsigned arg_count = cast(unsigned)processed_args.count;
  5948. if (return_ptr.value != nullptr) {
  5949. arg_count += 1;
  5950. }
  5951. if (context_ptr.addr.value != nullptr) {
  5952. arg_count += 1;
  5953. }
  5954. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  5955. isize arg_index = 0;
  5956. if (return_ptr.value != nullptr) {
  5957. args[arg_index++] = return_ptr.value;
  5958. }
  5959. for_array(i, processed_args) {
  5960. lbValue arg = processed_args[i];
  5961. args[arg_index++] = arg.value;
  5962. }
  5963. if (context_ptr.addr.value != nullptr) {
  5964. LLVMValueRef cp = context_ptr.addr.value;
  5965. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  5966. args[arg_index++] = cp;
  5967. }
  5968. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  5969. GB_ASSERT(curr_block != p->decl_block->block);
  5970. {
  5971. LLVMTypeRef ftp = lb_type(p->module, value.type);
  5972. LLVMTypeRef ft = LLVMGetElementType(ftp);
  5973. LLVMValueRef fn = value.value;
  5974. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  5975. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  5976. }
  5977. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  5978. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  5979. LLVMValueRef ret = LLVMBuildCall2(p->builder, ft, fn, args, arg_count, "");;
  5980. lbValue res = {};
  5981. res.value = ret;
  5982. res.type = abi_rt;
  5983. return res;
  5984. }
  5985. }
  5986. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  5987. String name = make_string_c(c_name);
  5988. AstPackage *pkg = p->module->info->runtime_package;
  5989. Entity *e = scope_lookup_current(pkg->scope, name);
  5990. lbValue *found = nullptr;
  5991. if (p->module != e->code_gen_module) {
  5992. gb_mutex_lock(&p->module->mutex);
  5993. }
  5994. GB_ASSERT(e->code_gen_module != nullptr);
  5995. found = map_get(&e->code_gen_module->values, hash_entity(e));
  5996. if (p->module != e->code_gen_module) {
  5997. gb_mutex_unlock(&p->module->mutex);
  5998. }
  5999. GB_ASSERT_MSG(found != nullptr, "%s", c_name);
  6000. return lb_emit_call(p, *found, args);
  6001. }
  6002. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_return_ptr_hint) {
  6003. lbModule *m = p->module;
  6004. Type *pt = base_type(value.type);
  6005. GB_ASSERT(pt->kind == Type_Proc);
  6006. Type *results = pt->Proc.results;
  6007. if (p->entity != nullptr) {
  6008. if (p->entity->flags & EntityFlag_Disabled) {
  6009. return {};
  6010. }
  6011. }
  6012. lbAddr context_ptr = {};
  6013. if (pt->Proc.calling_convention == ProcCC_Odin) {
  6014. context_ptr = lb_find_or_generate_context_ptr(p);
  6015. }
  6016. defer (if (pt->Proc.diverging) {
  6017. LLVMBuildUnreachable(p->builder);
  6018. });
  6019. set_procedure_abi_types(pt);
  6020. bool is_c_vararg = pt->Proc.c_vararg;
  6021. isize param_count = pt->Proc.param_count;
  6022. if (is_c_vararg) {
  6023. GB_ASSERT(param_count-1 <= args.count);
  6024. param_count -= 1;
  6025. } else {
  6026. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  6027. }
  6028. lbValue result = {};
  6029. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  6030. {
  6031. lbFunctionType **ft_found = nullptr;
  6032. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6033. if (!ft_found) {
  6034. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  6035. ft_found = map_get(&m->function_type_map, hash_type(pt));
  6036. }
  6037. GB_ASSERT(ft_found != nullptr);
  6038. lbFunctionType *ft = *ft_found;
  6039. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  6040. unsigned param_index = 0;
  6041. for (isize i = 0; i < param_count; i++) {
  6042. Entity *e = pt->Proc.params->Tuple.variables[i];
  6043. if (e->kind != Entity_Variable) {
  6044. continue;
  6045. }
  6046. GB_ASSERT(e->flags & EntityFlag_Param);
  6047. Type *original_type = e->type;
  6048. lbArgType *arg = &ft->args[param_index];
  6049. if (arg->kind == lbArg_Ignore) {
  6050. continue;
  6051. }
  6052. lbValue x = lb_emit_conv(p, args[i], original_type);
  6053. LLVMTypeRef xt = lb_type(p->module, x.type);
  6054. if (arg->kind == lbArg_Direct) {
  6055. LLVMTypeRef abi_type = arg->cast_type;
  6056. if (!abi_type) {
  6057. abi_type = arg->type;
  6058. }
  6059. if (xt == abi_type) {
  6060. array_add(&processed_args, x);
  6061. } else {
  6062. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  6063. array_add(&processed_args, x);
  6064. }
  6065. } else if (arg->kind == lbArg_Indirect) {
  6066. lbValue ptr = {};
  6067. if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  6068. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  6069. // i.e. `T const &` in C++
  6070. ptr = lb_address_from_load_or_generate_local(p, x);
  6071. } else {
  6072. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  6073. }
  6074. array_add(&processed_args, ptr);
  6075. }
  6076. param_index += 1;
  6077. }
  6078. if (inlining == ProcInlining_none) {
  6079. inlining = p->inlining;
  6080. }
  6081. Type *rt = reduce_tuple_to_single_type(results);
  6082. if (return_by_pointer) {
  6083. lbValue return_ptr = {};
  6084. if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) {
  6085. if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) {
  6086. return_ptr = p->return_ptr_hint_value;
  6087. p->return_ptr_hint_used = true;
  6088. }
  6089. }
  6090. if (return_ptr.value == nullptr) {
  6091. lbAddr r = lb_add_local_generated(p, rt, true);
  6092. return_ptr = r.addr;
  6093. }
  6094. GB_ASSERT(is_type_pointer(return_ptr.type));
  6095. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  6096. result = lb_emit_load(p, return_ptr);
  6097. } else if (rt != nullptr) {
  6098. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  6099. if (ft->ret.cast_type) {
  6100. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  6101. }
  6102. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  6103. result.type = rt;
  6104. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  6105. result.type = t_llvm_bool;
  6106. }
  6107. if (!is_type_tuple(rt)) {
  6108. result = lb_emit_conv(p, result, rt);
  6109. }
  6110. } else {
  6111. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  6112. }
  6113. }
  6114. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  6115. if (found != nullptr) {
  6116. Entity *e = *found;
  6117. if (e != nullptr && entity_has_deferred_procedure(e)) {
  6118. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  6119. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  6120. lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity));
  6121. GB_ASSERT(deferred_found != nullptr);
  6122. lbValue deferred = *deferred_found;
  6123. auto in_args = args;
  6124. Array<lbValue> result_as_args = {};
  6125. switch (kind) {
  6126. case DeferredProcedure_none:
  6127. break;
  6128. case DeferredProcedure_in:
  6129. result_as_args = in_args;
  6130. break;
  6131. case DeferredProcedure_out:
  6132. result_as_args = lb_value_to_array(p, result);
  6133. break;
  6134. case DeferredProcedure_in_out:
  6135. {
  6136. auto out_args = lb_value_to_array(p, result);
  6137. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  6138. array_copy(&result_as_args, in_args, 0);
  6139. array_copy(&result_as_args, out_args, in_args.count);
  6140. }
  6141. break;
  6142. }
  6143. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  6144. }
  6145. }
  6146. return result;
  6147. }
  6148. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  6149. Type *t = s.type;
  6150. GB_ASSERT(is_type_pointer(t));
  6151. Type *st = base_type(type_deref(t));
  6152. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6153. GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type));
  6154. LLVMValueRef indices[2] = {};
  6155. indices[0] = llvm_zero(p->module);
  6156. indices[1] = lb_emit_conv(p, index, t_int).value;
  6157. Type *ptr = base_array_type(st);
  6158. lbValue res = {};
  6159. res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, "");
  6160. res.type = alloc_type_pointer(ptr);
  6161. return res;
  6162. }
  6163. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  6164. Type *t = s.type;
  6165. GB_ASSERT(is_type_pointer(t));
  6166. Type *st = base_type(type_deref(t));
  6167. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st));
  6168. GB_ASSERT(0 <= index);
  6169. Type *ptr = base_array_type(st);
  6170. LLVMValueRef indices[2] = {
  6171. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  6172. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false),
  6173. };
  6174. lbValue res = {};
  6175. if (lb_is_const(s)) {
  6176. res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices));
  6177. } else {
  6178. res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), "");
  6179. }
  6180. res.type = alloc_type_pointer(ptr);
  6181. return res;
  6182. }
  6183. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  6184. LLVMValueRef indices[1] = {index.value};
  6185. lbValue res = {};
  6186. res.type = ptr.type;
  6187. if (lb_is_const(ptr) && lb_is_const(index)) {
  6188. res.value = LLVMConstGEP(ptr.value, indices, 1);
  6189. } else {
  6190. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, "");
  6191. }
  6192. return res;
  6193. }
  6194. LLVMValueRef llvm_const_slice(lbValue data, lbValue len) {
  6195. GB_ASSERT(is_type_pointer(data.type));
  6196. GB_ASSERT(are_types_identical(len.type, t_int));
  6197. LLVMValueRef vals[2] = {
  6198. data.value,
  6199. len.value,
  6200. };
  6201. return LLVMConstStruct(vals, gb_count_of(vals), false);
  6202. }
  6203. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  6204. Type *t = lb_addr_type(slice);
  6205. GB_ASSERT(is_type_slice(t));
  6206. lbValue ptr = lb_addr_get_ptr(p, slice);
  6207. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6208. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6209. }
  6210. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  6211. Type *t = lb_addr_type(string);
  6212. GB_ASSERT(is_type_string(t));
  6213. lbValue ptr = lb_addr_get_ptr(p, string);
  6214. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  6215. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  6216. }
  6217. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  6218. Type *t = base_type(string.type);
  6219. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  6220. return lb_emit_struct_ev(p, string, 0);
  6221. }
  6222. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  6223. Type *t = base_type(string.type);
  6224. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  6225. return lb_emit_struct_ev(p, string, 1);
  6226. }
  6227. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  6228. GB_ASSERT(is_type_cstring(value.type));
  6229. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6230. args[0] = lb_emit_conv(p, value, t_cstring);
  6231. return lb_emit_runtime_call(p, "cstring_len", args);
  6232. }
  6233. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  6234. Type *t = type_deref(array_ptr.type);
  6235. GB_ASSERT(is_type_array(t));
  6236. return lb_emit_struct_ep(p, array_ptr, 0);
  6237. }
  6238. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  6239. GB_ASSERT(is_type_slice(slice.type));
  6240. return lb_emit_struct_ev(p, slice, 0);
  6241. }
  6242. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  6243. GB_ASSERT(is_type_slice(slice.type));
  6244. return lb_emit_struct_ev(p, slice, 1);
  6245. }
  6246. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  6247. GB_ASSERT(is_type_dynamic_array(da.type));
  6248. return lb_emit_struct_ev(p, da, 0);
  6249. }
  6250. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  6251. GB_ASSERT(is_type_dynamic_array(da.type));
  6252. return lb_emit_struct_ev(p, da, 1);
  6253. }
  6254. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  6255. GB_ASSERT(is_type_dynamic_array(da.type));
  6256. return lb_emit_struct_ev(p, da, 2);
  6257. }
  6258. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  6259. GB_ASSERT(is_type_dynamic_array(da.type));
  6260. return lb_emit_struct_ev(p, da, 3);
  6261. }
  6262. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  6263. Type *t = base_type(value.type);
  6264. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6265. init_map_internal_types(t);
  6266. Type *gst = t->Map.generated_struct_type;
  6267. i32 index = 1;
  6268. lbValue entries = lb_emit_struct_ev(p, value, index);
  6269. return entries;
  6270. }
  6271. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  6272. Type *t = base_type(type_deref(value.type));
  6273. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  6274. init_map_internal_types(t);
  6275. Type *gst = t->Map.generated_struct_type;
  6276. i32 index = 1;
  6277. lbValue entries = lb_emit_struct_ep(p, value, index);
  6278. return entries;
  6279. }
  6280. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  6281. lbValue entries = lb_map_entries(p, value);
  6282. return lb_dynamic_array_len(p, entries);
  6283. }
  6284. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  6285. lbValue entries = lb_map_entries(p, value);
  6286. return lb_dynamic_array_cap(p, entries);
  6287. }
  6288. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  6289. Type *t = base_type(value.type);
  6290. bool is_ptr = false;
  6291. if (is_type_pointer(t)) {
  6292. is_ptr = true;
  6293. t = base_type(type_deref(t));
  6294. }
  6295. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6296. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6297. }
  6298. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  6299. t->Struct.soa_kind == StructSoa_Dynamic);
  6300. isize n = 0;
  6301. Type *elem = base_type(t->Struct.soa_elem);
  6302. if (elem->kind == Type_Struct) {
  6303. n = elem->Struct.fields.count;
  6304. } else if (elem->kind == Type_Array) {
  6305. n = elem->Array.count;
  6306. } else {
  6307. GB_PANIC("Unreachable");
  6308. }
  6309. if (is_ptr) {
  6310. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6311. return lb_emit_load(p, v);
  6312. }
  6313. return lb_emit_struct_ev(p, value, cast(i32)n);
  6314. }
  6315. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  6316. Type *t = base_type(value.type);
  6317. bool is_ptr = false;
  6318. if (is_type_pointer(t)) {
  6319. is_ptr = true;
  6320. t = base_type(type_deref(t));
  6321. }
  6322. if (t->Struct.soa_kind == StructSoa_Fixed) {
  6323. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  6324. }
  6325. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  6326. isize n = 0;
  6327. Type *elem = base_type(t->Struct.soa_elem);
  6328. if (elem->kind == Type_Struct) {
  6329. n = elem->Struct.fields.count+1;
  6330. } else if (elem->kind == Type_Array) {
  6331. n = elem->Array.count+1;
  6332. } else {
  6333. GB_PANIC("Unreachable");
  6334. }
  6335. if (is_ptr) {
  6336. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  6337. return lb_emit_load(p, v);
  6338. }
  6339. return lb_emit_struct_ev(p, value, cast(i32)n);
  6340. }
  6341. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  6342. ast_node(ce, CallExpr, expr);
  6343. switch (id) {
  6344. case BuiltinProc_DIRECTIVE: {
  6345. ast_node(bd, BasicDirective, ce->proc);
  6346. String name = bd->name;
  6347. GB_ASSERT(name == "location");
  6348. String procedure = p->entity->token.string;
  6349. TokenPos pos = ast_token(ce->proc).pos;
  6350. if (ce->args.count > 0) {
  6351. Ast *ident = unselector_expr(ce->args[0]);
  6352. GB_ASSERT(ident->kind == Ast_Ident);
  6353. Entity *e = entity_of_node(ident);
  6354. GB_ASSERT(e != nullptr);
  6355. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  6356. procedure = e->parent_proc_decl->entity->token.string;
  6357. } else {
  6358. procedure = str_lit("");
  6359. }
  6360. pos = e->token.pos;
  6361. }
  6362. return lb_emit_source_code_location(p, procedure, pos);
  6363. }
  6364. case BuiltinProc_type_info_of: {
  6365. Ast *arg = ce->args[0];
  6366. TypeAndValue tav = type_and_value_of_expr(arg);
  6367. if (tav.mode == Addressing_Type) {
  6368. Type *t = default_type(type_of_expr(arg));
  6369. return lb_type_info(p->module, t);
  6370. }
  6371. GB_ASSERT(is_type_typeid(tav.type));
  6372. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6373. args[0] = lb_build_expr(p, arg);
  6374. return lb_emit_runtime_call(p, "__type_info_of", args);
  6375. }
  6376. case BuiltinProc_typeid_of: {
  6377. Ast *arg = ce->args[0];
  6378. TypeAndValue tav = type_and_value_of_expr(arg);
  6379. GB_ASSERT(tav.mode == Addressing_Type);
  6380. Type *t = default_type(type_of_expr(arg));
  6381. return lb_typeid(p->module, t);
  6382. }
  6383. case BuiltinProc_len: {
  6384. lbValue v = lb_build_expr(p, ce->args[0]);
  6385. Type *t = base_type(v.type);
  6386. if (is_type_pointer(t)) {
  6387. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6388. v = lb_emit_load(p, v);
  6389. t = type_deref(t);
  6390. }
  6391. if (is_type_cstring(t)) {
  6392. return lb_cstring_len(p, v);
  6393. } else if (is_type_string(t)) {
  6394. return lb_string_len(p, v);
  6395. } else if (is_type_array(t)) {
  6396. GB_PANIC("Array lengths are constant");
  6397. } else if (is_type_slice(t)) {
  6398. return lb_slice_len(p, v);
  6399. } else if (is_type_dynamic_array(t)) {
  6400. return lb_dynamic_array_len(p, v);
  6401. } else if (is_type_map(t)) {
  6402. return lb_map_len(p, v);
  6403. } else if (is_type_soa_struct(t)) {
  6404. return lb_soa_struct_len(p, v);
  6405. }
  6406. GB_PANIC("Unreachable");
  6407. break;
  6408. }
  6409. case BuiltinProc_cap: {
  6410. lbValue v = lb_build_expr(p, ce->args[0]);
  6411. Type *t = base_type(v.type);
  6412. if (is_type_pointer(t)) {
  6413. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  6414. v = lb_emit_load(p, v);
  6415. t = type_deref(t);
  6416. }
  6417. if (is_type_string(t)) {
  6418. GB_PANIC("Unreachable");
  6419. } else if (is_type_array(t)) {
  6420. GB_PANIC("Array lengths are constant");
  6421. } else if (is_type_slice(t)) {
  6422. return lb_slice_len(p, v);
  6423. } else if (is_type_dynamic_array(t)) {
  6424. return lb_dynamic_array_cap(p, v);
  6425. } else if (is_type_map(t)) {
  6426. return lb_map_cap(p, v);
  6427. } else if (is_type_soa_struct(t)) {
  6428. return lb_soa_struct_cap(p, v);
  6429. }
  6430. GB_PANIC("Unreachable");
  6431. break;
  6432. }
  6433. case BuiltinProc_swizzle: {
  6434. isize index_count = ce->args.count-1;
  6435. if (is_type_simd_vector(tv.type)) {
  6436. lbValue vec = lb_build_expr(p, ce->args[0]);
  6437. if (index_count == 0) {
  6438. return vec;
  6439. }
  6440. unsigned mask_len = cast(unsigned)index_count;
  6441. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  6442. for (isize i = 1; i < ce->args.count; i++) {
  6443. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6444. GB_ASSERT(is_type_integer(tv.type));
  6445. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6446. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  6447. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  6448. }
  6449. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  6450. LLVMValueRef v1 = vec.value;
  6451. LLVMValueRef v2 = vec.value;
  6452. lbValue res = {};
  6453. res.type = tv.type;
  6454. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  6455. return res;
  6456. }
  6457. lbAddr addr = lb_build_addr(p, ce->args[0]);
  6458. if (index_count == 0) {
  6459. return lb_addr_load(p, addr);
  6460. }
  6461. lbValue src = lb_addr_get_ptr(p, addr);
  6462. // TODO(bill): Should this be zeroed or not?
  6463. lbAddr dst = lb_add_local_generated(p, tv.type, true);
  6464. lbValue dst_ptr = lb_addr_get_ptr(p, dst);
  6465. for (i32 i = 1; i < ce->args.count; i++) {
  6466. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  6467. GB_ASSERT(is_type_integer(tv.type));
  6468. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  6469. i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer);
  6470. i32 dst_index = i-1;
  6471. lbValue src_elem = lb_emit_array_epi(p, src, src_index);
  6472. lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index);
  6473. lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem));
  6474. }
  6475. return lb_addr_load(p, dst);
  6476. }
  6477. case BuiltinProc_complex: {
  6478. lbValue real = lb_build_expr(p, ce->args[0]);
  6479. lbValue imag = lb_build_expr(p, ce->args[1]);
  6480. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6481. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6482. Type *ft = base_complex_elem_type(tv.type);
  6483. real = lb_emit_conv(p, real, ft);
  6484. imag = lb_emit_conv(p, imag, ft);
  6485. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  6486. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  6487. return lb_emit_load(p, dst);
  6488. }
  6489. case BuiltinProc_quaternion: {
  6490. lbValue real = lb_build_expr(p, ce->args[0]);
  6491. lbValue imag = lb_build_expr(p, ce->args[1]);
  6492. lbValue jmag = lb_build_expr(p, ce->args[2]);
  6493. lbValue kmag = lb_build_expr(p, ce->args[3]);
  6494. // @QuaternionLayout
  6495. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  6496. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  6497. Type *ft = base_complex_elem_type(tv.type);
  6498. real = lb_emit_conv(p, real, ft);
  6499. imag = lb_emit_conv(p, imag, ft);
  6500. jmag = lb_emit_conv(p, jmag, ft);
  6501. kmag = lb_emit_conv(p, kmag, ft);
  6502. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  6503. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  6504. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  6505. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  6506. return lb_emit_load(p, dst);
  6507. }
  6508. case BuiltinProc_real: {
  6509. lbValue val = lb_build_expr(p, ce->args[0]);
  6510. if (is_type_complex(val.type)) {
  6511. lbValue real = lb_emit_struct_ev(p, val, 0);
  6512. return lb_emit_conv(p, real, tv.type);
  6513. } else if (is_type_quaternion(val.type)) {
  6514. // @QuaternionLayout
  6515. lbValue real = lb_emit_struct_ev(p, val, 3);
  6516. return lb_emit_conv(p, real, tv.type);
  6517. }
  6518. GB_PANIC("invalid type for real");
  6519. return {};
  6520. }
  6521. case BuiltinProc_imag: {
  6522. lbValue val = lb_build_expr(p, ce->args[0]);
  6523. if (is_type_complex(val.type)) {
  6524. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6525. return lb_emit_conv(p, imag, tv.type);
  6526. } else if (is_type_quaternion(val.type)) {
  6527. // @QuaternionLayout
  6528. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6529. return lb_emit_conv(p, imag, tv.type);
  6530. }
  6531. GB_PANIC("invalid type for imag");
  6532. return {};
  6533. }
  6534. case BuiltinProc_jmag: {
  6535. lbValue val = lb_build_expr(p, ce->args[0]);
  6536. if (is_type_quaternion(val.type)) {
  6537. // @QuaternionLayout
  6538. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6539. return lb_emit_conv(p, imag, tv.type);
  6540. }
  6541. GB_PANIC("invalid type for jmag");
  6542. return {};
  6543. }
  6544. case BuiltinProc_kmag: {
  6545. lbValue val = lb_build_expr(p, ce->args[0]);
  6546. if (is_type_quaternion(val.type)) {
  6547. // @QuaternionLayout
  6548. lbValue imag = lb_emit_struct_ev(p, val, 2);
  6549. return lb_emit_conv(p, imag, tv.type);
  6550. }
  6551. GB_PANIC("invalid type for kmag");
  6552. return {};
  6553. }
  6554. case BuiltinProc_conj: {
  6555. lbValue val = lb_build_expr(p, ce->args[0]);
  6556. lbValue res = {};
  6557. Type *t = val.type;
  6558. if (is_type_complex(t)) {
  6559. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6560. lbValue real = lb_emit_struct_ev(p, val, 0);
  6561. lbValue imag = lb_emit_struct_ev(p, val, 1);
  6562. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6563. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  6564. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  6565. } else if (is_type_quaternion(t)) {
  6566. // @QuaternionLayout
  6567. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6568. lbValue real = lb_emit_struct_ev(p, val, 3);
  6569. lbValue imag = lb_emit_struct_ev(p, val, 0);
  6570. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  6571. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  6572. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  6573. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  6574. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  6575. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  6576. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  6577. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  6578. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  6579. }
  6580. return lb_emit_load(p, res);
  6581. }
  6582. case BuiltinProc_expand_to_tuple: {
  6583. lbValue val = lb_build_expr(p, ce->args[0]);
  6584. Type *t = base_type(val.type);
  6585. if (!is_type_tuple(tv.type)) {
  6586. if (t->kind == Type_Struct) {
  6587. GB_ASSERT(t->Struct.fields.count == 1);
  6588. return lb_emit_struct_ev(p, val, 0);
  6589. } else if (t->kind == Type_Array) {
  6590. GB_ASSERT(t->Array.count == 1);
  6591. return lb_emit_array_epi(p, val, 0);
  6592. } else {
  6593. GB_PANIC("Unknown type of expand_to_tuple");
  6594. }
  6595. }
  6596. GB_ASSERT(is_type_tuple(tv.type));
  6597. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  6598. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  6599. if (t->kind == Type_Struct) {
  6600. for_array(src_index, t->Struct.fields) {
  6601. Entity *field = t->Struct.fields[src_index];
  6602. i32 field_index = field->Variable.field_index;
  6603. lbValue f = lb_emit_struct_ev(p, val, field_index);
  6604. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  6605. lb_emit_store(p, ep, f);
  6606. }
  6607. } else if (t->kind == Type_Array) {
  6608. // TODO(bill): Clean-up this code
  6609. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  6610. for (i32 i = 0; i < cast(i32)t->Array.count; i++) {
  6611. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  6612. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  6613. lb_emit_store(p, ep, f);
  6614. }
  6615. } else {
  6616. GB_PANIC("Unknown type of expand_to_tuple");
  6617. }
  6618. return lb_emit_load(p, tuple);
  6619. }
  6620. case BuiltinProc_min: {
  6621. Type *t = type_of_expr(expr);
  6622. if (ce->args.count == 2) {
  6623. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6624. } else {
  6625. lbValue x = lb_build_expr(p, ce->args[0]);
  6626. for (isize i = 1; i < ce->args.count; i++) {
  6627. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  6628. }
  6629. return x;
  6630. }
  6631. }
  6632. case BuiltinProc_max: {
  6633. Type *t = type_of_expr(expr);
  6634. if (ce->args.count == 2) {
  6635. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  6636. } else {
  6637. lbValue x = lb_build_expr(p, ce->args[0]);
  6638. for (isize i = 1; i < ce->args.count; i++) {
  6639. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  6640. }
  6641. return x;
  6642. }
  6643. }
  6644. case BuiltinProc_abs: {
  6645. lbValue x = lb_build_expr(p, ce->args[0]);
  6646. Type *t = x.type;
  6647. if (is_type_unsigned(t)) {
  6648. return x;
  6649. }
  6650. if (is_type_quaternion(t)) {
  6651. i64 sz = 8*type_size_of(t);
  6652. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6653. args[0] = x;
  6654. switch (sz) {
  6655. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  6656. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  6657. }
  6658. GB_PANIC("Unknown complex type");
  6659. } else if (is_type_complex(t)) {
  6660. i64 sz = 8*type_size_of(t);
  6661. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6662. args[0] = x;
  6663. switch (sz) {
  6664. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  6665. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  6666. }
  6667. GB_PANIC("Unknown complex type");
  6668. } else if (is_type_float(t)) {
  6669. i64 sz = 8*type_size_of(t);
  6670. auto args = array_make<lbValue>(permanent_allocator(), 1);
  6671. args[0] = x;
  6672. switch (sz) {
  6673. case 32: return lb_emit_runtime_call(p, "abs_f32", args);
  6674. case 64: return lb_emit_runtime_call(p, "abs_f64", args);
  6675. }
  6676. GB_PANIC("Unknown float type");
  6677. }
  6678. lbValue zero = lb_const_nil(p->module, t);
  6679. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  6680. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  6681. return lb_emit_select(p, cond, neg, x);
  6682. }
  6683. case BuiltinProc_clamp:
  6684. return lb_emit_clamp(p, type_of_expr(expr),
  6685. lb_build_expr(p, ce->args[0]),
  6686. lb_build_expr(p, ce->args[1]),
  6687. lb_build_expr(p, ce->args[2]));
  6688. // "Intrinsics"
  6689. case BuiltinProc_alloca:
  6690. {
  6691. lbValue sz = lb_build_expr(p, ce->args[0]);
  6692. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  6693. lbValue res = {};
  6694. res.type = t_u8_ptr;
  6695. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  6696. LLVMSetAlignment(res.value, cast(unsigned)al);
  6697. return res;
  6698. }
  6699. case BuiltinProc_cpu_relax:
  6700. if (build_context.metrics.arch == TargetArch_386 ||
  6701. build_context.metrics.arch == TargetArch_amd64) {
  6702. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  6703. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  6704. cast(char *)"pause", 5,
  6705. cast(char *)"", 0,
  6706. /*HasSideEffects*/true, /*IsAlignStack*/false,
  6707. LLVMInlineAsmDialectATT
  6708. );
  6709. GB_ASSERT(the_asm != nullptr);
  6710. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  6711. }
  6712. return {};
  6713. case BuiltinProc_atomic_fence:
  6714. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  6715. return {};
  6716. case BuiltinProc_atomic_fence_acq:
  6717. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  6718. return {};
  6719. case BuiltinProc_atomic_fence_rel:
  6720. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  6721. return {};
  6722. case BuiltinProc_atomic_fence_acqrel:
  6723. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  6724. return {};
  6725. case BuiltinProc_atomic_store:
  6726. case BuiltinProc_atomic_store_rel:
  6727. case BuiltinProc_atomic_store_relaxed:
  6728. case BuiltinProc_atomic_store_unordered: {
  6729. lbValue dst = lb_build_expr(p, ce->args[0]);
  6730. lbValue val = lb_build_expr(p, ce->args[1]);
  6731. val = lb_emit_conv(p, val, type_deref(dst.type));
  6732. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  6733. switch (id) {
  6734. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6735. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  6736. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6737. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6738. }
  6739. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6740. return {};
  6741. }
  6742. case BuiltinProc_atomic_load:
  6743. case BuiltinProc_atomic_load_acq:
  6744. case BuiltinProc_atomic_load_relaxed:
  6745. case BuiltinProc_atomic_load_unordered: {
  6746. lbValue dst = lb_build_expr(p, ce->args[0]);
  6747. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  6748. switch (id) {
  6749. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  6750. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  6751. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  6752. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  6753. }
  6754. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  6755. lbValue res = {};
  6756. res.value = instr;
  6757. res.type = type_deref(dst.type);
  6758. return res;
  6759. }
  6760. case BuiltinProc_atomic_add:
  6761. case BuiltinProc_atomic_add_acq:
  6762. case BuiltinProc_atomic_add_rel:
  6763. case BuiltinProc_atomic_add_acqrel:
  6764. case BuiltinProc_atomic_add_relaxed:
  6765. case BuiltinProc_atomic_sub:
  6766. case BuiltinProc_atomic_sub_acq:
  6767. case BuiltinProc_atomic_sub_rel:
  6768. case BuiltinProc_atomic_sub_acqrel:
  6769. case BuiltinProc_atomic_sub_relaxed:
  6770. case BuiltinProc_atomic_and:
  6771. case BuiltinProc_atomic_and_acq:
  6772. case BuiltinProc_atomic_and_rel:
  6773. case BuiltinProc_atomic_and_acqrel:
  6774. case BuiltinProc_atomic_and_relaxed:
  6775. case BuiltinProc_atomic_nand:
  6776. case BuiltinProc_atomic_nand_acq:
  6777. case BuiltinProc_atomic_nand_rel:
  6778. case BuiltinProc_atomic_nand_acqrel:
  6779. case BuiltinProc_atomic_nand_relaxed:
  6780. case BuiltinProc_atomic_or:
  6781. case BuiltinProc_atomic_or_acq:
  6782. case BuiltinProc_atomic_or_rel:
  6783. case BuiltinProc_atomic_or_acqrel:
  6784. case BuiltinProc_atomic_or_relaxed:
  6785. case BuiltinProc_atomic_xor:
  6786. case BuiltinProc_atomic_xor_acq:
  6787. case BuiltinProc_atomic_xor_rel:
  6788. case BuiltinProc_atomic_xor_acqrel:
  6789. case BuiltinProc_atomic_xor_relaxed:
  6790. case BuiltinProc_atomic_xchg:
  6791. case BuiltinProc_atomic_xchg_acq:
  6792. case BuiltinProc_atomic_xchg_rel:
  6793. case BuiltinProc_atomic_xchg_acqrel:
  6794. case BuiltinProc_atomic_xchg_relaxed: {
  6795. lbValue dst = lb_build_expr(p, ce->args[0]);
  6796. lbValue val = lb_build_expr(p, ce->args[1]);
  6797. val = lb_emit_conv(p, val, type_deref(dst.type));
  6798. LLVMAtomicRMWBinOp op = {};
  6799. LLVMAtomicOrdering ordering = {};
  6800. switch (id) {
  6801. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6802. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  6803. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  6804. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6805. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  6806. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6807. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  6808. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  6809. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6810. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  6811. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6812. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  6813. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  6814. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6815. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  6816. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6817. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  6818. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  6819. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6820. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  6821. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6822. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  6823. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  6824. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6825. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  6826. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6827. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  6828. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  6829. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6830. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  6831. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  6832. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  6833. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  6834. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  6835. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  6836. }
  6837. lbValue res = {};
  6838. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  6839. res.type = tv.type;
  6840. return res;
  6841. }
  6842. case BuiltinProc_atomic_cxchg:
  6843. case BuiltinProc_atomic_cxchg_acq:
  6844. case BuiltinProc_atomic_cxchg_rel:
  6845. case BuiltinProc_atomic_cxchg_acqrel:
  6846. case BuiltinProc_atomic_cxchg_relaxed:
  6847. case BuiltinProc_atomic_cxchg_failrelaxed:
  6848. case BuiltinProc_atomic_cxchg_failacq:
  6849. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  6850. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  6851. case BuiltinProc_atomic_cxchgweak:
  6852. case BuiltinProc_atomic_cxchgweak_acq:
  6853. case BuiltinProc_atomic_cxchgweak_rel:
  6854. case BuiltinProc_atomic_cxchgweak_acqrel:
  6855. case BuiltinProc_atomic_cxchgweak_relaxed:
  6856. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  6857. case BuiltinProc_atomic_cxchgweak_failacq:
  6858. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  6859. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  6860. Type *type = expr->tav.type;
  6861. lbValue address = lb_build_expr(p, ce->args[0]);
  6862. Type *elem = type_deref(address.type);
  6863. lbValue old_value = lb_build_expr(p, ce->args[1]);
  6864. lbValue new_value = lb_build_expr(p, ce->args[2]);
  6865. old_value = lb_emit_conv(p, old_value, elem);
  6866. new_value = lb_emit_conv(p, new_value, elem);
  6867. LLVMAtomicOrdering success_ordering = {};
  6868. LLVMAtomicOrdering failure_ordering = {};
  6869. LLVMBool weak = false;
  6870. switch (id) {
  6871. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6872. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6873. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6874. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6875. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6876. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6877. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  6878. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6879. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  6880. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  6881. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6882. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6883. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  6884. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6885. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6886. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  6887. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6888. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  6889. }
  6890. // TODO(bill): Figure out how to make it weak
  6891. LLVMBool single_threaded = weak;
  6892. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  6893. p->builder, address.value,
  6894. old_value.value, new_value.value,
  6895. success_ordering,
  6896. failure_ordering,
  6897. single_threaded
  6898. );
  6899. GB_ASSERT(tv.type->kind == Type_Tuple);
  6900. Type *fix_typed = alloc_type_tuple();
  6901. array_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  6902. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  6903. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  6904. lbValue res = {};
  6905. res.value = value;
  6906. res.type = fix_typed;
  6907. return res;
  6908. }
  6909. case BuiltinProc_type_equal_proc:
  6910. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  6911. case BuiltinProc_type_hasher_proc:
  6912. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  6913. }
  6914. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  6915. return {};
  6916. }
  6917. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  6918. switch (param_value.kind) {
  6919. case ParameterValue_Constant:
  6920. if (is_type_constant_type(parameter_type)) {
  6921. return lb_const_value(p->module, parameter_type, param_value.value);
  6922. } else {
  6923. ExactValue ev = param_value.value;
  6924. lbValue arg = {};
  6925. Type *type = type_of_expr(param_value.original_ast_expr);
  6926. if (type != nullptr) {
  6927. arg = lb_const_value(p->module, type, ev);
  6928. } else {
  6929. arg = lb_const_value(p->module, parameter_type, param_value.value);
  6930. }
  6931. return lb_emit_conv(p, arg, parameter_type);
  6932. }
  6933. case ParameterValue_Nil:
  6934. return lb_const_nil(p->module, parameter_type);
  6935. case ParameterValue_Location:
  6936. {
  6937. String proc_name = {};
  6938. if (p->entity != nullptr) {
  6939. proc_name = p->entity->token.string;
  6940. }
  6941. return lb_emit_source_code_location(p, proc_name, pos);
  6942. }
  6943. case ParameterValue_Value:
  6944. return lb_build_expr(p, param_value.ast_value);
  6945. }
  6946. return lb_const_nil(p->module, parameter_type);
  6947. }
  6948. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  6949. lbModule *m = p->module;
  6950. TypeAndValue tv = type_and_value_of_expr(expr);
  6951. ast_node(ce, CallExpr, expr);
  6952. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  6953. AddressingMode proc_mode = proc_tv.mode;
  6954. if (proc_mode == Addressing_Type) {
  6955. GB_ASSERT(ce->args.count == 1);
  6956. lbValue x = lb_build_expr(p, ce->args[0]);
  6957. lbValue y = lb_emit_conv(p, x, tv.type);
  6958. return y;
  6959. }
  6960. Ast *pexpr = unparen_expr(ce->proc);
  6961. if (proc_mode == Addressing_Builtin) {
  6962. Entity *e = entity_of_node(pexpr);
  6963. BuiltinProcId id = BuiltinProc_Invalid;
  6964. if (e != nullptr) {
  6965. id = cast(BuiltinProcId)e->Builtin.id;
  6966. } else {
  6967. id = BuiltinProc_DIRECTIVE;
  6968. }
  6969. return lb_build_builtin_proc(p, expr, tv, id);
  6970. }
  6971. // NOTE(bill): Regular call
  6972. lbValue value = {};
  6973. Ast *proc_expr = unparen_expr(ce->proc);
  6974. if (proc_expr->tav.mode == Addressing_Constant) {
  6975. ExactValue v = proc_expr->tav.value;
  6976. switch (v.kind) {
  6977. case ExactValue_Integer:
  6978. {
  6979. u64 u = big_int_to_u64(&v.value_integer);
  6980. lbValue x = {};
  6981. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  6982. x.type = t_uintptr;
  6983. x = lb_emit_conv(p, x, t_rawptr);
  6984. value = lb_emit_conv(p, x, proc_expr->tav.type);
  6985. break;
  6986. }
  6987. case ExactValue_Pointer:
  6988. {
  6989. u64 u = cast(u64)v.value_pointer;
  6990. lbValue x = {};
  6991. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  6992. x.type = t_uintptr;
  6993. x = lb_emit_conv(p, x, t_rawptr);
  6994. value = lb_emit_conv(p, x, proc_expr->tav.type);
  6995. break;
  6996. }
  6997. }
  6998. }
  6999. if (value.value == nullptr) {
  7000. value = lb_build_expr(p, proc_expr);
  7001. }
  7002. GB_ASSERT(value.value != nullptr);
  7003. Type *proc_type_ = base_type(value.type);
  7004. GB_ASSERT(proc_type_->kind == Type_Proc);
  7005. TypeProc *pt = &proc_type_->Proc;
  7006. set_procedure_abi_types(proc_type_);
  7007. if (is_call_expr_field_value(ce)) {
  7008. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  7009. for_array(arg_index, ce->args) {
  7010. Ast *arg = ce->args[arg_index];
  7011. ast_node(fv, FieldValue, arg);
  7012. GB_ASSERT(fv->field->kind == Ast_Ident);
  7013. String name = fv->field->Ident.token.string;
  7014. isize index = lookup_procedure_parameter(pt, name);
  7015. GB_ASSERT(index >= 0);
  7016. TypeAndValue tav = type_and_value_of_expr(fv->value);
  7017. if (tav.mode == Addressing_Type) {
  7018. args[index] = lb_const_nil(m, tav.type);
  7019. } else {
  7020. args[index] = lb_build_expr(p, fv->value);
  7021. }
  7022. }
  7023. TypeTuple *params = &pt->params->Tuple;
  7024. for (isize i = 0; i < args.count; i++) {
  7025. Entity *e = params->variables[i];
  7026. if (e->kind == Entity_TypeName) {
  7027. args[i] = lb_const_nil(m, e->type);
  7028. } else if (e->kind == Entity_Constant) {
  7029. continue;
  7030. } else {
  7031. GB_ASSERT(e->kind == Entity_Variable);
  7032. if (args[i].value == nullptr) {
  7033. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7034. } else {
  7035. args[i] = lb_emit_conv(p, args[i], e->type);
  7036. }
  7037. }
  7038. }
  7039. for (isize i = 0; i < args.count; i++) {
  7040. Entity *e = params->variables[i];
  7041. if (args[i].type == nullptr) {
  7042. continue;
  7043. } else if (is_type_untyped_nil(args[i].type)) {
  7044. args[i] = lb_const_nil(m, e->type);
  7045. } else if (is_type_untyped_undef(args[i].type)) {
  7046. args[i] = lb_const_undef(m, e->type);
  7047. }
  7048. }
  7049. return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr);
  7050. }
  7051. isize arg_index = 0;
  7052. isize arg_count = 0;
  7053. for_array(i, ce->args) {
  7054. Ast *arg = ce->args[i];
  7055. TypeAndValue tav = type_and_value_of_expr(arg);
  7056. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr));
  7057. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  7058. Type *at = tav.type;
  7059. if (at->kind == Type_Tuple) {
  7060. arg_count += at->Tuple.variables.count;
  7061. } else {
  7062. arg_count++;
  7063. }
  7064. }
  7065. isize param_count = 0;
  7066. if (pt->params) {
  7067. GB_ASSERT(pt->params->kind == Type_Tuple);
  7068. param_count = pt->params->Tuple.variables.count;
  7069. }
  7070. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  7071. isize variadic_index = pt->variadic_index;
  7072. bool variadic = pt->variadic && variadic_index >= 0;
  7073. bool vari_expand = ce->ellipsis.pos.line != 0;
  7074. bool is_c_vararg = pt->c_vararg;
  7075. String proc_name = {};
  7076. if (p->entity != nullptr) {
  7077. proc_name = p->entity->token.string;
  7078. }
  7079. TokenPos pos = ast_token(ce->proc).pos;
  7080. TypeTuple *param_tuple = nullptr;
  7081. if (pt->params) {
  7082. GB_ASSERT(pt->params->kind == Type_Tuple);
  7083. param_tuple = &pt->params->Tuple;
  7084. }
  7085. for_array(i, ce->args) {
  7086. Ast *arg = ce->args[i];
  7087. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  7088. if (arg_tv.mode == Addressing_Type) {
  7089. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  7090. } else {
  7091. lbValue a = lb_build_expr(p, arg);
  7092. Type *at = a.type;
  7093. if (at->kind == Type_Tuple) {
  7094. for_array(i, at->Tuple.variables) {
  7095. Entity *e = at->Tuple.variables[i];
  7096. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  7097. args[arg_index++] = v;
  7098. }
  7099. } else {
  7100. args[arg_index++] = a;
  7101. }
  7102. }
  7103. }
  7104. if (param_count > 0) {
  7105. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  7106. GB_ASSERT(param_count < 1000000);
  7107. if (arg_count < param_count) {
  7108. isize end = cast(isize)param_count;
  7109. if (variadic) {
  7110. end = variadic_index;
  7111. }
  7112. while (arg_index < end) {
  7113. Entity *e = param_tuple->variables[arg_index];
  7114. GB_ASSERT(e->kind == Entity_Variable);
  7115. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7116. }
  7117. }
  7118. if (is_c_vararg) {
  7119. GB_ASSERT(variadic);
  7120. GB_ASSERT(!vari_expand);
  7121. isize i = 0;
  7122. for (; i < variadic_index; i++) {
  7123. Entity *e = param_tuple->variables[i];
  7124. if (e->kind == Entity_Variable) {
  7125. args[i] = lb_emit_conv(p, args[i], e->type);
  7126. }
  7127. }
  7128. Type *variadic_type = param_tuple->variables[i]->type;
  7129. GB_ASSERT(is_type_slice(variadic_type));
  7130. variadic_type = base_type(variadic_type)->Slice.elem;
  7131. if (!is_type_any(variadic_type)) {
  7132. for (; i < arg_count; i++) {
  7133. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7134. }
  7135. } else {
  7136. for (; i < arg_count; i++) {
  7137. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  7138. }
  7139. }
  7140. } else if (variadic) {
  7141. isize i = 0;
  7142. for (; i < variadic_index; i++) {
  7143. Entity *e = param_tuple->variables[i];
  7144. if (e->kind == Entity_Variable) {
  7145. args[i] = lb_emit_conv(p, args[i], e->type);
  7146. }
  7147. }
  7148. if (!vari_expand) {
  7149. Type *variadic_type = param_tuple->variables[i]->type;
  7150. GB_ASSERT(is_type_slice(variadic_type));
  7151. variadic_type = base_type(variadic_type)->Slice.elem;
  7152. for (; i < arg_count; i++) {
  7153. args[i] = lb_emit_conv(p, args[i], variadic_type);
  7154. }
  7155. }
  7156. } else {
  7157. for (isize i = 0; i < param_count; i++) {
  7158. Entity *e = param_tuple->variables[i];
  7159. if (e->kind == Entity_Variable) {
  7160. if (args[i].value == nullptr) {
  7161. continue;
  7162. }
  7163. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  7164. args[i] = lb_emit_conv(p, args[i], e->type);
  7165. }
  7166. }
  7167. }
  7168. if (variadic && !vari_expand && !is_c_vararg) {
  7169. // variadic call argument generation
  7170. Type *slice_type = param_tuple->variables[variadic_index]->type;
  7171. Type *elem_type = base_type(slice_type)->Slice.elem;
  7172. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  7173. isize slice_len = arg_count+1 - (variadic_index+1);
  7174. if (slice_len > 0) {
  7175. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  7176. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  7177. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  7178. lb_emit_store(p, addr, args[i]);
  7179. }
  7180. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  7181. lbValue len = lb_const_int(m, t_int, slice_len);
  7182. lb_fill_slice(p, slice, base_elem, len);
  7183. }
  7184. arg_count = param_count;
  7185. args[variadic_index] = lb_addr_load(p, slice);
  7186. }
  7187. }
  7188. if (variadic && variadic_index+1 < param_count) {
  7189. for (isize i = variadic_index+1; i < param_count; i++) {
  7190. Entity *e = param_tuple->variables[i];
  7191. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  7192. }
  7193. }
  7194. isize final_count = param_count;
  7195. if (is_c_vararg) {
  7196. final_count = arg_count;
  7197. }
  7198. if (param_tuple != nullptr) {
  7199. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  7200. Entity *e = param_tuple->variables[i];
  7201. if (args[i].type == nullptr) {
  7202. continue;
  7203. } else if (is_type_untyped_nil(args[i].type)) {
  7204. args[i] = lb_const_nil(m, e->type);
  7205. } else if (is_type_untyped_undef(args[i].type)) {
  7206. args[i] = lb_const_undef(m, e->type);
  7207. }
  7208. }
  7209. }
  7210. auto call_args = array_slice(args, 0, final_count);
  7211. return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr);
  7212. }
  7213. bool lb_is_const(lbValue value) {
  7214. LLVMValueRef v = value.value;
  7215. if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) {
  7216. // TODO(bill): Is this correct behaviour?
  7217. return true;
  7218. }
  7219. if (LLVMIsConstant(v)) {
  7220. return true;
  7221. }
  7222. return false;
  7223. }
  7224. bool lb_is_const_or_global(lbValue value) {
  7225. return (LLVMGetValueKind(value.value) == LLVMGlobalVariableValueKind) || lb_is_const(value);
  7226. }
  7227. bool lb_is_const_nil(lbValue value) {
  7228. LLVMValueRef v = value.value;
  7229. if (LLVMIsConstant(v)) {
  7230. if (LLVMIsAConstantAggregateZero(v)) {
  7231. return true;
  7232. } else if (LLVMIsAConstantPointerNull(v)) {
  7233. return true;
  7234. }
  7235. }
  7236. return false;
  7237. }
  7238. String lb_get_const_string(lbModule *m, lbValue value) {
  7239. GB_ASSERT(lb_is_const(value));
  7240. Type *t = base_type(value.type);
  7241. GB_ASSERT(are_types_identical(t, t_string));
  7242. unsigned ptr_indices[1] = {0};
  7243. unsigned len_indices[1] = {1};
  7244. LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices));
  7245. LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices));
  7246. GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr);
  7247. underlying_ptr = LLVMGetOperand(underlying_ptr, 0);
  7248. GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr));
  7249. underlying_ptr = LLVMGetInitializer(underlying_ptr);
  7250. size_t length = 0;
  7251. char const *text = LLVMGetAsString(underlying_ptr, &length);
  7252. isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len);
  7253. return make_string(cast(u8 const *)text, real_length);
  7254. }
  7255. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  7256. GB_ASSERT(is_type_pointer(addr.type));
  7257. Type *type = type_deref(addr.type);
  7258. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  7259. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  7260. }
  7261. LLVMValueRef lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  7262. AstPackage *pkg = m->info->runtime_package;
  7263. Entity *e = scope_lookup_current(pkg->scope, name);
  7264. lbValue *found = nullptr;
  7265. if (m != e->code_gen_module) {
  7266. gb_mutex_lock(&m->mutex);
  7267. }
  7268. GB_ASSERT(e->code_gen_module != nullptr);
  7269. found = map_get(&e->code_gen_module->values, hash_entity(e));
  7270. if (m != e->code_gen_module) {
  7271. gb_mutex_unlock(&m->mutex);
  7272. }
  7273. GB_ASSERT(found != nullptr);
  7274. return found->value;
  7275. }
  7276. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) {
  7277. Type *vt = core_type(value.type);
  7278. GB_ASSERT(type_size_of(vt) == type_size_of(platform_type));
  7279. // TODO(bill): lb_emit_byte_swap
  7280. lbValue res = {};
  7281. res.type = platform_type;
  7282. res.value = value.value;
  7283. int sz = cast(int)type_size_of(vt);
  7284. if (sz > 1) {
  7285. if (is_type_float(platform_type)) {
  7286. String name = {};
  7287. switch (sz) {
  7288. case 4: name = str_lit("bswap_f32"); break;
  7289. case 8: name = str_lit("bswap_f64"); break;
  7290. default: GB_PANIC("unhandled byteswap size"); break;
  7291. }
  7292. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7293. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7294. } else {
  7295. GB_ASSERT(is_type_integer(platform_type));
  7296. String name = {};
  7297. switch (sz) {
  7298. case 2: name = str_lit("bswap_16"); break;
  7299. case 4: name = str_lit("bswap_32"); break;
  7300. case 8: name = str_lit("bswap_64"); break;
  7301. case 16: name = str_lit("bswap_128"); break;
  7302. default: GB_PANIC("unhandled byteswap size"); break;
  7303. }
  7304. LLVMValueRef fn = lb_lookup_runtime_procedure(p->module, name);
  7305. res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, "");
  7306. }
  7307. }
  7308. return res;
  7309. }
  7310. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) {
  7311. lbLoopData data = {};
  7312. lbValue max = lb_const_int(p->module, t_int, count);
  7313. data.idx_addr = lb_add_local_generated(p, index_type, true);
  7314. data.body = lb_create_block(p, "loop.body");
  7315. data.done = lb_create_block(p, "loop.done");
  7316. data.loop = lb_create_block(p, "loop.loop");
  7317. lb_emit_jump(p, data.loop);
  7318. lb_start_block(p, data.loop);
  7319. data.idx = lb_addr_load(p, data.idx_addr);
  7320. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  7321. lb_emit_if(p, cond, data.body, data.done);
  7322. lb_start_block(p, data.body);
  7323. return data;
  7324. }
  7325. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  7326. if (data.idx_addr.addr.value != nullptr) {
  7327. lb_emit_increment(p, data.idx_addr.addr);
  7328. lb_emit_jump(p, data.loop);
  7329. lb_start_block(p, data.done);
  7330. }
  7331. }
  7332. lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  7333. lbValue res = {};
  7334. res.type = t_llvm_bool;
  7335. Type *t = x.type;
  7336. if (is_type_pointer(t)) {
  7337. if (op_kind == Token_CmpEq) {
  7338. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7339. } else if (op_kind == Token_NotEq) {
  7340. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7341. }
  7342. return res;
  7343. } else if (is_type_cstring(t)) {
  7344. lbValue ptr = lb_emit_conv(p, x, t_u8_ptr);
  7345. if (op_kind == Token_CmpEq) {
  7346. res.value = LLVMBuildIsNull(p->builder, ptr.value, "");
  7347. } else if (op_kind == Token_NotEq) {
  7348. res.value = LLVMBuildIsNotNull(p->builder, ptr.value, "");
  7349. }
  7350. return res;
  7351. } else if (is_type_proc(t)) {
  7352. if (op_kind == Token_CmpEq) {
  7353. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  7354. } else if (op_kind == Token_NotEq) {
  7355. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  7356. }
  7357. return res;
  7358. } else if (is_type_any(t)) {
  7359. // TODO(bill): is this correct behaviour for nil comparison for any?
  7360. lbValue data = lb_emit_struct_ev(p, x, 0);
  7361. lbValue ti = lb_emit_struct_ev(p, x, 1);
  7362. if (op_kind == Token_CmpEq) {
  7363. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  7364. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  7365. res.value = LLVMBuildOr(p->builder, a, b, "");
  7366. return res;
  7367. } else if (op_kind == Token_NotEq) {
  7368. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  7369. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  7370. res.value = LLVMBuildAnd(p->builder, a, b, "");
  7371. return res;
  7372. }
  7373. } else if (is_type_slice(t)) {
  7374. lbValue len = lb_emit_struct_ev(p, x, 1);
  7375. if (op_kind == Token_CmpEq) {
  7376. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7377. return res;
  7378. } else if (op_kind == Token_NotEq) {
  7379. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7380. return res;
  7381. }
  7382. } else if (is_type_dynamic_array(t)) {
  7383. lbValue cap = lb_emit_struct_ev(p, x, 2);
  7384. if (op_kind == Token_CmpEq) {
  7385. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7386. return res;
  7387. } else if (op_kind == Token_NotEq) {
  7388. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7389. return res;
  7390. }
  7391. } else if (is_type_map(t)) {
  7392. lbValue cap = lb_map_cap(p, x);
  7393. return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type));
  7394. } else if (is_type_union(t)) {
  7395. if (type_size_of(t) == 0) {
  7396. if (op_kind == Token_CmpEq) {
  7397. return lb_const_bool(p->module, t_llvm_bool, true);
  7398. } else if (op_kind == Token_NotEq) {
  7399. return lb_const_bool(p->module, t_llvm_bool, false);
  7400. }
  7401. } else {
  7402. lbValue tag = lb_emit_union_tag_value(p, x);
  7403. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  7404. }
  7405. } else if (is_type_typeid(t)) {
  7406. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  7407. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  7408. } else if (is_type_soa_struct(t)) {
  7409. Type *bt = base_type(t);
  7410. if (bt->Struct.soa_kind == StructSoa_Slice) {
  7411. lbValue len = lb_soa_struct_len(p, x);
  7412. if (op_kind == Token_CmpEq) {
  7413. res.value = LLVMBuildIsNull(p->builder, len.value, "");
  7414. return res;
  7415. } else if (op_kind == Token_NotEq) {
  7416. res.value = LLVMBuildIsNotNull(p->builder, len.value, "");
  7417. return res;
  7418. }
  7419. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  7420. lbValue cap = lb_soa_struct_cap(p, x);
  7421. if (op_kind == Token_CmpEq) {
  7422. res.value = LLVMBuildIsNull(p->builder, cap.value, "");
  7423. return res;
  7424. } else if (op_kind == Token_NotEq) {
  7425. res.value = LLVMBuildIsNotNull(p->builder, cap.value, "");
  7426. return res;
  7427. }
  7428. }
  7429. } else if (is_type_struct(t) && type_has_nil(t)) {
  7430. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7431. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  7432. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7433. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  7434. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  7435. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  7436. return res;
  7437. }
  7438. return {};
  7439. }
  7440. lbValue lb_get_equal_proc_for_type(lbModule *m, Type *type) {
  7441. Type *original_type = type;
  7442. type = base_type(type);
  7443. GB_ASSERT(is_type_comparable(type));
  7444. Type *pt = alloc_type_pointer(type);
  7445. LLVMTypeRef ptr_type = lb_type(m, pt);
  7446. auto key = hash_type(type);
  7447. lbProcedure **found = map_get(&m->equal_procs, key);
  7448. lbProcedure *compare_proc = nullptr;
  7449. if (found) {
  7450. compare_proc = *found;
  7451. GB_ASSERT(compare_proc != nullptr);
  7452. return {compare_proc->value, compare_proc->type};
  7453. }
  7454. static u32 proc_index = 0;
  7455. char buf[16] = {};
  7456. isize n = gb_snprintf(buf, 16, "__$equal%u", ++proc_index);
  7457. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  7458. String proc_name = make_string_c(str);
  7459. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  7460. map_set(&m->equal_procs, key, p);
  7461. lb_begin_procedure_body(p);
  7462. LLVMValueRef x = LLVMGetParam(p->value, 0);
  7463. LLVMValueRef y = LLVMGetParam(p->value, 1);
  7464. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  7465. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  7466. lbValue lhs = {x, pt};
  7467. lbValue rhs = {y, pt};
  7468. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  7469. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  7470. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  7471. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  7472. lb_start_block(p, block_same_ptr);
  7473. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  7474. lb_start_block(p, block_diff_ptr);
  7475. if (type->kind == Type_Struct) {
  7476. type_set_offsets(type);
  7477. lbBlock *block_false = lb_create_block(p, "bfalse");
  7478. lbValue res = lb_const_bool(m, t_bool, true);
  7479. for_array(i, type->Struct.fields) {
  7480. lbBlock *next_block = lb_create_block(p, "btrue");
  7481. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  7482. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  7483. lbValue left = lb_emit_load(p, pleft);
  7484. lbValue right = lb_emit_load(p, pright);
  7485. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  7486. lb_emit_if(p, ok, next_block, block_false);
  7487. lb_emit_jump(p, next_block);
  7488. lb_start_block(p, next_block);
  7489. }
  7490. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  7491. lb_start_block(p, block_false);
  7492. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  7493. } else {
  7494. lbValue left = lb_emit_load(p, lhs);
  7495. lbValue right = lb_emit_load(p, rhs);
  7496. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  7497. ok = lb_emit_conv(p, ok, t_bool);
  7498. LLVMBuildRet(p->builder, ok.value);
  7499. }
  7500. lb_end_procedure_body(p);
  7501. compare_proc = p;
  7502. return {compare_proc->value, compare_proc->type};
  7503. }
  7504. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  7505. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  7506. i64 sz = type_size_of(type);
  7507. if (1 <= sz && sz <= 16) {
  7508. char name[20] = {};
  7509. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  7510. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7511. args[0] = data;
  7512. args[1] = seed;
  7513. return lb_emit_runtime_call(p, name, args);
  7514. }
  7515. auto args = array_make<lbValue>(permanent_allocator(), 3);
  7516. args[0] = data;
  7517. args[1] = seed;
  7518. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  7519. return lb_emit_runtime_call(p, "default_hasher_n", args);
  7520. }
  7521. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  7522. Type *original_type = type;
  7523. type = core_type(type);
  7524. GB_ASSERT(is_type_valid_for_keys(type));
  7525. Type *pt = alloc_type_pointer(type);
  7526. LLVMTypeRef ptr_type = lb_type(m, pt);
  7527. auto key = hash_type(type);
  7528. lbProcedure **found = map_get(&m->hasher_procs, key);
  7529. if (found) {
  7530. GB_ASSERT(*found != nullptr);
  7531. return {(*found)->value, (*found)->type};
  7532. }
  7533. static u32 proc_index = 0;
  7534. char buf[16] = {};
  7535. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  7536. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  7537. String proc_name = make_string_c(str);
  7538. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  7539. map_set(&m->hasher_procs, key, p);
  7540. lb_begin_procedure_body(p);
  7541. defer (lb_end_procedure_body(p));
  7542. LLVMValueRef x = LLVMGetParam(p->value, 0);
  7543. LLVMValueRef y = LLVMGetParam(p->value, 1);
  7544. lbValue data = {x, t_rawptr};
  7545. lbValue seed = {y, t_uintptr};
  7546. if (is_type_simple_compare(type)) {
  7547. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  7548. LLVMBuildRet(p->builder, res.value);
  7549. return {p->value, p->type};
  7550. }
  7551. if (type->kind == Type_Struct) {
  7552. type_set_offsets(type);
  7553. data = lb_emit_conv(p, data, t_u8_ptr);
  7554. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7555. for_array(i, type->Struct.fields) {
  7556. i64 offset = type->Struct.offsets[i];
  7557. Entity *field = type->Struct.fields[i];
  7558. lbValue field_hasher = lb_get_hasher_proc_for_type(m, field->type);
  7559. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  7560. args[0] = ptr;
  7561. args[1] = seed;
  7562. seed = lb_emit_call(p, field_hasher, args);
  7563. }
  7564. LLVMBuildRet(p->builder, seed.value);
  7565. } else if (type->kind == Type_Array) {
  7566. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  7567. lb_addr_store(p, pres, seed);
  7568. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7569. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->Array.elem);
  7570. auto loop_data = lb_loop_start(p, type->Array.count, t_i32);
  7571. data = lb_emit_conv(p, data, pt);
  7572. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  7573. args[0] = ptr;
  7574. args[1] = lb_addr_load(p, pres);
  7575. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  7576. lb_addr_store(p, pres, new_seed);
  7577. lb_loop_end(p, loop_data);
  7578. lbValue res = lb_addr_load(p, pres);
  7579. LLVMBuildRet(p->builder, res.value);
  7580. } else if (type->kind == Type_EnumeratedArray) {
  7581. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  7582. lb_addr_store(p, res, seed);
  7583. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7584. lbValue elem_hasher = lb_get_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  7585. auto loop_data = lb_loop_start(p, type->EnumeratedArray.count, t_i32);
  7586. data = lb_emit_conv(p, data, pt);
  7587. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  7588. args[0] = ptr;
  7589. args[1] = lb_addr_load(p, res);
  7590. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  7591. lb_addr_store(p, res, new_seed);
  7592. lb_loop_end(p, loop_data);
  7593. lbValue vres = lb_addr_load(p, res);
  7594. LLVMBuildRet(p->builder, vres.value);
  7595. } else if (is_type_cstring(type)) {
  7596. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7597. args[0] = data;
  7598. args[1] = seed;
  7599. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  7600. LLVMBuildRet(p->builder, res.value);
  7601. } else if (is_type_string(type)) {
  7602. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7603. args[0] = data;
  7604. args[1] = seed;
  7605. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  7606. LLVMBuildRet(p->builder, res.value);
  7607. } else {
  7608. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  7609. }
  7610. return {p->value, p->type};
  7611. }
  7612. lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  7613. Type *a = core_type(left.type);
  7614. Type *b = core_type(right.type);
  7615. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  7616. lbValue nil_check = {};
  7617. if (is_type_untyped_nil(left.type)) {
  7618. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  7619. } else if (is_type_untyped_nil(right.type)) {
  7620. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  7621. }
  7622. if (nil_check.value != nullptr) {
  7623. return nil_check;
  7624. }
  7625. if (are_types_identical(a, b)) {
  7626. // NOTE(bill): No need for a conversion
  7627. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  7628. left = lb_emit_conv(p, left, right.type);
  7629. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  7630. right = lb_emit_conv(p, right, left.type);
  7631. } else {
  7632. Type *lt = left.type;
  7633. Type *rt = right.type;
  7634. // if (is_type_bit_set(lt) && is_type_bit_set(rt)) {
  7635. // Type *blt = base_type(lt);
  7636. // Type *brt = base_type(rt);
  7637. // i64 bits = gb_max(blt->BitSet.bits, brt->BitSet.bits);
  7638. // i64 bytes = bits / 8;
  7639. // switch (bytes) {
  7640. // case 1:
  7641. // left = lb_emit_conv(p, left, t_u8);
  7642. // right = lb_emit_conv(p, right, t_u8);
  7643. // break;
  7644. // case 2:
  7645. // left = lb_emit_conv(p, left, t_u16);
  7646. // right = lb_emit_conv(p, right, t_u16);
  7647. // break;
  7648. // case 4:
  7649. // left = lb_emit_conv(p, left, t_u32);
  7650. // right = lb_emit_conv(p, right, t_u32);
  7651. // break;
  7652. // case 8:
  7653. // left = lb_emit_conv(p, left, t_u64);
  7654. // right = lb_emit_conv(p, right, t_u64);
  7655. // break;
  7656. // default: GB_PANIC("Unknown integer size"); break;
  7657. // }
  7658. // }
  7659. lt = left.type;
  7660. rt = right.type;
  7661. i64 ls = type_size_of(lt);
  7662. i64 rs = type_size_of(rt);
  7663. if (ls < rs) {
  7664. left = lb_emit_conv(p, left, rt);
  7665. } else if (ls > rs) {
  7666. right = lb_emit_conv(p, right, lt);
  7667. } else {
  7668. right = lb_emit_conv(p, right, lt);
  7669. }
  7670. }
  7671. if (is_type_array(a)) {
  7672. Type *tl = base_type(a);
  7673. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  7674. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  7675. TokenKind cmp_op = Token_And;
  7676. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  7677. if (op_kind == Token_NotEq) {
  7678. res = lb_const_bool(p->module, t_llvm_bool, false);
  7679. cmp_op = Token_Or;
  7680. } else if (op_kind == Token_CmpEq) {
  7681. res = lb_const_bool(p->module, t_llvm_bool, true);
  7682. cmp_op = Token_And;
  7683. }
  7684. bool inline_array_arith = type_size_of(tl) <= build_context.max_align;
  7685. i32 count = cast(i32)tl->Array.count;
  7686. if (inline_array_arith) {
  7687. // inline
  7688. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7689. lb_addr_store(p, val, res);
  7690. for (i32 i = 0; i < count; i++) {
  7691. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  7692. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  7693. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7694. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7695. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7696. }
  7697. return lb_addr_load(p, val);
  7698. } else {
  7699. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  7700. // TODO(bill): Test to see if this is actually faster!!!!
  7701. auto args = array_make<lbValue>(permanent_allocator(), 3);
  7702. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  7703. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  7704. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  7705. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  7706. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  7707. return lb_emit_conv(p, res, t_bool);
  7708. } else {
  7709. lbAddr val = lb_add_local_generated(p, t_bool, false);
  7710. lb_addr_store(p, val, res);
  7711. auto loop_data = lb_loop_start(p, count, t_i32);
  7712. {
  7713. lbValue i = loop_data.idx;
  7714. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  7715. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  7716. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  7717. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  7718. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  7719. }
  7720. lb_loop_end(p, loop_data);
  7721. return lb_addr_load(p, val);
  7722. }
  7723. }
  7724. }
  7725. if (is_type_struct(a) && is_type_comparable(a)) {
  7726. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  7727. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  7728. lbValue res = {};
  7729. if (is_type_simple_compare(a)) {
  7730. // TODO(bill): Test to see if this is actually faster!!!!
  7731. auto args = array_make<lbValue>(permanent_allocator(), 3);
  7732. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  7733. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  7734. args[2] = lb_const_int(p->module, t_int, type_size_of(a));
  7735. res = lb_emit_runtime_call(p, "memory_equal", args);
  7736. } else {
  7737. lbValue value = lb_get_equal_proc_for_type(p->module, a);
  7738. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7739. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  7740. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  7741. res = lb_emit_call(p, value, args);
  7742. }
  7743. if (op_kind == Token_NotEq) {
  7744. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  7745. }
  7746. return res;
  7747. }
  7748. if (is_type_string(a)) {
  7749. if (is_type_cstring(a)) {
  7750. left = lb_emit_conv(p, left, t_string);
  7751. right = lb_emit_conv(p, right, t_string);
  7752. }
  7753. char const *runtime_procedure = nullptr;
  7754. switch (op_kind) {
  7755. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  7756. case Token_NotEq: runtime_procedure = "string_ne"; break;
  7757. case Token_Lt: runtime_procedure = "string_lt"; break;
  7758. case Token_Gt: runtime_procedure = "string_gt"; break;
  7759. case Token_LtEq: runtime_procedure = "string_le"; break;
  7760. case Token_GtEq: runtime_procedure = "string_gt"; break;
  7761. }
  7762. GB_ASSERT(runtime_procedure != nullptr);
  7763. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7764. args[0] = left;
  7765. args[1] = right;
  7766. return lb_emit_runtime_call(p, runtime_procedure, args);
  7767. }
  7768. if (is_type_complex(a)) {
  7769. char const *runtime_procedure = "";
  7770. i64 sz = 8*type_size_of(a);
  7771. switch (sz) {
  7772. case 64:
  7773. switch (op_kind) {
  7774. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  7775. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  7776. }
  7777. break;
  7778. case 128:
  7779. switch (op_kind) {
  7780. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  7781. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  7782. }
  7783. break;
  7784. }
  7785. GB_ASSERT(runtime_procedure != nullptr);
  7786. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7787. args[0] = left;
  7788. args[1] = right;
  7789. return lb_emit_runtime_call(p, runtime_procedure, args);
  7790. }
  7791. if (is_type_quaternion(a)) {
  7792. char const *runtime_procedure = "";
  7793. i64 sz = 8*type_size_of(a);
  7794. switch (sz) {
  7795. case 128:
  7796. switch (op_kind) {
  7797. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  7798. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  7799. }
  7800. break;
  7801. case 256:
  7802. switch (op_kind) {
  7803. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  7804. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  7805. }
  7806. break;
  7807. }
  7808. GB_ASSERT(runtime_procedure != nullptr);
  7809. auto args = array_make<lbValue>(permanent_allocator(), 2);
  7810. args[0] = left;
  7811. args[1] = right;
  7812. return lb_emit_runtime_call(p, runtime_procedure, args);
  7813. }
  7814. if (is_type_bit_set(a)) {
  7815. switch (op_kind) {
  7816. case Token_Lt:
  7817. case Token_LtEq:
  7818. case Token_Gt:
  7819. case Token_GtEq:
  7820. {
  7821. Type *it = bit_set_to_int(a);
  7822. lbValue lhs = lb_emit_transmute(p, left, it);
  7823. lbValue rhs = lb_emit_transmute(p, right, it);
  7824. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  7825. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  7826. // (lhs & rhs) == lhs
  7827. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  7828. res.type = t_llvm_bool;
  7829. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  7830. // (lhs & rhs) == rhs
  7831. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  7832. res.type = t_llvm_bool;
  7833. }
  7834. // NOTE(bill): Strict subsets
  7835. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  7836. // res &~ (lhs == rhs)
  7837. lbValue eq = {};
  7838. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  7839. eq.type = t_llvm_bool;
  7840. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  7841. }
  7842. return res;
  7843. }
  7844. case Token_CmpEq:
  7845. case Token_NotEq:
  7846. {
  7847. LLVMIntPredicate pred = {};
  7848. switch (op_kind) {
  7849. case Token_CmpEq: pred = LLVMIntEQ; break;
  7850. case Token_NotEq: pred = LLVMIntNE; break;
  7851. }
  7852. lbValue res = {};
  7853. res.type = t_llvm_bool;
  7854. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7855. return res;
  7856. }
  7857. }
  7858. }
  7859. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  7860. Type *t = left.type;
  7861. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  7862. Type *platform_type = integer_endian_type_to_platform_type(t);
  7863. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  7864. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  7865. left = x;
  7866. right = y;
  7867. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  7868. Type *platform_type = integer_endian_type_to_platform_type(t);
  7869. lbValue x = lb_emit_conv(p, left, platform_type);
  7870. lbValue y = lb_emit_conv(p, right, platform_type);
  7871. left = x;
  7872. right = y;
  7873. }
  7874. }
  7875. a = core_type(left.type);
  7876. b = core_type(right.type);
  7877. lbValue res = {};
  7878. res.type = t_llvm_bool;
  7879. if (is_type_integer(a) ||
  7880. is_type_boolean(a) ||
  7881. is_type_pointer(a) ||
  7882. is_type_proc(a) ||
  7883. is_type_enum(a)) {
  7884. LLVMIntPredicate pred = {};
  7885. if (is_type_unsigned(left.type)) {
  7886. switch (op_kind) {
  7887. case Token_Gt: pred = LLVMIntUGT; break;
  7888. case Token_GtEq: pred = LLVMIntUGE; break;
  7889. case Token_Lt: pred = LLVMIntULT; break;
  7890. case Token_LtEq: pred = LLVMIntULE; break;
  7891. }
  7892. } else {
  7893. switch (op_kind) {
  7894. case Token_Gt: pred = LLVMIntSGT; break;
  7895. case Token_GtEq: pred = LLVMIntSGE; break;
  7896. case Token_Lt: pred = LLVMIntSLT; break;
  7897. case Token_LtEq: pred = LLVMIntSLE; break;
  7898. }
  7899. }
  7900. switch (op_kind) {
  7901. case Token_CmpEq: pred = LLVMIntEQ; break;
  7902. case Token_NotEq: pred = LLVMIntNE; break;
  7903. }
  7904. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7905. } else if (is_type_float(a)) {
  7906. LLVMRealPredicate pred = {};
  7907. switch (op_kind) {
  7908. case Token_CmpEq: pred = LLVMRealOEQ; break;
  7909. case Token_Gt: pred = LLVMRealOGT; break;
  7910. case Token_GtEq: pred = LLVMRealOGE; break;
  7911. case Token_Lt: pred = LLVMRealOLT; break;
  7912. case Token_LtEq: pred = LLVMRealOLE; break;
  7913. case Token_NotEq: pred = LLVMRealONE; break;
  7914. }
  7915. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  7916. } else if (is_type_typeid(a)) {
  7917. LLVMIntPredicate pred = {};
  7918. switch (op_kind) {
  7919. case Token_Gt: pred = LLVMIntUGT; break;
  7920. case Token_GtEq: pred = LLVMIntUGE; break;
  7921. case Token_Lt: pred = LLVMIntULT; break;
  7922. case Token_LtEq: pred = LLVMIntULE; break;
  7923. case Token_CmpEq: pred = LLVMIntEQ; break;
  7924. case Token_NotEq: pred = LLVMIntNE; break;
  7925. }
  7926. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  7927. } else {
  7928. 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)));
  7929. }
  7930. return res;
  7931. }
  7932. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  7933. auto *found = map_get(&m->anonymous_proc_lits, hash_pointer(expr));
  7934. if (found != nullptr) {
  7935. lbValue value = {};
  7936. value.value = (*found)->value;
  7937. value.type = (*found)->type;
  7938. return value;
  7939. }
  7940. ast_node(pl, ProcLit, expr);
  7941. // NOTE(bill): Generate a new name
  7942. // parent$count
  7943. isize name_len = prefix_name.len + 1 + 8 + 1;
  7944. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  7945. i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count;
  7946. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  7947. String name = make_string((u8 *)name_text, name_len-1);
  7948. Type *type = type_of_expr(expr);
  7949. set_procedure_abi_types(type);
  7950. Token token = {};
  7951. token.pos = ast_token(expr).pos;
  7952. token.kind = Token_Ident;
  7953. token.string = name;
  7954. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  7955. e->decl_info = pl->decl;
  7956. lbProcedure *p = lb_create_procedure(m, e);
  7957. lbValue value = {};
  7958. value.value = p->value;
  7959. value.type = p->type;
  7960. array_add(&m->procedures_to_generate, p);
  7961. if (parent != nullptr) {
  7962. array_add(&parent->children, p);
  7963. } else {
  7964. string_map_set(&m->members, name, value);
  7965. }
  7966. map_set(&m->anonymous_proc_lits, hash_pointer(expr), p);
  7967. return value;
  7968. }
  7969. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) {
  7970. lbModule *m = p->module;
  7971. Type *src_type = value.type;
  7972. bool is_ptr = is_type_pointer(src_type);
  7973. bool is_tuple = true;
  7974. Type *tuple = type;
  7975. if (type->kind != Type_Tuple) {
  7976. is_tuple = false;
  7977. tuple = make_optional_ok_type(type);
  7978. }
  7979. lbAddr v = lb_add_local_generated(p, tuple, true);
  7980. if (is_ptr) {
  7981. value = lb_emit_load(p, value);
  7982. }
  7983. Type *src = base_type(type_deref(src_type));
  7984. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  7985. Type *dst = tuple->Tuple.variables[0]->type;
  7986. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  7987. lbValue tag = {};
  7988. lbValue dst_tag = {};
  7989. lbValue cond = {};
  7990. lbValue data = {};
  7991. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  7992. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  7993. if (is_type_union_maybe_pointer(src)) {
  7994. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  7995. } else {
  7996. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  7997. dst_tag = lb_const_union_tag(m, src, dst);
  7998. }
  7999. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  8000. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  8001. if (data.value != nullptr) {
  8002. GB_ASSERT(is_type_union_maybe_pointer(src));
  8003. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  8004. } else {
  8005. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  8006. }
  8007. lb_emit_if(p, cond, ok_block, end_block);
  8008. lb_start_block(p, ok_block);
  8009. if (data.value == nullptr) {
  8010. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  8011. }
  8012. lb_emit_store(p, gep0, data);
  8013. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8014. lb_emit_jump(p, end_block);
  8015. lb_start_block(p, end_block);
  8016. if (!is_tuple) {
  8017. if (do_conversion_check) {
  8018. // NOTE(bill): Panic on invalid conversion
  8019. Type *dst_type = tuple->Tuple.variables[0]->type;
  8020. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8021. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8022. args[0] = ok;
  8023. args[1] = lb_const_string(m, pos.file);
  8024. args[2] = lb_const_int(m, t_int, pos.line);
  8025. args[3] = lb_const_int(m, t_int, pos.column);
  8026. args[4] = lb_typeid(m, src_type);
  8027. args[5] = lb_typeid(m, dst_type);
  8028. args[6] = lb_emit_conv(p, value_, t_rawptr);
  8029. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8030. }
  8031. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  8032. }
  8033. return lb_addr_load(p, v);
  8034. }
  8035. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8036. lbModule *m = p->module;
  8037. Type *src_type = value.type;
  8038. if (is_type_pointer(src_type)) {
  8039. value = lb_emit_load(p, value);
  8040. }
  8041. bool is_tuple = true;
  8042. Type *tuple = type;
  8043. if (type->kind != Type_Tuple) {
  8044. is_tuple = false;
  8045. tuple = make_optional_ok_type(type);
  8046. }
  8047. Type *dst_type = tuple->Tuple.variables[0]->type;
  8048. lbAddr v = lb_add_local_generated(p, tuple, true);
  8049. lbValue dst_typeid = lb_typeid(m, dst_type);
  8050. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  8051. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  8052. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  8053. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  8054. lb_emit_if(p, cond, ok_block, end_block);
  8055. lb_start_block(p, ok_block);
  8056. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  8057. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  8058. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  8059. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  8060. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  8061. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  8062. lb_emit_jump(p, end_block);
  8063. lb_start_block(p, end_block);
  8064. if (!is_tuple) {
  8065. // NOTE(bill): Panic on invalid conversion
  8066. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  8067. auto args = array_make<lbValue>(permanent_allocator(), 7);
  8068. args[0] = ok;
  8069. args[1] = lb_const_string(m, pos.file);
  8070. args[2] = lb_const_int(m, t_int, pos.line);
  8071. args[3] = lb_const_int(m, t_int, pos.column);
  8072. args[4] = any_typeid;
  8073. args[5] = dst_typeid;
  8074. args[6] = lb_emit_struct_ev(p, value, 0);;
  8075. lb_emit_runtime_call(p, "type_assertion_check2", args);
  8076. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  8077. }
  8078. return v;
  8079. }
  8080. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  8081. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  8082. }
  8083. lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  8084. lbModule *m = p->module;
  8085. u64 prev_state_flags = p->module->state_flags;
  8086. defer (p->module->state_flags = prev_state_flags);
  8087. if (expr->state_flags != 0) {
  8088. u64 in = expr->state_flags;
  8089. u64 out = p->module->state_flags;
  8090. if (in & StateFlag_bounds_check) {
  8091. out |= StateFlag_bounds_check;
  8092. out &= ~StateFlag_no_bounds_check;
  8093. } else if (in & StateFlag_no_bounds_check) {
  8094. out |= StateFlag_no_bounds_check;
  8095. out &= ~StateFlag_bounds_check;
  8096. }
  8097. p->module->state_flags = out;
  8098. }
  8099. expr = unparen_expr(expr);
  8100. TokenPos expr_pos = ast_token(expr).pos;
  8101. TypeAndValue tv = type_and_value_of_expr(expr);
  8102. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %.*s(%td:%td)\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), LIT(expr_pos.file), expr_pos.line, expr_pos.column, LIT(p->name), type_to_string(p->type));
  8103. if (tv.value.kind != ExactValue_Invalid) {
  8104. // NOTE(bill): Short on constant values
  8105. return lb_const_value(p->module, tv.type, tv.value);
  8106. }
  8107. switch (expr->kind) {
  8108. case_ast_node(bl, BasicLit, expr);
  8109. TokenPos pos = bl->token.pos;
  8110. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(token_strings[bl->token.kind]));
  8111. case_end;
  8112. case_ast_node(bd, BasicDirective, expr);
  8113. TokenPos pos = bd->token.pos;
  8114. GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name));
  8115. case_end;
  8116. case_ast_node(i, Implicit, expr);
  8117. return lb_addr_load(p, lb_build_addr(p, expr));
  8118. case_end;
  8119. case_ast_node(u, Undef, expr)
  8120. lbValue res = {};
  8121. if (is_type_untyped(tv.type)) {
  8122. res.value = nullptr;
  8123. res.type = t_untyped_undef;
  8124. } else {
  8125. res.value = LLVMGetUndef(lb_type(m, tv.type));
  8126. res.type = tv.type;
  8127. }
  8128. return res;
  8129. case_end;
  8130. case_ast_node(i, Ident, expr);
  8131. Entity *e = entity_from_expr(expr);
  8132. e = strip_entity_wrapping(e);
  8133. GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr));
  8134. if (e->kind == Entity_Builtin) {
  8135. Token token = ast_token(expr);
  8136. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  8137. "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name),
  8138. LIT(token.pos.file), token.pos.line, token.pos.column);
  8139. return {};
  8140. } else if (e->kind == Entity_Nil) {
  8141. lbValue res = {};
  8142. res.value = nullptr;
  8143. res.type = e->type;
  8144. return res;
  8145. }
  8146. GB_ASSERT(e->kind != Entity_ProcGroup);
  8147. auto *found = map_get(&p->module->values, hash_entity(e));
  8148. if (found) {
  8149. auto v = *found;
  8150. // NOTE(bill): This is because pointers are already pointers in LLVM
  8151. if (is_type_proc(v.type)) {
  8152. return v;
  8153. }
  8154. return lb_emit_load(p, v);
  8155. } else if (e != nullptr && e->kind == Entity_Variable) {
  8156. return lb_addr_load(p, lb_build_addr(p, expr));
  8157. }
  8158. gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column);
  8159. String pkg = {};
  8160. if (e->pkg) {
  8161. pkg = e->pkg->name;
  8162. }
  8163. 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);
  8164. return {};
  8165. case_end;
  8166. case_ast_node(de, DerefExpr, expr);
  8167. return lb_addr_load(p, lb_build_addr(p, expr));
  8168. case_end;
  8169. case_ast_node(se, SelectorExpr, expr);
  8170. TypeAndValue tav = type_and_value_of_expr(expr);
  8171. GB_ASSERT(tav.mode != Addressing_Invalid);
  8172. return lb_addr_load(p, lb_build_addr(p, expr));
  8173. case_end;
  8174. case_ast_node(ise, ImplicitSelectorExpr, expr);
  8175. TypeAndValue tav = type_and_value_of_expr(expr);
  8176. GB_ASSERT(tav.mode == Addressing_Constant);
  8177. return lb_const_value(p->module, tv.type, tv.value);
  8178. case_end;
  8179. case_ast_node(se, SelectorCallExpr, expr);
  8180. GB_ASSERT(se->modified_call);
  8181. TypeAndValue tav = type_and_value_of_expr(expr);
  8182. GB_ASSERT(tav.mode != Addressing_Invalid);
  8183. return lb_build_expr(p, se->call);
  8184. case_end;
  8185. case_ast_node(te, TernaryExpr, expr);
  8186. LLVMValueRef incoming_values[2] = {};
  8187. LLVMBasicBlockRef incoming_blocks[2] = {};
  8188. GB_ASSERT(te->y != nullptr);
  8189. lbBlock *then = lb_create_block(p, "if.then");
  8190. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8191. lbBlock *else_ = lb_create_block(p, "if.else");
  8192. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8193. lb_start_block(p, then);
  8194. Type *type = default_type(type_of_expr(expr));
  8195. lb_open_scope(p);
  8196. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8197. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8198. lb_emit_jump(p, done);
  8199. lb_start_block(p, else_);
  8200. lb_open_scope(p);
  8201. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8202. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8203. lb_emit_jump(p, done);
  8204. lb_start_block(p, done);
  8205. lbValue res = {};
  8206. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8207. res.type = type;
  8208. GB_ASSERT(p->curr_block->preds.count >= 2);
  8209. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8210. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8211. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8212. return res;
  8213. case_end;
  8214. case_ast_node(te, TernaryIfExpr, expr);
  8215. LLVMValueRef incoming_values[2] = {};
  8216. LLVMBasicBlockRef incoming_blocks[2] = {};
  8217. GB_ASSERT(te->y != nullptr);
  8218. lbBlock *then = lb_create_block(p, "if.then");
  8219. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  8220. lbBlock *else_ = lb_create_block(p, "if.else");
  8221. lbValue cond = lb_build_cond(p, te->cond, then, else_);
  8222. lb_start_block(p, then);
  8223. Type *type = default_type(type_of_expr(expr));
  8224. lb_open_scope(p);
  8225. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  8226. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8227. lb_emit_jump(p, done);
  8228. lb_start_block(p, else_);
  8229. lb_open_scope(p);
  8230. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  8231. lb_close_scope(p, lbDeferExit_Default, nullptr);
  8232. lb_emit_jump(p, done);
  8233. lb_start_block(p, done);
  8234. lbValue res = {};
  8235. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  8236. res.type = type;
  8237. GB_ASSERT(p->curr_block->preds.count >= 2);
  8238. incoming_blocks[0] = p->curr_block->preds[0]->block;
  8239. incoming_blocks[1] = p->curr_block->preds[1]->block;
  8240. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  8241. return res;
  8242. case_end;
  8243. case_ast_node(te, TernaryWhenExpr, expr);
  8244. TypeAndValue tav = type_and_value_of_expr(te->cond);
  8245. GB_ASSERT(tav.mode == Addressing_Constant);
  8246. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  8247. if (tav.value.value_bool) {
  8248. return lb_build_expr(p, te->x);
  8249. } else {
  8250. return lb_build_expr(p, te->y);
  8251. }
  8252. case_end;
  8253. case_ast_node(ta, TypeAssertion, expr);
  8254. TokenPos pos = ast_token(expr).pos;
  8255. Type *type = tv.type;
  8256. lbValue e = lb_build_expr(p, ta->expr);
  8257. Type *t = type_deref(e.type);
  8258. if (is_type_union(t)) {
  8259. return lb_emit_union_cast(p, e, type, pos);
  8260. } else if (is_type_any(t)) {
  8261. return lb_emit_any_cast(p, e, type, pos);
  8262. } else {
  8263. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8264. }
  8265. case_end;
  8266. case_ast_node(tc, TypeCast, expr);
  8267. lbValue e = lb_build_expr(p, tc->expr);
  8268. switch (tc->token.kind) {
  8269. case Token_cast:
  8270. return lb_emit_conv(p, e, tv.type);
  8271. case Token_transmute:
  8272. return lb_emit_transmute(p, e, tv.type);
  8273. }
  8274. GB_PANIC("Invalid AST TypeCast");
  8275. case_end;
  8276. case_ast_node(ac, AutoCast, expr);
  8277. return lb_build_expr(p, ac->expr);
  8278. case_end;
  8279. case_ast_node(ue, UnaryExpr, expr);
  8280. switch (ue->op.kind) {
  8281. case Token_And: {
  8282. Ast *ue_expr = unparen_expr(ue->expr);
  8283. if (ue_expr->kind == Ast_CompoundLit) {
  8284. lbValue v = lb_build_expr(p, ue->expr);
  8285. Type *type = v.type;
  8286. lbAddr addr = {};
  8287. if (p->is_startup) {
  8288. addr = lb_add_global_generated(p->module, type, v);
  8289. } else {
  8290. addr = lb_add_local_generated(p, type, false);
  8291. }
  8292. lb_addr_store(p, addr, v);
  8293. return addr.addr;
  8294. } else if (ue_expr->kind == Ast_TypeAssertion) {
  8295. GB_ASSERT(is_type_pointer(tv.type));
  8296. ast_node(ta, TypeAssertion, ue_expr);
  8297. TokenPos pos = ast_token(expr).pos;
  8298. Type *type = type_of_expr(ue_expr);
  8299. GB_ASSERT(!is_type_tuple(type));
  8300. lbValue e = lb_build_expr(p, ta->expr);
  8301. Type *t = type_deref(e.type);
  8302. if (is_type_union(t)) {
  8303. lbValue v = e;
  8304. if (!is_type_pointer(v.type)) {
  8305. v = lb_address_from_load_or_generate_local(p, v);
  8306. }
  8307. Type *src_type = type_deref(v.type);
  8308. Type *dst_type = type;
  8309. lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  8310. lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  8311. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  8312. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8313. args[0] = ok;
  8314. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8315. args[2] = lb_const_int(p->module, t_int, pos.line);
  8316. args[3] = lb_const_int(p->module, t_int, pos.column);
  8317. args[4] = lb_typeid(p->module, src_type);
  8318. args[5] = lb_typeid(p->module, dst_type);
  8319. lb_emit_runtime_call(p, "type_assertion_check", args);
  8320. lbValue data_ptr = v;
  8321. return lb_emit_conv(p, data_ptr, tv.type);
  8322. } else if (is_type_any(t)) {
  8323. lbValue v = e;
  8324. if (is_type_pointer(v.type)) {
  8325. v = lb_emit_load(p, v);
  8326. }
  8327. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  8328. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  8329. lbValue id = lb_typeid(p->module, type);
  8330. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  8331. auto args = array_make<lbValue>(permanent_allocator(), 6);
  8332. args[0] = ok;
  8333. args[1] = lb_find_or_add_entity_string(p->module, pos.file);
  8334. args[2] = lb_const_int(p->module, t_int, pos.line);
  8335. args[3] = lb_const_int(p->module, t_int, pos.column);
  8336. args[4] = any_id;
  8337. args[5] = id;
  8338. lb_emit_runtime_call(p, "type_assertion_check", args);
  8339. return lb_emit_conv(p, data_ptr, tv.type);
  8340. } else {
  8341. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  8342. }
  8343. }
  8344. return lb_build_addr_ptr(p, ue->expr);
  8345. }
  8346. default:
  8347. {
  8348. lbValue v = lb_build_expr(p, ue->expr);
  8349. return lb_emit_unary_arith(p, ue->op.kind, v, tv.type);
  8350. }
  8351. }
  8352. case_end;
  8353. case_ast_node(be, BinaryExpr, expr);
  8354. return lb_build_binary_expr(p, expr);
  8355. case_end;
  8356. case_ast_node(pl, ProcLit, expr);
  8357. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  8358. case_end;
  8359. case_ast_node(cl, CompoundLit, expr);
  8360. return lb_addr_load(p, lb_build_addr(p, expr));
  8361. case_end;
  8362. case_ast_node(ce, CallExpr, expr);
  8363. lbValue res = lb_build_call_expr(p, expr);
  8364. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  8365. GB_ASSERT(is_type_tuple(res.type));
  8366. GB_ASSERT(res.type->Tuple.variables.count == 2);
  8367. return lb_emit_struct_ev(p, res, 0);
  8368. }
  8369. return res;
  8370. case_end;
  8371. case_ast_node(se, SliceExpr, expr);
  8372. return lb_addr_load(p, lb_build_addr(p, expr));
  8373. case_end;
  8374. case_ast_node(ie, IndexExpr, expr);
  8375. return lb_addr_load(p, lb_build_addr(p, expr));
  8376. case_end;
  8377. case_ast_node(ia, InlineAsmExpr, expr);
  8378. Type *t = type_of_expr(expr);
  8379. GB_ASSERT(is_type_asm_proc(t));
  8380. String asm_string = {};
  8381. String constraints_string = {};
  8382. TypeAndValue tav;
  8383. tav = type_and_value_of_expr(ia->asm_string);
  8384. GB_ASSERT(is_type_string(tav.type));
  8385. GB_ASSERT(tav.value.kind == ExactValue_String);
  8386. asm_string = tav.value.value_string;
  8387. tav = type_and_value_of_expr(ia->constraints_string);
  8388. GB_ASSERT(is_type_string(tav.type));
  8389. GB_ASSERT(tav.value.kind == ExactValue_String);
  8390. constraints_string = tav.value.value_string;
  8391. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  8392. switch (ia->dialect) {
  8393. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  8394. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  8395. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  8396. default: GB_PANIC("Unhandled inline asm dialect"); break;
  8397. }
  8398. LLVMTypeRef func_type = LLVMGetElementType(lb_type(p->module, t));
  8399. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  8400. cast(char *)asm_string.text, cast(size_t)asm_string.len,
  8401. cast(char *)constraints_string.text, cast(size_t)constraints_string.len,
  8402. ia->has_side_effects, ia->is_align_stack, dialect
  8403. );
  8404. GB_ASSERT(the_asm != nullptr);
  8405. return {the_asm, t};
  8406. case_end;
  8407. }
  8408. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  8409. return {};
  8410. }
  8411. lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  8412. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  8413. String name = e->token.string;
  8414. Entity *parent = e->using_parent;
  8415. Selection sel = lookup_field(parent->type, name, false);
  8416. GB_ASSERT(sel.entity != nullptr);
  8417. lbValue *pv = map_get(&p->module->values, hash_entity(parent));
  8418. lbValue v = {};
  8419. if (pv != nullptr) {
  8420. v = *pv;
  8421. } else {
  8422. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  8423. v = lb_build_addr_ptr(p, e->using_expr);
  8424. }
  8425. GB_ASSERT(v.value != nullptr);
  8426. GB_ASSERT(parent->type == type_deref(v.type));
  8427. return lb_emit_deep_field_gep(p, v, sel);
  8428. }
  8429. lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  8430. GB_ASSERT(e != nullptr);
  8431. if (e->kind == Entity_Constant) {
  8432. Type *t = default_type(type_of_expr(expr));
  8433. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  8434. lbAddr g = lb_add_global_generated(p->module, t, v);
  8435. return g;
  8436. }
  8437. lbValue v = {};
  8438. lbValue *found = map_get(&p->module->values, hash_entity(e));
  8439. if (found) {
  8440. v = *found;
  8441. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  8442. // NOTE(bill): Calculate the using variable every time
  8443. v = lb_get_using_variable(p, e);
  8444. }
  8445. if (v.value == nullptr) {
  8446. error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  8447. LIT(p->name),
  8448. LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  8449. GB_PANIC("Unknown value");
  8450. }
  8451. return lb_addr(v);
  8452. }
  8453. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  8454. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  8455. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  8456. map_type = base_type(map_type);
  8457. GB_ASSERT(map_type->kind == Type_Map);
  8458. Type *key_type = map_type->Map.key;
  8459. Type *val_type = map_type->Map.value;
  8460. // NOTE(bill): Removes unnecessary allocation if split gep
  8461. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  8462. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  8463. lb_emit_store(p, gep0, m);
  8464. i64 entry_size = type_size_of (map_type->Map.entry_type);
  8465. i64 entry_align = type_align_of (map_type->Map.entry_type);
  8466. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  8467. i64 key_size = type_size_of (map_type->Map.key);
  8468. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  8469. i64 value_size = type_size_of (map_type->Map.value);
  8470. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_get_equal_proc_for_type(p->module, key_type));
  8471. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size));
  8472. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align));
  8473. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, key_offset));
  8474. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, key_size));
  8475. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 6), lb_const_int(p->module, t_uintptr, value_offset));
  8476. lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 7), lb_const_int(p->module, t_int, value_size));
  8477. return lb_addr_load(p, h);
  8478. }
  8479. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  8480. if (true) {
  8481. return {};
  8482. }
  8483. lbValue hashed_key = {};
  8484. if (lb_is_const(key)) {
  8485. u64 hash = 0xcbf29ce484222325;
  8486. if (is_type_cstring(key_type)) {
  8487. size_t length = 0;
  8488. char const *text = LLVMGetAsString(key.value, &length);
  8489. hash = fnv64a(text, cast(isize)length);
  8490. } else if (is_type_string(key_type)) {
  8491. unsigned data_indices[] = {0};
  8492. unsigned len_indices[] = {1};
  8493. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  8494. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  8495. isize length = LLVMConstIntGetSExtValue(len);
  8496. char const *text = nullptr;
  8497. if (false && length != 0) {
  8498. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  8499. return {};
  8500. }
  8501. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  8502. size_t ulength = 0;
  8503. text = LLVMGetAsString(data, &ulength);
  8504. gb_printf_err("%td %td %s\n", length, ulength, text);
  8505. length = gb_min(length, cast(isize)ulength);
  8506. }
  8507. hash = fnv64a(text, cast(isize)length);
  8508. } else {
  8509. return {};
  8510. }
  8511. // TODO(bill): other const hash types
  8512. if (build_context.word_size == 4) {
  8513. hash &= 0xffffffffull;
  8514. }
  8515. hashed_key = lb_const_int(m, t_uintptr, hash);
  8516. }
  8517. return hashed_key;
  8518. }
  8519. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  8520. Type *hash_type = t_u64;
  8521. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  8522. lbValue vp = lb_addr_get_ptr(p, v);
  8523. Type *t = base_type(key.type);
  8524. key = lb_emit_conv(p, key, key_type);
  8525. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  8526. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  8527. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  8528. if (hashed_key.value == nullptr) {
  8529. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  8530. auto args = array_make<lbValue>(permanent_allocator(), 2);
  8531. args[0] = key_ptr;
  8532. args[1] = lb_const_int(p->module, t_uintptr, 0);
  8533. hashed_key = lb_emit_call(p, hasher, args);
  8534. }
  8535. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  8536. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  8537. return lb_addr_load(p, v);
  8538. }
  8539. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  8540. lbValue map_key, lbValue map_value, Ast *node) {
  8541. map_type = base_type(map_type);
  8542. GB_ASSERT(map_type->kind == Type_Map);
  8543. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  8544. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  8545. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  8546. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  8547. lb_addr_store(p, value_addr, v);
  8548. auto args = array_make<lbValue>(permanent_allocator(), 4);
  8549. args[0] = h;
  8550. args[1] = key;
  8551. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  8552. args[3] = lb_emit_source_code_location(p, node);
  8553. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  8554. }
  8555. lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  8556. expr = unparen_expr(expr);
  8557. switch (expr->kind) {
  8558. case_ast_node(i, Implicit, expr);
  8559. lbAddr v = {};
  8560. switch (i->kind) {
  8561. case Token_context:
  8562. v = lb_find_or_generate_context_ptr(p);
  8563. break;
  8564. }
  8565. GB_ASSERT(v.addr.value != nullptr);
  8566. return v;
  8567. case_end;
  8568. case_ast_node(i, Ident, expr);
  8569. if (is_blank_ident(expr)) {
  8570. lbAddr val = {};
  8571. return val;
  8572. }
  8573. String name = i->token.string;
  8574. Entity *e = entity_of_node(expr);
  8575. return lb_build_addr_from_entity(p, e, expr);
  8576. case_end;
  8577. case_ast_node(se, SelectorExpr, expr);
  8578. Ast *sel = unparen_expr(se->selector);
  8579. if (sel->kind == Ast_Ident) {
  8580. String selector = sel->Ident.token.string;
  8581. TypeAndValue tav = type_and_value_of_expr(se->expr);
  8582. if (tav.mode == Addressing_Invalid) {
  8583. // NOTE(bill): Imports
  8584. Entity *imp = entity_of_node(se->expr);
  8585. if (imp != nullptr) {
  8586. GB_ASSERT(imp->kind == Entity_ImportName);
  8587. }
  8588. return lb_build_addr(p, unparen_expr(se->selector));
  8589. }
  8590. Type *type = base_type(tav.type);
  8591. if (tav.mode == Addressing_Type) { // Addressing_Type
  8592. Selection sel = lookup_field(type, selector, true);
  8593. Entity *e = sel.entity;
  8594. GB_ASSERT_MSG(e->kind == Entity_Variable, "Entity_%.*s", LIT(entity_strings[e->kind]));
  8595. GB_ASSERT(e->flags & EntityFlag_TypeField);
  8596. String name = e->token.string;
  8597. /*if (name == "names") {
  8598. lbValue ti_ptr = lb_type_info(m, type);
  8599. lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2);
  8600. lbValue names_ptr = nullptr;
  8601. if (is_type_enum(type)) {
  8602. lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  8603. names_ptr = lb_emit_struct_ep(p, enum_info, 1);
  8604. } else if (type->kind == Type_Struct) {
  8605. lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr);
  8606. names_ptr = lb_emit_struct_ep(p, struct_info, 1);
  8607. }
  8608. return ir_addr(names_ptr);
  8609. } else */{
  8610. GB_PANIC("Unhandled TypeField %.*s", LIT(name));
  8611. }
  8612. GB_PANIC("Unreachable");
  8613. }
  8614. Selection sel = lookup_field(type, selector, false);
  8615. GB_ASSERT(sel.entity != nullptr);
  8616. {
  8617. lbAddr addr = lb_build_addr(p, se->expr);
  8618. if (addr.kind == lbAddr_Map) {
  8619. lbValue v = lb_addr_load(p, addr);
  8620. lbValue a = lb_address_from_load_or_generate_local(p, v);
  8621. a = lb_emit_deep_field_gep(p, a, sel);
  8622. return lb_addr(a);
  8623. } else if (addr.kind == lbAddr_Context) {
  8624. GB_ASSERT(sel.index.count > 0);
  8625. if (addr.ctx.sel.index.count >= 0) {
  8626. sel = selection_combine(addr.ctx.sel, sel);
  8627. }
  8628. addr.ctx.sel = sel;
  8629. addr.kind = lbAddr_Context;
  8630. return addr;
  8631. } else if (addr.kind == lbAddr_SoaVariable) {
  8632. lbValue index = addr.soa.index;
  8633. i32 first_index = sel.index[0];
  8634. Selection sub_sel = sel;
  8635. sub_sel.index.data += 1;
  8636. sub_sel.index.count -= 1;
  8637. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  8638. Type *t = base_type(type_deref(addr.addr.type));
  8639. GB_ASSERT(is_type_soa_struct(t));
  8640. // TODO(bill): Bounds check
  8641. if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) {
  8642. lbValue len = lb_soa_struct_len(p, addr.addr);
  8643. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  8644. }
  8645. lbValue item = {};
  8646. if (t->Struct.soa_kind == StructSoa_Fixed) {
  8647. item = lb_emit_array_ep(p, arr, index);
  8648. } else {
  8649. item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index));
  8650. }
  8651. if (sub_sel.index.count > 0) {
  8652. item = lb_emit_deep_field_gep(p, item, sub_sel);
  8653. }
  8654. return lb_addr(item);
  8655. }
  8656. lbValue a = lb_addr_get_ptr(p, addr);
  8657. a = lb_emit_deep_field_gep(p, a, sel);
  8658. return lb_addr(a);
  8659. }
  8660. } else {
  8661. GB_PANIC("Unsupported selector expression");
  8662. }
  8663. case_end;
  8664. case_ast_node(se, SelectorCallExpr, expr);
  8665. GB_ASSERT(se->modified_call);
  8666. TypeAndValue tav = type_and_value_of_expr(expr);
  8667. GB_ASSERT(tav.mode != Addressing_Invalid);
  8668. return lb_build_addr(p, se->call);
  8669. case_end;
  8670. case_ast_node(ta, TypeAssertion, expr);
  8671. TokenPos pos = ast_token(expr).pos;
  8672. lbValue e = lb_build_expr(p, ta->expr);
  8673. Type *t = type_deref(e.type);
  8674. if (is_type_union(t)) {
  8675. Type *type = type_of_expr(expr);
  8676. lbAddr v = lb_add_local_generated(p, type, false);
  8677. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  8678. return v;
  8679. } else if (is_type_any(t)) {
  8680. Type *type = type_of_expr(expr);
  8681. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  8682. } else {
  8683. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  8684. }
  8685. case_end;
  8686. case_ast_node(ue, UnaryExpr, expr);
  8687. switch (ue->op.kind) {
  8688. case Token_And: {
  8689. return lb_build_addr(p, ue->expr);
  8690. }
  8691. default:
  8692. GB_PANIC("Invalid unary expression for lb_build_addr");
  8693. }
  8694. case_end;
  8695. case_ast_node(be, BinaryExpr, expr);
  8696. lbValue v = lb_build_expr(p, expr);
  8697. Type *t = v.type;
  8698. if (is_type_pointer(t)) {
  8699. return lb_addr(v);
  8700. }
  8701. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  8702. case_end;
  8703. case_ast_node(ie, IndexExpr, expr);
  8704. Type *t = base_type(type_of_expr(ie->expr));
  8705. bool deref = is_type_pointer(t);
  8706. t = base_type(type_deref(t));
  8707. if (is_type_soa_struct(t)) {
  8708. // SOA STRUCTURES!!!!
  8709. lbValue val = lb_build_addr_ptr(p, ie->expr);
  8710. if (deref) {
  8711. val = lb_emit_load(p, val);
  8712. }
  8713. lbValue index = lb_build_expr(p, ie->index);
  8714. return lb_addr_soa_variable(val, index, ie->index);
  8715. }
  8716. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  8717. // SOA Structures for slices/dynamic arrays
  8718. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  8719. lbValue field = lb_build_expr(p, ie->expr);
  8720. lbValue index = lb_build_expr(p, ie->index);
  8721. if (!build_context.no_bounds_check) {
  8722. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  8723. // GB_ASSERT(LLVMIsALoadInst(field.value));
  8724. // lbValue a = {};
  8725. // a.value = LLVMGetOperand(field.value, 0);
  8726. // a.type = alloc_type_pointer(field.type);
  8727. // irInstr *b = &a->Instr;
  8728. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  8729. // lbValue base_struct = b->StructElementPtr.address;
  8730. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  8731. // lbValue len = ir_soa_struct_len(p, base_struct);
  8732. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8733. }
  8734. lbValue val = lb_emit_ptr_offset(p, field, index);
  8735. return lb_addr(val);
  8736. }
  8737. if (!is_type_indexable(t)) {
  8738. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8739. if (found != nullptr) {
  8740. if (found->kind == TypeAtomOp_index_get) {
  8741. return lb_build_addr(p, found->node);
  8742. } else if (found->kind == TypeAtomOp_index_get_ptr) {
  8743. return lb_addr(lb_build_expr(p, found->node));
  8744. } else if (found->kind == TypeAtomOp_index_set) {
  8745. lbValue ptr = lb_build_addr_ptr(p, ie->expr);
  8746. if (deref) {
  8747. ptr = lb_emit_load(p, ptr);
  8748. }
  8749. lbAddr addr = {lbAddr_AtomOp_index_set};
  8750. addr.addr = ptr;
  8751. addr.index_set.index = lb_build_expr(p, ie->index);
  8752. addr.index_set.node = found->node;
  8753. return addr;
  8754. }
  8755. }
  8756. }
  8757. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  8758. if (is_type_map(t)) {
  8759. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  8760. if (deref) {
  8761. map_val = lb_emit_load(p, map_val);
  8762. }
  8763. lbValue key = lb_build_expr(p, ie->index);
  8764. key = lb_emit_conv(p, key, t->Map.key);
  8765. Type *result_type = type_of_expr(expr);
  8766. return lb_addr_map(map_val, key, t, result_type);
  8767. }
  8768. switch (t->kind) {
  8769. case Type_Array: {
  8770. lbValue array = {};
  8771. array = lb_build_addr_ptr(p, ie->expr);
  8772. if (deref) {
  8773. array = lb_emit_load(p, array);
  8774. }
  8775. lbValue index = lb_build_expr(p, ie->index);
  8776. index = lb_emit_conv(p, index, t_int);
  8777. lbValue elem = lb_emit_array_ep(p, array, index);
  8778. auto index_tv = type_and_value_of_expr(ie->index);
  8779. if (index_tv.mode != Addressing_Constant) {
  8780. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  8781. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8782. }
  8783. return lb_addr(elem);
  8784. }
  8785. case Type_EnumeratedArray: {
  8786. lbValue array = {};
  8787. array = lb_build_addr_ptr(p, ie->expr);
  8788. if (deref) {
  8789. array = lb_emit_load(p, array);
  8790. }
  8791. Type *index_type = t->EnumeratedArray.index;
  8792. auto index_tv = type_and_value_of_expr(ie->index);
  8793. lbValue index = {};
  8794. if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) {
  8795. if (index_tv.mode == Addressing_Constant) {
  8796. ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value);
  8797. index = lb_const_value(p->module, index_type, idx);
  8798. } else {
  8799. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8800. index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type);
  8801. }
  8802. } else {
  8803. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8804. }
  8805. lbValue elem = lb_emit_array_ep(p, array, index);
  8806. if (index_tv.mode != Addressing_Constant) {
  8807. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  8808. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8809. }
  8810. return lb_addr(elem);
  8811. }
  8812. case Type_Slice: {
  8813. lbValue slice = {};
  8814. slice = lb_build_expr(p, ie->expr);
  8815. if (deref) {
  8816. slice = lb_emit_load(p, slice);
  8817. }
  8818. lbValue elem = lb_slice_elem(p, slice);
  8819. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8820. lbValue len = lb_slice_len(p, slice);
  8821. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8822. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8823. return lb_addr(v);
  8824. }
  8825. case Type_RelativeSlice: {
  8826. lbAddr slice_addr = {};
  8827. if (deref) {
  8828. slice_addr = lb_addr(lb_build_expr(p, ie->expr));
  8829. } else {
  8830. slice_addr = lb_build_addr(p, ie->expr);
  8831. }
  8832. lbValue slice = lb_addr_load(p, slice_addr);
  8833. lbValue elem = lb_slice_elem(p, slice);
  8834. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8835. lbValue len = lb_slice_len(p, slice);
  8836. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8837. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8838. return lb_addr(v);
  8839. }
  8840. case Type_DynamicArray: {
  8841. lbValue dynamic_array = {};
  8842. dynamic_array = lb_build_expr(p, ie->expr);
  8843. if (deref) {
  8844. dynamic_array = lb_emit_load(p, dynamic_array);
  8845. }
  8846. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  8847. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  8848. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8849. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8850. lbValue v = lb_emit_ptr_offset(p, elem, index);
  8851. return lb_addr(v);
  8852. }
  8853. case Type_Basic: { // Basic_string
  8854. lbValue str;
  8855. lbValue elem;
  8856. lbValue len;
  8857. lbValue index;
  8858. str = lb_build_expr(p, ie->expr);
  8859. if (deref) {
  8860. str = lb_emit_load(p, str);
  8861. }
  8862. elem = lb_string_elem(p, str);
  8863. len = lb_string_len(p, str);
  8864. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  8865. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  8866. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  8867. }
  8868. }
  8869. case_end;
  8870. case_ast_node(se, SliceExpr, expr);
  8871. lbValue low = lb_const_int(p->module, t_int, 0);
  8872. lbValue high = {};
  8873. if (se->low != nullptr) low = lb_build_expr(p, se->low);
  8874. if (se->high != nullptr) high = lb_build_expr(p, se->high);
  8875. bool no_indices = se->low == nullptr && se->high == nullptr;
  8876. {
  8877. Type *type = base_type(type_of_expr(se->expr));
  8878. if (type->kind == Type_Struct && !is_type_soa_struct(type)) {
  8879. TypeAtomOpTable *atom_op_table = type->Struct.atom_op_table;
  8880. if (atom_op_table != nullptr && atom_op_table->op[TypeAtomOp_slice]) {
  8881. AtomOpMapEntry *found = map_get(&p->module->info->atom_op_map, hash_pointer(expr));
  8882. if (found) {
  8883. lbValue base = lb_build_expr(p, found->node);
  8884. Type *slice_type = base.type;
  8885. lbValue len = lb_slice_len(p, base);
  8886. if (high.value == nullptr) high = len;
  8887. if (!no_indices) {
  8888. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8889. }
  8890. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8891. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8892. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8893. lb_fill_slice(p, slice, elem, new_len);
  8894. return slice;
  8895. }
  8896. }
  8897. }
  8898. }
  8899. lbAddr addr = lb_build_addr(p, se->expr);
  8900. lbValue base = lb_addr_load(p, addr);
  8901. Type *type = base_type(base.type);
  8902. if (is_type_pointer(type)) {
  8903. type = base_type(type_deref(type));
  8904. addr = lb_addr(base);
  8905. base = lb_addr_load(p, addr);
  8906. }
  8907. switch (type->kind) {
  8908. case Type_Slice: {
  8909. Type *slice_type = type;
  8910. lbValue len = lb_slice_len(p, base);
  8911. if (high.value == nullptr) high = len;
  8912. if (!no_indices) {
  8913. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8914. }
  8915. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  8916. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8917. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8918. lb_fill_slice(p, slice, elem, new_len);
  8919. return slice;
  8920. }
  8921. case Type_RelativeSlice:
  8922. GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load");
  8923. break;
  8924. case Type_DynamicArray: {
  8925. Type *elem_type = type->DynamicArray.elem;
  8926. Type *slice_type = alloc_type_slice(elem_type);
  8927. lbValue len = lb_dynamic_array_len(p, base);
  8928. if (high.value == nullptr) high = len;
  8929. if (!no_indices) {
  8930. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8931. }
  8932. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  8933. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8934. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8935. lb_fill_slice(p, slice, elem, new_len);
  8936. return slice;
  8937. }
  8938. case Type_Array: {
  8939. Type *slice_type = alloc_type_slice(type->Array.elem);
  8940. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  8941. if (high.value == nullptr) high = len;
  8942. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  8943. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  8944. if (!low_const || !high_const) {
  8945. if (!no_indices) {
  8946. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8947. }
  8948. }
  8949. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  8950. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8951. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  8952. lb_fill_slice(p, slice, elem, new_len);
  8953. return slice;
  8954. }
  8955. case Type_Basic: {
  8956. GB_ASSERT(type == t_string);
  8957. lbValue len = lb_string_len(p, base);
  8958. if (high.value == nullptr) high = len;
  8959. if (!no_indices) {
  8960. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8961. }
  8962. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  8963. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8964. lbAddr str = lb_add_local_generated(p, t_string, false);
  8965. lb_fill_string(p, str, elem, new_len);
  8966. return str;
  8967. }
  8968. case Type_Struct:
  8969. if (is_type_soa_struct(type)) {
  8970. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  8971. if (high.value == nullptr) high = len;
  8972. if (!no_indices) {
  8973. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  8974. }
  8975. #if 1
  8976. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  8977. if (type->Struct.soa_kind == StructSoa_Fixed) {
  8978. i32 field_count = cast(i32)type->Struct.fields.count;
  8979. for (i32 i = 0; i < field_count; i++) {
  8980. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8981. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  8982. field_src = lb_emit_array_ep(p, field_src, low);
  8983. lb_emit_store(p, field_dst, field_src);
  8984. }
  8985. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  8986. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  8987. lb_emit_store(p, len_dst, new_len);
  8988. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  8989. if (no_indices) {
  8990. lb_addr_store(p, dst, base);
  8991. } else {
  8992. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  8993. for (i32 i = 0; i < field_count; i++) {
  8994. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  8995. lbValue field_src = lb_emit_struct_ev(p, base, i);
  8996. field_src = lb_emit_ptr_offset(p, field_src, low);
  8997. lb_emit_store(p, field_dst, field_src);
  8998. }
  8999. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9000. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9001. lb_emit_store(p, len_dst, new_len);
  9002. }
  9003. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  9004. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  9005. for (i32 i = 0; i < field_count; i++) {
  9006. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  9007. lbValue field_src = lb_emit_struct_ev(p, base, i);
  9008. field_src = lb_emit_ptr_offset(p, field_src, low);
  9009. lb_emit_store(p, field_dst, field_src);
  9010. }
  9011. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  9012. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  9013. lb_emit_store(p, len_dst, new_len);
  9014. }
  9015. return dst;
  9016. #endif
  9017. }
  9018. break;
  9019. }
  9020. GB_PANIC("Unknown slicable type");
  9021. case_end;
  9022. case_ast_node(de, DerefExpr, expr);
  9023. if (is_type_relative_pointer(type_of_expr(de->expr))) {
  9024. lbAddr addr = lb_build_addr(p, de->expr);
  9025. addr.relative.deref = true;
  9026. return addr;
  9027. }
  9028. lbValue addr = lb_build_expr(p, de->expr);
  9029. return lb_addr(addr);
  9030. case_end;
  9031. case_ast_node(ce, CallExpr, expr);
  9032. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  9033. lbValue e = lb_build_expr(p, expr);
  9034. lbAddr v = lb_add_local_generated(p, e.type, false);
  9035. lb_addr_store(p, v, e);
  9036. return v;
  9037. case_end;
  9038. case_ast_node(cl, CompoundLit, expr);
  9039. Type *type = type_of_expr(expr);
  9040. Type *bt = base_type(type);
  9041. lbAddr v = lb_add_local_generated(p, type, true);
  9042. Type *et = nullptr;
  9043. switch (bt->kind) {
  9044. case Type_Array: et = bt->Array.elem; break;
  9045. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  9046. case Type_Slice: et = bt->Slice.elem; break;
  9047. case Type_BitSet: et = bt->BitSet.elem; break;
  9048. case Type_SimdVector: et = bt->SimdVector.elem; break;
  9049. }
  9050. String proc_name = {};
  9051. if (p->entity) {
  9052. proc_name = p->entity->token.string;
  9053. }
  9054. TokenPos pos = ast_token(expr).pos;
  9055. switch (bt->kind) {
  9056. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  9057. case Type_Struct: {
  9058. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  9059. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  9060. bool is_raw_union = is_type_raw_union(bt);
  9061. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  9062. TypeStruct *st = &bt->Struct;
  9063. if (cl->elems.count > 0) {
  9064. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9065. for_array(field_index, cl->elems) {
  9066. Ast *elem = cl->elems[field_index];
  9067. lbValue field_expr = {};
  9068. Entity *field = nullptr;
  9069. isize index = field_index;
  9070. if (elem->kind == Ast_FieldValue) {
  9071. ast_node(fv, FieldValue, elem);
  9072. String name = fv->field->Ident.token.string;
  9073. Selection sel = lookup_field(bt, name, false);
  9074. index = sel.index[0];
  9075. elem = fv->value;
  9076. TypeAndValue tav = type_and_value_of_expr(elem);
  9077. } else {
  9078. TypeAndValue tav = type_and_value_of_expr(elem);
  9079. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index);
  9080. index = sel.index[0];
  9081. }
  9082. field = st->fields[index];
  9083. Type *ft = field->type;
  9084. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  9085. continue;
  9086. }
  9087. field_expr = lb_build_expr(p, elem);
  9088. Type *fet = field_expr.type;
  9089. GB_ASSERT(fet->kind != Type_Tuple);
  9090. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  9091. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  9092. GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet));
  9093. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9094. lb_emit_store_union_variant(p, gep, field_expr, fet);
  9095. } else {
  9096. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9097. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9098. lb_emit_store(p, gep, fv);
  9099. }
  9100. }
  9101. }
  9102. break;
  9103. }
  9104. case Type_Map: {
  9105. if (cl->elems.count == 0) {
  9106. break;
  9107. }
  9108. {
  9109. auto args = array_make<lbValue>(permanent_allocator(), 3);
  9110. args[0] = lb_gen_map_header(p, v.addr, type);
  9111. args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count);
  9112. args[2] = lb_emit_source_code_location(p, proc_name, pos);
  9113. lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  9114. }
  9115. for_array(field_index, cl->elems) {
  9116. Ast *elem = cl->elems[field_index];
  9117. ast_node(fv, FieldValue, elem);
  9118. lbValue key = lb_build_expr(p, fv->field);
  9119. lbValue value = lb_build_expr(p, fv->value);
  9120. lb_insert_dynamic_map_key_and_value(p, v, type, key, value, elem);
  9121. }
  9122. break;
  9123. }
  9124. case Type_Array: {
  9125. if (cl->elems.count > 0) {
  9126. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9127. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9128. // NOTE(bill): Separate value, gep, store into their own chunks
  9129. for_array(i, cl->elems) {
  9130. Ast *elem = cl->elems[i];
  9131. if (elem->kind == Ast_FieldValue) {
  9132. ast_node(fv, FieldValue, elem);
  9133. if (lb_is_elem_const(fv->value, et)) {
  9134. continue;
  9135. }
  9136. if (is_ast_range(fv->field)) {
  9137. ast_node(ie, BinaryExpr, fv->field);
  9138. TypeAndValue lo_tav = ie->left->tav;
  9139. TypeAndValue hi_tav = ie->right->tav;
  9140. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9141. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9142. TokenKind op = ie->op.kind;
  9143. i64 lo = exact_value_to_i64(lo_tav.value);
  9144. i64 hi = exact_value_to_i64(hi_tav.value);
  9145. if (op == Token_Ellipsis) {
  9146. hi += 1;
  9147. }
  9148. lbValue value = lb_build_expr(p, fv->value);
  9149. for (i64 k = lo; k < hi; k++) {
  9150. lbCompoundLitElemTempData data = {};
  9151. data.value = value;
  9152. data.elem_index = cast(i32)k;
  9153. array_add(&temp_data, data);
  9154. }
  9155. } else {
  9156. auto tav = fv->field->tav;
  9157. GB_ASSERT(tav.mode == Addressing_Constant);
  9158. i64 index = exact_value_to_i64(tav.value);
  9159. lbValue value = lb_build_expr(p, fv->value);
  9160. lbCompoundLitElemTempData data = {};
  9161. data.value = lb_emit_conv(p, value, et);
  9162. data.expr = fv->value;
  9163. data.elem_index = cast(i32)index;
  9164. array_add(&temp_data, data);
  9165. }
  9166. } else {
  9167. if (lb_is_elem_const(elem, et)) {
  9168. continue;
  9169. }
  9170. lbCompoundLitElemTempData data = {};
  9171. data.expr = elem;
  9172. data.elem_index = cast(i32)i;
  9173. array_add(&temp_data, data);
  9174. }
  9175. }
  9176. for_array(i, temp_data) {
  9177. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index);
  9178. }
  9179. for_array(i, temp_data) {
  9180. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9181. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9182. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9183. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9184. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9185. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9186. lbValue field_expr = temp_data[i].value;
  9187. Ast *expr = temp_data[i].expr;
  9188. p->return_ptr_hint_value = temp_data[i].gep;
  9189. p->return_ptr_hint_ast = unparen_expr(expr);
  9190. if (field_expr.value == nullptr) {
  9191. field_expr = lb_build_expr(p, expr);
  9192. }
  9193. Type *t = field_expr.type;
  9194. GB_ASSERT(t->kind != Type_Tuple);
  9195. lbValue ev = lb_emit_conv(p, field_expr, et);
  9196. if (!p->return_ptr_hint_used) {
  9197. temp_data[i].value = ev;
  9198. }
  9199. }
  9200. for_array(i, temp_data) {
  9201. if (temp_data[i].value.value != nullptr) {
  9202. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9203. }
  9204. }
  9205. }
  9206. break;
  9207. }
  9208. case Type_EnumeratedArray: {
  9209. if (cl->elems.count > 0) {
  9210. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9211. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9212. // NOTE(bill): Separate value, gep, store into their own chunks
  9213. for_array(i, cl->elems) {
  9214. Ast *elem = cl->elems[i];
  9215. if (elem->kind == Ast_FieldValue) {
  9216. ast_node(fv, FieldValue, elem);
  9217. if (lb_is_elem_const(fv->value, et)) {
  9218. continue;
  9219. }
  9220. if (is_ast_range(fv->field)) {
  9221. ast_node(ie, BinaryExpr, fv->field);
  9222. TypeAndValue lo_tav = ie->left->tav;
  9223. TypeAndValue hi_tav = ie->right->tav;
  9224. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9225. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9226. TokenKind op = ie->op.kind;
  9227. i64 lo = exact_value_to_i64(lo_tav.value);
  9228. i64 hi = exact_value_to_i64(hi_tav.value);
  9229. if (op == Token_Ellipsis) {
  9230. hi += 1;
  9231. }
  9232. lbValue value = lb_build_expr(p, fv->value);
  9233. for (i64 k = lo; k < hi; k++) {
  9234. lbCompoundLitElemTempData data = {};
  9235. data.value = value;
  9236. data.elem_index = cast(i32)k;
  9237. array_add(&temp_data, data);
  9238. }
  9239. } else {
  9240. auto tav = fv->field->tav;
  9241. GB_ASSERT(tav.mode == Addressing_Constant);
  9242. i64 index = exact_value_to_i64(tav.value);
  9243. lbValue value = lb_build_expr(p, fv->value);
  9244. lbCompoundLitElemTempData data = {};
  9245. data.value = lb_emit_conv(p, value, et);
  9246. data.expr = fv->value;
  9247. data.elem_index = cast(i32)index;
  9248. array_add(&temp_data, data);
  9249. }
  9250. } else {
  9251. if (lb_is_elem_const(elem, et)) {
  9252. continue;
  9253. }
  9254. lbCompoundLitElemTempData data = {};
  9255. data.expr = elem;
  9256. data.elem_index = cast(i32)i;
  9257. array_add(&temp_data, data);
  9258. }
  9259. }
  9260. i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value);
  9261. for_array(i, temp_data) {
  9262. i32 index = temp_data[i].elem_index - index_offset;
  9263. temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index);
  9264. }
  9265. for_array(i, temp_data) {
  9266. auto return_ptr_hint_ast = p->return_ptr_hint_ast;
  9267. auto return_ptr_hint_value = p->return_ptr_hint_value;
  9268. auto return_ptr_hint_used = p->return_ptr_hint_used;
  9269. defer (p->return_ptr_hint_ast = return_ptr_hint_ast);
  9270. defer (p->return_ptr_hint_value = return_ptr_hint_value);
  9271. defer (p->return_ptr_hint_used = return_ptr_hint_used);
  9272. lbValue field_expr = temp_data[i].value;
  9273. Ast *expr = temp_data[i].expr;
  9274. p->return_ptr_hint_value = temp_data[i].gep;
  9275. p->return_ptr_hint_ast = unparen_expr(expr);
  9276. if (field_expr.value == nullptr) {
  9277. field_expr = lb_build_expr(p, expr);
  9278. }
  9279. Type *t = field_expr.type;
  9280. GB_ASSERT(t->kind != Type_Tuple);
  9281. lbValue ev = lb_emit_conv(p, field_expr, et);
  9282. if (!p->return_ptr_hint_used) {
  9283. temp_data[i].value = ev;
  9284. }
  9285. }
  9286. for_array(i, temp_data) {
  9287. if (temp_data[i].value.value != nullptr) {
  9288. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9289. }
  9290. }
  9291. }
  9292. break;
  9293. }
  9294. case Type_Slice: {
  9295. if (cl->elems.count > 0) {
  9296. Type *elem_type = bt->Slice.elem;
  9297. Type *elem_ptr_type = alloc_type_pointer(elem_type);
  9298. Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type);
  9299. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  9300. lbValue data = lb_slice_elem(p, slice);
  9301. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  9302. for_array(i, cl->elems) {
  9303. Ast *elem = cl->elems[i];
  9304. if (elem->kind == Ast_FieldValue) {
  9305. ast_node(fv, FieldValue, elem);
  9306. if (lb_is_elem_const(fv->value, et)) {
  9307. continue;
  9308. }
  9309. if (is_ast_range(fv->field)) {
  9310. ast_node(ie, BinaryExpr, fv->field);
  9311. TypeAndValue lo_tav = ie->left->tav;
  9312. TypeAndValue hi_tav = ie->right->tav;
  9313. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9314. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9315. TokenKind op = ie->op.kind;
  9316. i64 lo = exact_value_to_i64(lo_tav.value);
  9317. i64 hi = exact_value_to_i64(hi_tav.value);
  9318. if (op == Token_Ellipsis) {
  9319. hi += 1;
  9320. }
  9321. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9322. for (i64 k = lo; k < hi; k++) {
  9323. lbCompoundLitElemTempData data = {};
  9324. data.value = value;
  9325. data.elem_index = cast(i32)k;
  9326. array_add(&temp_data, data);
  9327. }
  9328. } else {
  9329. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9330. i64 index = exact_value_to_i64(fv->field->tav.value);
  9331. lbValue field_expr = lb_build_expr(p, fv->value);
  9332. GB_ASSERT(!is_type_tuple(field_expr.type));
  9333. lbValue ev = lb_emit_conv(p, field_expr, et);
  9334. lbCompoundLitElemTempData data = {};
  9335. data.value = ev;
  9336. data.elem_index = cast(i32)index;
  9337. array_add(&temp_data, data);
  9338. }
  9339. } else {
  9340. if (lb_is_elem_const(elem, et)) {
  9341. continue;
  9342. }
  9343. lbValue field_expr = lb_build_expr(p, elem);
  9344. GB_ASSERT(!is_type_tuple(field_expr.type));
  9345. lbValue ev = lb_emit_conv(p, field_expr, et);
  9346. lbCompoundLitElemTempData data = {};
  9347. data.value = ev;
  9348. data.elem_index = cast(i32)i;
  9349. array_add(&temp_data, data);
  9350. }
  9351. }
  9352. for_array(i, temp_data) {
  9353. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  9354. }
  9355. for_array(i, temp_data) {
  9356. lb_emit_store(p, temp_data[i].gep, temp_data[i].value);
  9357. }
  9358. {
  9359. lbValue count = {};
  9360. count.type = t_int;
  9361. if (lb_is_const(slice)) {
  9362. unsigned indices[1] = {1};
  9363. count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices));
  9364. } else {
  9365. count.value = LLVMBuildExtractValue(p->builder, slice.value, 1, "");
  9366. }
  9367. lb_fill_slice(p, v, data, count);
  9368. }
  9369. }
  9370. break;
  9371. }
  9372. case Type_DynamicArray: {
  9373. if (cl->elems.count == 0) {
  9374. break;
  9375. }
  9376. Type *et = bt->DynamicArray.elem;
  9377. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  9378. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  9379. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  9380. {
  9381. auto args = array_make<lbValue>(permanent_allocator(), 5);
  9382. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  9383. args[1] = size;
  9384. args[2] = align;
  9385. args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste?
  9386. args[4] = lb_emit_source_code_location(p, proc_name, pos);
  9387. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  9388. }
  9389. lbValue items = lb_generate_local_array(p, et, item_count);
  9390. // lbValue items = lb_generate_global_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr);
  9391. for_array(i, cl->elems) {
  9392. Ast *elem = cl->elems[i];
  9393. if (elem->kind == Ast_FieldValue) {
  9394. ast_node(fv, FieldValue, elem);
  9395. if (is_ast_range(fv->field)) {
  9396. ast_node(ie, BinaryExpr, fv->field);
  9397. TypeAndValue lo_tav = ie->left->tav;
  9398. TypeAndValue hi_tav = ie->right->tav;
  9399. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  9400. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  9401. TokenKind op = ie->op.kind;
  9402. i64 lo = exact_value_to_i64(lo_tav.value);
  9403. i64 hi = exact_value_to_i64(hi_tav.value);
  9404. if (op == Token_Ellipsis) {
  9405. hi += 1;
  9406. }
  9407. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  9408. for (i64 k = lo; k < hi; k++) {
  9409. lbValue ep = lb_emit_array_epi(p, items, cast(i32)k);
  9410. lb_emit_store(p, ep, value);
  9411. }
  9412. } else {
  9413. GB_ASSERT(fv->field->tav.mode == Addressing_Constant);
  9414. i64 field_index = exact_value_to_i64(fv->field->tav.value);
  9415. lbValue ev = lb_build_expr(p, fv->value);
  9416. lbValue value = lb_emit_conv(p, ev, et);
  9417. lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index);
  9418. lb_emit_store(p, ep, value);
  9419. }
  9420. } else {
  9421. lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et);
  9422. lbValue ep = lb_emit_array_epi(p, items, cast(i32)i);
  9423. lb_emit_store(p, ep, value);
  9424. }
  9425. }
  9426. {
  9427. auto args = array_make<lbValue>(permanent_allocator(), 6);
  9428. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  9429. args[1] = size;
  9430. args[2] = align;
  9431. args[3] = lb_emit_conv(p, items, t_rawptr);
  9432. args[4] = lb_const_int(p->module, t_int, item_count);
  9433. args[5] = lb_emit_source_code_location(p, proc_name, pos);
  9434. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  9435. }
  9436. break;
  9437. }
  9438. case Type_Basic: {
  9439. GB_ASSERT(is_type_any(bt));
  9440. if (cl->elems.count > 0) {
  9441. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9442. String field_names[2] = {
  9443. str_lit("data"),
  9444. str_lit("id"),
  9445. };
  9446. Type *field_types[2] = {
  9447. t_rawptr,
  9448. t_typeid,
  9449. };
  9450. for_array(field_index, cl->elems) {
  9451. Ast *elem = cl->elems[field_index];
  9452. lbValue field_expr = {};
  9453. isize index = field_index;
  9454. if (elem->kind == Ast_FieldValue) {
  9455. ast_node(fv, FieldValue, elem);
  9456. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  9457. index = sel.index[0];
  9458. elem = fv->value;
  9459. } else {
  9460. TypeAndValue tav = type_and_value_of_expr(elem);
  9461. Selection sel = lookup_field(bt, field_names[field_index], false);
  9462. index = sel.index[0];
  9463. }
  9464. field_expr = lb_build_expr(p, elem);
  9465. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  9466. Type *ft = field_types[index];
  9467. lbValue fv = lb_emit_conv(p, field_expr, ft);
  9468. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  9469. lb_emit_store(p, gep, fv);
  9470. }
  9471. }
  9472. break;
  9473. }
  9474. case Type_BitSet: {
  9475. i64 sz = type_size_of(type);
  9476. if (cl->elems.count > 0 && sz > 0) {
  9477. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  9478. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  9479. for_array(i, cl->elems) {
  9480. Ast *elem = cl->elems[i];
  9481. GB_ASSERT(elem->kind != Ast_FieldValue);
  9482. if (lb_is_elem_const(elem, et)) {
  9483. continue;
  9484. }
  9485. lbValue expr = lb_build_expr(p, elem);
  9486. GB_ASSERT(expr.type->kind != Type_Tuple);
  9487. Type *it = bit_set_to_int(bt);
  9488. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  9489. lbValue e = lb_emit_conv(p, expr, it);
  9490. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  9491. e = lb_emit_arith(p, Token_Shl, one, e, it);
  9492. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  9493. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  9494. new_value = lb_emit_transmute(p, new_value, type);
  9495. lb_addr_store(p, v, new_value);
  9496. }
  9497. }
  9498. break;
  9499. }
  9500. }
  9501. return v;
  9502. case_end;
  9503. case_ast_node(tc, TypeCast, expr);
  9504. Type *type = type_of_expr(expr);
  9505. lbValue x = lb_build_expr(p, tc->expr);
  9506. lbValue e = {};
  9507. switch (tc->token.kind) {
  9508. case Token_cast:
  9509. e = lb_emit_conv(p, x, type);
  9510. break;
  9511. case Token_transmute:
  9512. e = lb_emit_transmute(p, x, type);
  9513. break;
  9514. default:
  9515. GB_PANIC("Invalid AST TypeCast");
  9516. }
  9517. lbAddr v = lb_add_local_generated(p, type, false);
  9518. lb_addr_store(p, v, e);
  9519. return v;
  9520. case_end;
  9521. case_ast_node(ac, AutoCast, expr);
  9522. return lb_build_addr(p, ac->expr);
  9523. case_end;
  9524. }
  9525. TokenPos token_pos = ast_token(expr).pos;
  9526. GB_PANIC("Unexpected address expression\n"
  9527. "\tAst: %.*s @ "
  9528. "%.*s(%td:%td)\n",
  9529. LIT(ast_strings[expr->kind]),
  9530. LIT(token_pos.file), token_pos.line, token_pos.column);
  9531. return {};
  9532. }
  9533. void lb_init_module(lbModule *m, Checker *c) {
  9534. m->info = &c->info;
  9535. m->ctx = LLVMGetGlobalContext();
  9536. m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx);
  9537. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  9538. m->state_flags = 0;
  9539. m->state_flags |= StateFlag_bounds_check;
  9540. gb_mutex_init(&m->mutex);
  9541. gbAllocator a = heap_allocator();
  9542. map_init(&m->types, a);
  9543. map_init(&m->llvm_types, a);
  9544. map_init(&m->values, a);
  9545. string_map_init(&m->members, a);
  9546. map_init(&m->procedure_values, a);
  9547. string_map_init(&m->procedures, a);
  9548. string_map_init(&m->const_strings, a);
  9549. map_init(&m->anonymous_proc_lits, a);
  9550. map_init(&m->function_type_map, a);
  9551. map_init(&m->equal_procs, a);
  9552. map_init(&m->hasher_procs, a);
  9553. array_init(&m->procedures_to_generate, a);
  9554. array_init(&m->foreign_library_paths, a);
  9555. map_init(&m->debug_values, a);
  9556. }
  9557. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  9558. if (global_error_collector.count != 0) {
  9559. return false;
  9560. }
  9561. isize tc = c->parser->total_token_count;
  9562. if (tc < 2) {
  9563. return false;
  9564. }
  9565. String init_fullpath = c->parser->init_fullpath;
  9566. if (build_context.out_filepath.len == 0) {
  9567. gen->output_name = remove_directory_from_path(init_fullpath);
  9568. gen->output_name = remove_extension_from_path(gen->output_name);
  9569. gen->output_name = string_trim_whitespace(gen->output_name);
  9570. if (gen->output_name.len == 0) {
  9571. gen->output_name = c->info.init_scope->pkg->name;
  9572. }
  9573. gen->output_base = gen->output_name;
  9574. } else {
  9575. gen->output_name = build_context.out_filepath;
  9576. gen->output_name = string_trim_whitespace(gen->output_name);
  9577. if (gen->output_name.len == 0) {
  9578. gen->output_name = c->info.init_scope->pkg->name;
  9579. }
  9580. isize pos = string_extension_position(gen->output_name);
  9581. if (pos < 0) {
  9582. gen->output_base = gen->output_name;
  9583. } else {
  9584. gen->output_base = substring(gen->output_name, 0, pos);
  9585. }
  9586. }
  9587. gbAllocator ha = heap_allocator();
  9588. array_init(&gen->output_object_paths, ha);
  9589. gen->output_base = path_to_full_path(ha, gen->output_base);
  9590. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  9591. output_file_path = gb_string_appendc(output_file_path, ".obj");
  9592. defer (gb_string_free(output_file_path));
  9593. gen->info = &c->info;
  9594. lb_init_module(&gen->module, c);
  9595. return true;
  9596. }
  9597. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  9598. GB_ASSERT(type != nullptr);
  9599. type = default_type(type);
  9600. isize max_len = 7+8+1;
  9601. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  9602. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index);
  9603. m->global_generated_index++;
  9604. String name = make_string(str, len-1);
  9605. Scope *scope = nullptr;
  9606. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  9607. lbValue g = {};
  9608. g.type = alloc_type_pointer(type);
  9609. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  9610. if (value.value != nullptr) {
  9611. GB_ASSERT(LLVMIsConstant(value.value));
  9612. LLVMSetInitializer(g.value, value.value);
  9613. } else {
  9614. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  9615. }
  9616. lb_add_entity(m, e, g);
  9617. lb_add_member(m, name, g);
  9618. return lb_addr(g);
  9619. }
  9620. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  9621. AstPackage *p = m->info->runtime_package;
  9622. Entity *e = scope_lookup_current(p->scope, name);
  9623. lbValue *found = map_get(&m->values, hash_entity(e));
  9624. GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name));
  9625. lbValue value = *found;
  9626. return value;
  9627. }
  9628. lbValue lb_get_type_info_ptr(lbModule *m, Type *type) {
  9629. i32 index = cast(i32)lb_type_info_index(m->info, type);
  9630. GB_ASSERT(index >= 0);
  9631. // gb_printf_err("%d %s\n", index, type_to_string(type));
  9632. LLVMValueRef indices[2] = {
  9633. LLVMConstInt(lb_type(m, t_int), 0, false),
  9634. LLVMConstInt(lb_type(m, t_int), index, false),
  9635. };
  9636. lbValue res = {};
  9637. res.type = t_type_info_ptr;
  9638. res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices));
  9639. return res;
  9640. }
  9641. lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) {
  9642. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index);
  9643. lb_global_type_info_member_types_index += cast(i32)count;
  9644. return offset;
  9645. }
  9646. lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) {
  9647. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index);
  9648. lb_global_type_info_member_names_index += cast(i32)count;
  9649. return offset;
  9650. }
  9651. lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) {
  9652. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index);
  9653. lb_global_type_info_member_offsets_index += cast(i32)count;
  9654. return offset;
  9655. }
  9656. lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) {
  9657. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index);
  9658. lb_global_type_info_member_usings_index += cast(i32)count;
  9659. return offset;
  9660. }
  9661. lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) {
  9662. lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index);
  9663. lb_global_type_info_member_tags_index += cast(i32)count;
  9664. return offset;
  9665. }
  9666. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  9667. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  9668. return lb_addr_get_ptr(p, addr);
  9669. }
  9670. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  9671. Token token = {Token_Ident};
  9672. isize name_len = prefix.len + 1 + 20;
  9673. auto suffix_id = cast(unsigned long long)id;
  9674. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  9675. gb_snprintf(text, name_len,
  9676. "%.*s-%llu", LIT(prefix), suffix_id);
  9677. text[name_len] = 0;
  9678. String s = make_string_c(text);
  9679. Type *t = alloc_type_array(elem_type, count);
  9680. lbValue g = {};
  9681. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  9682. g.type = alloc_type_pointer(t);
  9683. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  9684. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  9685. string_map_set(&m->members, s, g);
  9686. return g;
  9687. }
  9688. void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data
  9689. lbModule *m = p->module;
  9690. LLVMContextRef ctx = m->ctx;
  9691. CheckerInfo *info = m->info;
  9692. {
  9693. // NOTE(bill): Set the type_table slice with the global backing array
  9694. lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table"));
  9695. Type *type = base_type(lb_addr_type(lb_global_type_info_data));
  9696. GB_ASSERT(is_type_array(type));
  9697. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  9698. LLVMValueRef values[2] = {
  9699. LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)),
  9700. LLVMConstInt(lb_type(m, t_int), type->Array.count, true),
  9701. };
  9702. LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false);
  9703. LLVMSetInitializer(global_type_table.value, slice);
  9704. }
  9705. // Useful types
  9706. Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64));
  9707. Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string));
  9708. Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags"));
  9709. Type *t_type_info_flags = type_info_flags_entity->type;
  9710. i32 type_info_member_types_index = 0;
  9711. i32 type_info_member_names_index = 0;
  9712. i32 type_info_member_offsets_index = 0;
  9713. for_array(type_info_type_index, info->type_info_types) {
  9714. Type *t = info->type_info_types[type_info_type_index];
  9715. if (t == nullptr || t == t_invalid) {
  9716. continue;
  9717. }
  9718. isize entry_index = lb_type_info_index(info, t, false);
  9719. if (entry_index <= 0) {
  9720. continue;
  9721. }
  9722. lbValue tag = {};
  9723. lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index);
  9724. lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 4);
  9725. lbValue type_info_flags = lb_const_int(p->module, t_type_info_flags, type_info_flags_of_type(t));
  9726. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t)));
  9727. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t)));
  9728. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), type_info_flags);
  9729. lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 3), lb_typeid(m, t));
  9730. switch (t->kind) {
  9731. case Type_Named: {
  9732. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr);
  9733. LLVMValueRef pkg_name = nullptr;
  9734. if (t->Named.type_name->pkg) {
  9735. pkg_name = lb_const_string(m, t->Named.type_name->pkg->name).value;
  9736. } else {
  9737. pkg_name = LLVMConstNull(lb_type(m, t_string));
  9738. }
  9739. String proc_name = {};
  9740. if (t->Named.type_name->parent_proc_decl) {
  9741. DeclInfo *decl = t->Named.type_name->parent_proc_decl;
  9742. if (decl->entity && decl->entity->kind == Entity_Procedure) {
  9743. proc_name = decl->entity->token.string;
  9744. }
  9745. }
  9746. TokenPos pos = t->Named.type_name->token.pos;
  9747. lbValue loc = lb_emit_source_code_location(p, proc_name, pos);
  9748. LLVMValueRef vals[4] = {
  9749. lb_const_string(p->module, t->Named.type_name->token.string).value,
  9750. lb_get_type_info_ptr(m, t->Named.base).value,
  9751. pkg_name,
  9752. loc.value
  9753. };
  9754. lbValue res = {};
  9755. res.type = type_deref(tag.type);
  9756. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9757. lb_emit_store(p, tag, res);
  9758. break;
  9759. }
  9760. case Type_Basic:
  9761. switch (t->Basic.kind) {
  9762. case Basic_bool:
  9763. case Basic_b8:
  9764. case Basic_b16:
  9765. case Basic_b32:
  9766. case Basic_b64:
  9767. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr);
  9768. break;
  9769. case Basic_i8:
  9770. case Basic_u8:
  9771. case Basic_i16:
  9772. case Basic_u16:
  9773. case Basic_i32:
  9774. case Basic_u32:
  9775. case Basic_i64:
  9776. case Basic_u64:
  9777. case Basic_i128:
  9778. case Basic_u128:
  9779. case Basic_i16le:
  9780. case Basic_u16le:
  9781. case Basic_i32le:
  9782. case Basic_u32le:
  9783. case Basic_i64le:
  9784. case Basic_u64le:
  9785. case Basic_i128le:
  9786. case Basic_u128le:
  9787. case Basic_i16be:
  9788. case Basic_u16be:
  9789. case Basic_i32be:
  9790. case Basic_u32be:
  9791. case Basic_i64be:
  9792. case Basic_u64be:
  9793. case Basic_i128be:
  9794. case Basic_u128be:
  9795. case Basic_int:
  9796. case Basic_uint:
  9797. case Basic_uintptr: {
  9798. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr);
  9799. lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0);
  9800. // NOTE(bill): This is matches the runtime layout
  9801. u8 endianness_value = 0;
  9802. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9803. endianness_value = 1;
  9804. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9805. endianness_value = 2;
  9806. }
  9807. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9808. LLVMValueRef vals[2] = {
  9809. is_signed.value,
  9810. endianness.value,
  9811. };
  9812. lbValue res = {};
  9813. res.type = type_deref(tag.type);
  9814. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9815. lb_emit_store(p, tag, res);
  9816. break;
  9817. }
  9818. case Basic_rune:
  9819. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr);
  9820. break;
  9821. // case Basic_f16:
  9822. case Basic_f32:
  9823. case Basic_f64:
  9824. case Basic_f32le:
  9825. case Basic_f64le:
  9826. case Basic_f32be:
  9827. case Basic_f64be:
  9828. {
  9829. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr);
  9830. // NOTE(bill): This is matches the runtime layout
  9831. u8 endianness_value = 0;
  9832. if (t->Basic.flags & BasicFlag_EndianLittle) {
  9833. endianness_value = 1;
  9834. } else if (t->Basic.flags & BasicFlag_EndianBig) {
  9835. endianness_value = 2;
  9836. }
  9837. lbValue endianness = lb_const_int(m, t_u8, endianness_value);
  9838. LLVMValueRef vals[1] = {
  9839. endianness.value,
  9840. };
  9841. lbValue res = {};
  9842. res.type = type_deref(tag.type);
  9843. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9844. lb_emit_store(p, tag, res);
  9845. }
  9846. break;
  9847. // case Basic_complex32:
  9848. case Basic_complex64:
  9849. case Basic_complex128:
  9850. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr);
  9851. break;
  9852. case Basic_quaternion128:
  9853. case Basic_quaternion256:
  9854. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr);
  9855. break;
  9856. case Basic_rawptr:
  9857. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9858. break;
  9859. case Basic_string:
  9860. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9861. break;
  9862. case Basic_cstring:
  9863. {
  9864. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr);
  9865. LLVMValueRef vals[1] = {
  9866. lb_const_bool(m, t_bool, true).value,
  9867. };
  9868. lbValue res = {};
  9869. res.type = type_deref(tag.type);
  9870. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9871. lb_emit_store(p, tag, res);
  9872. }
  9873. break;
  9874. case Basic_any:
  9875. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr);
  9876. break;
  9877. case Basic_typeid:
  9878. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr);
  9879. break;
  9880. }
  9881. break;
  9882. case Type_Pointer: {
  9883. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr);
  9884. lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem);
  9885. LLVMValueRef vals[1] = {
  9886. gep.value,
  9887. };
  9888. lbValue res = {};
  9889. res.type = type_deref(tag.type);
  9890. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9891. lb_emit_store(p, tag, res);
  9892. break;
  9893. }
  9894. case Type_Array: {
  9895. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr);
  9896. i64 ez = type_size_of(t->Array.elem);
  9897. LLVMValueRef vals[3] = {
  9898. lb_get_type_info_ptr(m, t->Array.elem).value,
  9899. lb_const_int(m, t_int, ez).value,
  9900. lb_const_int(m, t_int, t->Array.count).value,
  9901. };
  9902. lbValue res = {};
  9903. res.type = type_deref(tag.type);
  9904. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9905. lb_emit_store(p, tag, res);
  9906. break;
  9907. }
  9908. case Type_EnumeratedArray: {
  9909. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr);
  9910. LLVMValueRef vals[6] = {
  9911. lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value,
  9912. lb_get_type_info_ptr(m, t->EnumeratedArray.index).value,
  9913. lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value,
  9914. lb_const_int(m, t_int, t->EnumeratedArray.count).value,
  9915. // Unions
  9916. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9917. LLVMConstNull(lb_type(m, t_type_info_enum_value)),
  9918. };
  9919. lbValue res = {};
  9920. res.type = type_deref(tag.type);
  9921. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9922. lb_emit_store(p, tag, res);
  9923. // NOTE(bill): Union assignment
  9924. lbValue min_value = lb_emit_struct_ep(p, tag, 4);
  9925. lbValue max_value = lb_emit_struct_ep(p, tag, 5);
  9926. lbValue min_v = lb_const_value(m, t_i64, t->EnumeratedArray.min_value);
  9927. lbValue max_v = lb_const_value(m, t_i64, t->EnumeratedArray.max_value);
  9928. lb_emit_store(p, min_value, min_v);
  9929. lb_emit_store(p, max_value, max_v);
  9930. break;
  9931. }
  9932. case Type_DynamicArray: {
  9933. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr);
  9934. LLVMValueRef vals[2] = {
  9935. lb_get_type_info_ptr(m, t->DynamicArray.elem).value,
  9936. lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value,
  9937. };
  9938. lbValue res = {};
  9939. res.type = type_deref(tag.type);
  9940. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9941. lb_emit_store(p, tag, res);
  9942. break;
  9943. }
  9944. case Type_Slice: {
  9945. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr);
  9946. LLVMValueRef vals[2] = {
  9947. lb_get_type_info_ptr(m, t->Slice.elem).value,
  9948. lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value,
  9949. };
  9950. lbValue res = {};
  9951. res.type = type_deref(tag.type);
  9952. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9953. lb_emit_store(p, tag, res);
  9954. break;
  9955. }
  9956. case Type_Proc: {
  9957. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr);
  9958. LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9959. LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr));
  9960. if (t->Proc.params != nullptr) {
  9961. params = lb_get_type_info_ptr(m, t->Proc.params).value;
  9962. }
  9963. if (t->Proc.results != nullptr) {
  9964. results = lb_get_type_info_ptr(m, t->Proc.results).value;
  9965. }
  9966. LLVMValueRef vals[4] = {
  9967. params,
  9968. results,
  9969. lb_const_bool(m, t_bool, t->Proc.variadic).value,
  9970. lb_const_int(m, t_u8, t->Proc.calling_convention).value,
  9971. };
  9972. lbValue res = {};
  9973. res.type = type_deref(tag.type);
  9974. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  9975. lb_emit_store(p, tag, res);
  9976. break;
  9977. }
  9978. case Type_Tuple: {
  9979. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr);
  9980. lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count);
  9981. lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count);
  9982. for_array(i, t->Tuple.variables) {
  9983. // NOTE(bill): offset is not used for tuples
  9984. Entity *f = t->Tuple.variables[i];
  9985. lbValue index = lb_const_int(m, t_int, i);
  9986. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  9987. // TODO(bill): Make this constant if possible, 'lb_const_store' does not work
  9988. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  9989. if (f->token.string.len > 0) {
  9990. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  9991. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  9992. }
  9993. }
  9994. lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count);
  9995. LLVMValueRef types_slice = llvm_const_slice(memory_types, count);
  9996. LLVMValueRef names_slice = llvm_const_slice(memory_names, count);
  9997. LLVMValueRef vals[2] = {
  9998. types_slice,
  9999. names_slice,
  10000. };
  10001. lbValue res = {};
  10002. res.type = type_deref(tag.type);
  10003. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10004. lb_emit_store(p, tag, res);
  10005. break;
  10006. }
  10007. case Type_Enum:
  10008. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr);
  10009. {
  10010. GB_ASSERT(t->Enum.base_type != nullptr);
  10011. // 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));
  10012. LLVMValueRef vals[3] = {};
  10013. vals[0] = lb_type_info(m, t->Enum.base_type).value;
  10014. if (t->Enum.fields.count > 0) {
  10015. auto fields = t->Enum.fields;
  10016. lbValue name_array = lb_generate_global_array(m, t_string, fields.count,
  10017. str_lit("$enum_names"), cast(i64)entry_index);
  10018. lbValue value_array = lb_generate_global_array(m, t_type_info_enum_value, fields.count,
  10019. str_lit("$enum_values"), cast(i64)entry_index);
  10020. LLVMValueRef *name_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10021. LLVMValueRef *value_values = gb_alloc_array(temporary_allocator(), LLVMValueRef, fields.count);
  10022. GB_ASSERT(is_type_integer(t->Enum.base_type));
  10023. LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t));
  10024. LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8);
  10025. for_array(i, fields) {
  10026. name_values[i] = lb_const_string(m, fields[i]->token.string).value;
  10027. value_values[i] = lb_const_value(m, t_i64, fields[i]->Constant.value).value;
  10028. }
  10029. LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count);
  10030. LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count);
  10031. LLVMSetInitializer(name_array.value, name_init);
  10032. LLVMSetInitializer(value_array.value, value_init);
  10033. lbValue v_count = lb_const_int(m, t_int, fields.count);
  10034. vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count);
  10035. vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count);
  10036. } else {
  10037. vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type));
  10038. vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type));
  10039. }
  10040. lbValue res = {};
  10041. res.type = type_deref(tag.type);
  10042. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10043. lb_emit_store(p, tag, res);
  10044. }
  10045. break;
  10046. case Type_Union: {
  10047. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr);
  10048. {
  10049. LLVMValueRef vals[6] = {};
  10050. isize variant_count = gb_max(0, t->Union.variants.count);
  10051. lbValue memory_types = lb_type_info_member_types_offset(p, variant_count);
  10052. // NOTE(bill): Zeroth is nil so ignore it
  10053. for (isize variant_index = 0; variant_index < variant_count; variant_index++) {
  10054. Type *vt = t->Union.variants[variant_index];
  10055. lbValue tip = lb_get_type_info_ptr(m, vt);
  10056. lbValue index = lb_const_int(m, t_int, variant_index);
  10057. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10058. lb_emit_store(p, type_info, lb_type_info(m, vt));
  10059. }
  10060. lbValue count = lb_const_int(m, t_int, variant_count);
  10061. vals[0] = llvm_const_slice(memory_types, count);
  10062. i64 tag_size = union_tag_size(t);
  10063. i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size);
  10064. if (tag_size > 0) {
  10065. vals[1] = lb_const_int(m, t_uintptr, tag_offset).value;
  10066. vals[2] = lb_type_info(m, union_tag_type(t)).value;
  10067. } else {
  10068. vals[1] = lb_const_int(m, t_uintptr, 0).value;
  10069. vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr));
  10070. }
  10071. vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value;
  10072. vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value;
  10073. vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value;
  10074. lbValue res = {};
  10075. res.type = type_deref(tag.type);
  10076. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10077. lb_emit_store(p, tag, res);
  10078. }
  10079. break;
  10080. }
  10081. case Type_Struct: {
  10082. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr);
  10083. LLVMValueRef vals[12] = {};
  10084. {
  10085. lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed);
  10086. lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union);
  10087. lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0);
  10088. vals[5] = is_packed.value;
  10089. vals[6] = is_raw_union.value;
  10090. vals[7] = is_custom_align.value;
  10091. if (is_type_comparable(t) && !is_type_simple_compare(t)) {
  10092. vals[8] = lb_get_equal_proc_for_type(m, t).value;
  10093. }
  10094. if (t->Struct.soa_kind != StructSoa_None) {
  10095. lbValue kind = lb_emit_struct_ep(p, tag, 9);
  10096. Type *kind_type = type_deref(kind.type);
  10097. lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind));
  10098. lbValue soa_type = lb_type_info(m, t->Struct.soa_elem);
  10099. lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count);
  10100. vals[9] = soa_kind.value;
  10101. vals[10] = soa_type.value;
  10102. vals[11] = soa_len.value;
  10103. }
  10104. }
  10105. isize count = t->Struct.fields.count;
  10106. if (count > 0) {
  10107. lbValue memory_types = lb_type_info_member_types_offset (p, count);
  10108. lbValue memory_names = lb_type_info_member_names_offset (p, count);
  10109. lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count);
  10110. lbValue memory_usings = lb_type_info_member_usings_offset (p, count);
  10111. lbValue memory_tags = lb_type_info_member_tags_offset (p, count);
  10112. type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet
  10113. for (isize source_index = 0; source_index < count; source_index++) {
  10114. // TODO(bill): Order fields in source order not layout order
  10115. Entity *f = t->Struct.fields[source_index];
  10116. lbValue tip = lb_get_type_info_ptr(m, f->type);
  10117. i64 foffset = 0;
  10118. if (!t->Struct.is_raw_union) {
  10119. foffset = t->Struct.offsets[f->Variable.field_index];
  10120. }
  10121. GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field);
  10122. lbValue index = lb_const_int(m, t_int, source_index);
  10123. lbValue type_info = lb_emit_ptr_offset(p, memory_types, index);
  10124. lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index);
  10125. lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index);
  10126. lb_emit_store(p, type_info, lb_type_info(m, f->type));
  10127. if (f->token.string.len > 0) {
  10128. lbValue name = lb_emit_ptr_offset(p, memory_names, index);
  10129. lb_emit_store(p, name, lb_const_string(m, f->token.string));
  10130. }
  10131. lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset));
  10132. lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0));
  10133. if (t->Struct.tags.count > 0) {
  10134. String tag_string = t->Struct.tags[source_index];
  10135. if (tag_string.len > 0) {
  10136. lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index);
  10137. lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string));
  10138. }
  10139. }
  10140. }
  10141. lbValue cv = lb_const_int(m, t_int, count);
  10142. vals[0] = llvm_const_slice(memory_types, cv);
  10143. vals[1] = llvm_const_slice(memory_names, cv);
  10144. vals[2] = llvm_const_slice(memory_offsets, cv);
  10145. vals[3] = llvm_const_slice(memory_usings, cv);
  10146. vals[4] = llvm_const_slice(memory_tags, cv);
  10147. }
  10148. for (isize i = 0; i < gb_count_of(vals); i++) {
  10149. if (vals[i] == nullptr) {
  10150. vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i)));
  10151. }
  10152. }
  10153. lbValue res = {};
  10154. res.type = type_deref(tag.type);
  10155. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10156. lb_emit_store(p, tag, res);
  10157. break;
  10158. }
  10159. case Type_Map: {
  10160. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr);
  10161. init_map_internal_types(t);
  10162. LLVMValueRef vals[5] = {
  10163. lb_get_type_info_ptr(m, t->Map.key).value,
  10164. lb_get_type_info_ptr(m, t->Map.value).value,
  10165. lb_get_type_info_ptr(m, t->Map.generated_struct_type).value,
  10166. lb_get_equal_proc_for_type(m, t->Map.key).value,
  10167. lb_get_hasher_proc_for_type(m, t->Map.key).value
  10168. };
  10169. lbValue res = {};
  10170. res.type = type_deref(tag.type);
  10171. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10172. lb_emit_store(p, tag, res);
  10173. break;
  10174. }
  10175. case Type_BitSet:
  10176. {
  10177. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr);
  10178. GB_ASSERT(is_type_typed(t->BitSet.elem));
  10179. LLVMValueRef vals[4] = {
  10180. lb_get_type_info_ptr(m, t->BitSet.elem).value,
  10181. LLVMConstNull(lb_type(m, t_type_info_ptr)),
  10182. lb_const_int(m, t_i64, t->BitSet.lower).value,
  10183. lb_const_int(m, t_i64, t->BitSet.upper).value,
  10184. };
  10185. if (t->BitSet.underlying != nullptr) {
  10186. vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value;
  10187. }
  10188. lbValue res = {};
  10189. res.type = type_deref(tag.type);
  10190. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10191. lb_emit_store(p, tag, res);
  10192. }
  10193. break;
  10194. case Type_SimdVector:
  10195. {
  10196. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr);
  10197. LLVMValueRef vals[4] = {};
  10198. if (t->SimdVector.is_x86_mmx) {
  10199. vals[3] = lb_const_bool(m, t_bool, true).value;
  10200. } else {
  10201. vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value;
  10202. vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value;
  10203. vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value;
  10204. }
  10205. lbValue res = {};
  10206. res.type = type_deref(tag.type);
  10207. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10208. lb_emit_store(p, tag, res);
  10209. }
  10210. break;
  10211. case Type_RelativePointer:
  10212. {
  10213. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_pointer_ptr);
  10214. LLVMValueRef vals[2] = {
  10215. lb_get_type_info_ptr(m, t->RelativePointer.pointer_type).value,
  10216. lb_get_type_info_ptr(m, t->RelativePointer.base_integer).value,
  10217. };
  10218. lbValue res = {};
  10219. res.type = type_deref(tag.type);
  10220. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10221. lb_emit_store(p, tag, res);
  10222. }
  10223. break;
  10224. case Type_RelativeSlice:
  10225. {
  10226. tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr);
  10227. LLVMValueRef vals[2] = {
  10228. lb_get_type_info_ptr(m, t->RelativeSlice.slice_type).value,
  10229. lb_get_type_info_ptr(m, t->RelativeSlice.base_integer).value,
  10230. };
  10231. lbValue res = {};
  10232. res.type = type_deref(tag.type);
  10233. res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals));
  10234. lb_emit_store(p, tag, res);
  10235. }
  10236. break;
  10237. }
  10238. if (tag.value != nullptr) {
  10239. Type *tag_type = type_deref(tag.type);
  10240. GB_ASSERT(is_type_named(tag_type));
  10241. // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type);
  10242. lb_emit_store_union_variant_tag(p, variant_ptr, tag_type);
  10243. } else {
  10244. if (t != t_llvm_bool) {
  10245. GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t));
  10246. }
  10247. }
  10248. }
  10249. }
  10250. void lb_generate_code(lbGenerator *gen) {
  10251. #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0)
  10252. TIME_SECTION("LLVM Initializtion");
  10253. lbModule *m = &gen->module;
  10254. LLVMModuleRef mod = gen->module.mod;
  10255. CheckerInfo *info = gen->info;
  10256. auto *min_dep_set = &info->minimum_dependency_set;
  10257. LLVMInitializeAllTargetInfos();
  10258. LLVMInitializeAllTargets();
  10259. LLVMInitializeAllTargetMCs();
  10260. LLVMInitializeAllAsmPrinters();
  10261. LLVMInitializeAllAsmParsers();
  10262. LLVMInitializeAllDisassemblers();
  10263. LLVMInitializeNativeTarget();
  10264. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  10265. char const *target_data_layout = alloc_cstring(permanent_allocator(), build_context.metrics.target_data_layout);
  10266. LLVMSetTarget(mod, target_triple);
  10267. LLVMTargetRef target = {};
  10268. char *llvm_error = nullptr;
  10269. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  10270. GB_ASSERT(target != nullptr);
  10271. TIME_SECTION("LLVM Create Target Machine");
  10272. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  10273. if (build_context.metrics.arch == TargetArch_wasm32) {
  10274. code_mode = LLVMCodeModelJITDefault;
  10275. }
  10276. char const *host_cpu_name = LLVMGetHostCPUName();
  10277. char const *llvm_cpu = "generic";
  10278. char const *llvm_features = "";
  10279. if (build_context.microarch.len != 0) {
  10280. if (build_context.microarch == "native") {
  10281. llvm_cpu = host_cpu_name;
  10282. } else {
  10283. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  10284. }
  10285. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  10286. llvm_features = LLVMGetHostCPUFeatures();
  10287. }
  10288. }
  10289. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  10290. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  10291. switch (build_context.optimization_level) {
  10292. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  10293. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  10294. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  10295. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  10296. }
  10297. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, llvm_cpu, llvm_features, code_gen_level, LLVMRelocDefault, code_mode);
  10298. defer (LLVMDisposeTargetMachine(target_machine));
  10299. LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine));
  10300. { // Debug Info
  10301. for_array(i, info->files.entries) {
  10302. AstFile *f = info->files.entries[i].value;
  10303. String fullpath = f->fullpath;
  10304. String filename = filename_from_path(fullpath);
  10305. String directory = directory_from_path(fullpath);
  10306. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  10307. cast(char const *)filename.text, filename.len,
  10308. cast(char const *)directory.text, directory.len);
  10309. map_set(&m->debug_values, hash_pointer(f), res);
  10310. f->llvm_metadata = res;
  10311. }
  10312. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC,
  10313. cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata,
  10314. "odin", 4,
  10315. false, "", 0,
  10316. 1, "", 0,
  10317. LLVMDWARFEmissionFull, 0, true,
  10318. true
  10319. #if LLVM_VERSION_MAJOR > 10
  10320. , "", 0,
  10321. "", 0
  10322. #endif
  10323. );
  10324. }
  10325. TIME_SECTION("LLVM Global Variables");
  10326. {
  10327. { // Add type info data
  10328. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  10329. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  10330. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  10331. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  10332. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10333. LLVMSetLinkage(g, LLVMInternalLinkage);
  10334. lbValue value = {};
  10335. value.value = g;
  10336. value.type = alloc_type_pointer(t);
  10337. lb_global_type_info_data = lb_addr(value);
  10338. }
  10339. { // Type info member buffer
  10340. // NOTE(bill): Removes need for heap allocation by making it global memory
  10341. isize count = 0;
  10342. for_array(entry_index, m->info->type_info_types) {
  10343. Type *t = m->info->type_info_types[entry_index];
  10344. isize index = lb_type_info_index(m->info, t, false);
  10345. if (index < 0) {
  10346. continue;
  10347. }
  10348. switch (t->kind) {
  10349. case Type_Union:
  10350. count += t->Union.variants.count;
  10351. break;
  10352. case Type_Struct:
  10353. count += t->Struct.fields.count;
  10354. break;
  10355. case Type_Tuple:
  10356. count += t->Tuple.variables.count;
  10357. break;
  10358. }
  10359. }
  10360. if (count > 0) {
  10361. {
  10362. char const *name = LB_TYPE_INFO_TYPES_NAME;
  10363. Type *t = alloc_type_array(t_type_info_ptr, count);
  10364. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10365. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10366. LLVMSetLinkage(g, LLVMInternalLinkage);
  10367. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  10368. }
  10369. {
  10370. char const *name = LB_TYPE_INFO_NAMES_NAME;
  10371. Type *t = alloc_type_array(t_string, count);
  10372. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10373. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10374. LLVMSetLinkage(g, LLVMInternalLinkage);
  10375. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  10376. }
  10377. {
  10378. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  10379. Type *t = alloc_type_array(t_uintptr, count);
  10380. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10381. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10382. LLVMSetLinkage(g, LLVMInternalLinkage);
  10383. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  10384. }
  10385. {
  10386. char const *name = LB_TYPE_INFO_USINGS_NAME;
  10387. Type *t = alloc_type_array(t_bool, count);
  10388. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10389. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10390. LLVMSetLinkage(g, LLVMInternalLinkage);
  10391. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  10392. }
  10393. {
  10394. char const *name = LB_TYPE_INFO_TAGS_NAME;
  10395. Type *t = alloc_type_array(t_string, count);
  10396. LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name);
  10397. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  10398. LLVMSetLinkage(g, LLVMInternalLinkage);
  10399. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  10400. }
  10401. }
  10402. }
  10403. }
  10404. isize global_variable_max_count = 0;
  10405. Entity *entry_point = info->entry_point;
  10406. bool has_dll_main = false;
  10407. bool has_win_main = false;
  10408. for_array(i, info->entities) {
  10409. Entity *e = info->entities[i];
  10410. String name = e->token.string;
  10411. bool is_global = e->pkg != nullptr;
  10412. if (e->kind == Entity_Variable) {
  10413. global_variable_max_count++;
  10414. } else if (e->kind == Entity_Procedure && !is_global) {
  10415. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  10416. GB_ASSERT(e == entry_point);
  10417. // entry_point = e;
  10418. }
  10419. if (e->Procedure.is_export ||
  10420. (e->Procedure.link_name.len > 0) ||
  10421. ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) {
  10422. if (!has_dll_main && name == "DllMain") {
  10423. has_dll_main = true;
  10424. } else if (!has_win_main && name == "WinMain") {
  10425. has_win_main = true;
  10426. }
  10427. }
  10428. }
  10429. }
  10430. struct GlobalVariable {
  10431. lbValue var;
  10432. lbValue init;
  10433. DeclInfo *decl;
  10434. bool is_initialized;
  10435. };
  10436. auto global_variables = array_make<GlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  10437. for_array(i, info->variable_init_order) {
  10438. DeclInfo *d = info->variable_init_order[i];
  10439. Entity *e = d->entity;
  10440. if ((e->scope->flags & ScopeFlag_File) == 0) {
  10441. continue;
  10442. }
  10443. if (!ptr_set_exists(min_dep_set, e)) {
  10444. continue;
  10445. }
  10446. DeclInfo *decl = decl_info_of_entity(e);
  10447. if (decl == nullptr) {
  10448. continue;
  10449. }
  10450. GB_ASSERT(e->kind == Entity_Variable);
  10451. bool is_foreign = e->Variable.is_foreign;
  10452. bool is_export = e->Variable.is_export;
  10453. String name = lb_get_entity_name(m, e);
  10454. lbValue g = {};
  10455. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  10456. g.type = alloc_type_pointer(e->type);
  10457. if (e->Variable.thread_local_model != "") {
  10458. LLVMSetThreadLocal(g.value, true);
  10459. String m = e->Variable.thread_local_model;
  10460. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  10461. if (m == "default") {
  10462. mode = LLVMGeneralDynamicTLSModel;
  10463. } else if (m == "localdynamic") {
  10464. mode = LLVMLocalDynamicTLSModel;
  10465. } else if (m == "initialexec") {
  10466. mode = LLVMInitialExecTLSModel;
  10467. } else if (m == "localexec") {
  10468. mode = LLVMLocalExecTLSModel;
  10469. } else {
  10470. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  10471. }
  10472. LLVMSetThreadLocalMode(g.value, mode);
  10473. }
  10474. if (is_foreign) {
  10475. LLVMSetExternallyInitialized(g.value, true);
  10476. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  10477. } else {
  10478. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  10479. }
  10480. if (is_export) {
  10481. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  10482. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  10483. }
  10484. if (e->flags & EntityFlag_Static) {
  10485. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  10486. }
  10487. GlobalVariable var = {};
  10488. var.var = g;
  10489. var.decl = decl;
  10490. if (decl->init_expr != nullptr) {
  10491. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  10492. if (!is_type_any(e->type)) {
  10493. if (tav.mode != Addressing_Invalid) {
  10494. if (tav.value.kind != ExactValue_Invalid) {
  10495. ExactValue v = tav.value;
  10496. lbValue init = lb_const_value(m, tav.type, v);
  10497. LLVMSetInitializer(g.value, init.value);
  10498. var.is_initialized = true;
  10499. }
  10500. }
  10501. }
  10502. if (!var.is_initialized &&
  10503. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  10504. var.is_initialized = true;
  10505. }
  10506. }
  10507. array_add(&global_variables, var);
  10508. lb_add_entity(m, e, g);
  10509. lb_add_member(m, name, g);
  10510. }
  10511. TIME_SECTION("LLVM Global Procedures and Types");
  10512. for_array(i, info->entities) {
  10513. Entity *e = info->entities[i];
  10514. String name = e->token.string;
  10515. DeclInfo *decl = e->decl_info;
  10516. Scope * scope = e->scope;
  10517. if ((scope->flags & ScopeFlag_File) == 0) {
  10518. continue;
  10519. }
  10520. Scope *package_scope = scope->parent;
  10521. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  10522. switch (e->kind) {
  10523. case Entity_Variable:
  10524. // NOTE(bill): Handled above as it requires a specific load order
  10525. continue;
  10526. case Entity_ProcGroup:
  10527. continue;
  10528. case Entity_TypeName:
  10529. case Entity_Procedure:
  10530. break;
  10531. }
  10532. bool polymorphic_struct = false;
  10533. if (e->type != nullptr && e->kind == Entity_TypeName) {
  10534. Type *bt = base_type(e->type);
  10535. if (bt->kind == Type_Struct) {
  10536. polymorphic_struct = is_type_polymorphic(bt);
  10537. }
  10538. }
  10539. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  10540. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  10541. continue;
  10542. }
  10543. String mangled_name = lb_get_entity_name(m, e);
  10544. switch (e->kind) {
  10545. case Entity_TypeName:
  10546. lb_type(m, e->type);
  10547. break;
  10548. case Entity_Procedure:
  10549. {
  10550. lbProcedure *p = lb_create_procedure(m, e);
  10551. array_add(&m->procedures_to_generate, p);
  10552. }
  10553. break;
  10554. }
  10555. }
  10556. TIME_SECTION("LLVM Registry Initializtion");
  10557. LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry();
  10558. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod);
  10559. defer (LLVMDisposePassManager(default_function_pass_manager));
  10560. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  10561. {
  10562. auto dfpm = default_function_pass_manager;
  10563. if (build_context.optimization_level == 0) {
  10564. LLVMAddMemCpyOptPass(dfpm);
  10565. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10566. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10567. LLVMAddAggressiveInstCombinerPass(dfpm);
  10568. LLVMAddEarlyCSEPass(dfpm);
  10569. LLVMAddEarlyCSEMemSSAPass(dfpm);
  10570. LLVMAddConstantPropagationPass(dfpm);
  10571. LLVMAddAggressiveDCEPass(dfpm);
  10572. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10573. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10574. LLVMAddCFGSimplificationPass(dfpm);
  10575. // LLVMAddInstructionCombiningPass(dfpm);
  10576. LLVMAddSLPVectorizePass(dfpm);
  10577. LLVMAddLoopVectorizePass(dfpm);
  10578. LLVMAddScalarizerPass(dfpm);
  10579. LLVMAddLoopIdiomPass(dfpm);
  10580. } else {
  10581. bool do_extra_passes = true;
  10582. int repeat_count = cast(int)build_context.optimization_level;
  10583. do {
  10584. LLVMAddMemCpyOptPass(dfpm);
  10585. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10586. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10587. LLVMAddAlignmentFromAssumptionsPass(dfpm);
  10588. LLVMAddEarlyCSEPass(dfpm);
  10589. LLVMAddEarlyCSEMemSSAPass(dfpm);
  10590. LLVMAddConstantPropagationPass(dfpm);
  10591. if (do_extra_passes) {
  10592. LLVMAddAggressiveInstCombinerPass(dfpm);
  10593. LLVMAddAggressiveDCEPass(dfpm);
  10594. }
  10595. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10596. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10597. LLVMAddCFGSimplificationPass(dfpm);
  10598. LLVMAddTailCallEliminationPass(dfpm);
  10599. if (do_extra_passes) {
  10600. LLVMAddSLPVectorizePass(dfpm);
  10601. LLVMAddLoopVectorizePass(dfpm);
  10602. LLVMAddConstantPropagationPass(dfpm);
  10603. LLVMAddScalarizerPass(dfpm);
  10604. LLVMAddLoopIdiomPass(dfpm);
  10605. LLVMAddAggressiveInstCombinerPass(dfpm);
  10606. LLVMAddLowerExpectIntrinsicPass(dfpm);
  10607. LLVMAddDeadStoreEliminationPass(dfpm);
  10608. LLVMAddReassociatePass(dfpm);
  10609. LLVMAddAddDiscriminatorsPass(dfpm);
  10610. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10611. LLVMAddCorrelatedValuePropagationPass(dfpm);
  10612. }
  10613. } while (repeat_count --> 0);
  10614. }
  10615. }
  10616. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  10617. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod);
  10618. defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy));
  10619. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  10620. {
  10621. auto dfpm = default_function_pass_manager_without_memcpy;
  10622. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10623. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10624. LLVMAddAggressiveInstCombinerPass(dfpm);
  10625. LLVMAddConstantPropagationPass(dfpm);
  10626. LLVMAddAggressiveDCEPass(dfpm);
  10627. LLVMAddMergedLoadStoreMotionPass(dfpm);
  10628. LLVMAddPromoteMemoryToRegisterPass(dfpm);
  10629. LLVMAddCFGSimplificationPass(dfpm);
  10630. // LLVMAddUnifyFunctionExitNodesPass(dfpm);
  10631. }
  10632. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  10633. TIME_SECTION("LLVM Runtime Type Information Creation");
  10634. lbProcedure *startup_type_info = nullptr;
  10635. lbProcedure *startup_runtime = nullptr;
  10636. { // Startup Type Info
  10637. Type *params = alloc_type_tuple();
  10638. Type *results = alloc_type_tuple();
  10639. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10640. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  10641. p->is_startup = true;
  10642. startup_type_info = p;
  10643. lb_begin_procedure_body(p);
  10644. lb_setup_type_info_data(p);
  10645. lb_end_procedure_body(p);
  10646. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10647. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10648. LLVMDumpValue(p->value);
  10649. gb_printf_err("\n\n\n\n");
  10650. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10651. }
  10652. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10653. }
  10654. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  10655. { // Startup Runtime
  10656. Type *params = alloc_type_tuple();
  10657. Type *results = alloc_type_tuple();
  10658. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  10659. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  10660. p->is_startup = true;
  10661. startup_runtime = p;
  10662. lb_begin_procedure_body(p);
  10663. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  10664. for_array(i, global_variables) {
  10665. auto *var = &global_variables[i];
  10666. if (var->is_initialized) {
  10667. continue;
  10668. }
  10669. Entity *e = var->decl->entity;
  10670. GB_ASSERT(e->kind == Entity_Variable);
  10671. if (var->decl->init_expr != nullptr) {
  10672. // gb_printf_err("%s\n", expr_to_string(var->decl->init_expr));
  10673. lbValue init = lb_build_expr(p, var->decl->init_expr);
  10674. LLVMValueKind value_kind = LLVMGetValueKind(init.value);
  10675. // gb_printf_err("%s %d\n", LLVMPrintValueToString(init.value));
  10676. if (lb_is_const_or_global(init)) {
  10677. if (!var->is_initialized) {
  10678. LLVMSetInitializer(var->var.value, init.value);
  10679. var->is_initialized = true;
  10680. continue;
  10681. }
  10682. } else {
  10683. var->init = init;
  10684. }
  10685. }
  10686. if (var->init.value != nullptr) {
  10687. GB_ASSERT(!var->is_initialized);
  10688. Type *t = type_deref(var->var.type);
  10689. if (is_type_any(t)) {
  10690. // NOTE(bill): Edge case for 'any' type
  10691. Type *var_type = default_type(var->init.type);
  10692. lbAddr g = lb_add_global_generated(m, var_type, var->init);
  10693. lb_addr_store(p, g, var->init);
  10694. lbValue gp = lb_addr_get_ptr(p, g);
  10695. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  10696. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  10697. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  10698. lb_emit_store(p, ti, lb_type_info(m, var_type));
  10699. } else {
  10700. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  10701. LLVMTypeRef vt = LLVMGetElementType(pvt);
  10702. lbValue src0 = lb_emit_conv(p, var->init, t);
  10703. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  10704. LLVMValueRef dst = var->var.value;
  10705. LLVMBuildStore(p->builder, src, dst);
  10706. }
  10707. var->is_initialized = true;
  10708. }
  10709. }
  10710. lb_end_procedure_body(p);
  10711. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10712. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10713. LLVMDumpValue(p->value);
  10714. gb_printf_err("\n\n\n\n");
  10715. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10716. }
  10717. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10718. /*{
  10719. LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block);
  10720. for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block);
  10721. instr != last_instr;
  10722. instr = LLVMGetNextInstruction(instr)) {
  10723. if (LLVMIsAAllocaInst(instr)) {
  10724. LLVMTypeRef type = LLVMGetAllocatedType(instr);
  10725. LLVMValueRef sz_val = LLVMSizeOf(type);
  10726. GB_ASSERT(LLVMIsConstant(sz_val));
  10727. gb_printf_err(">> 0x%p\n", sz_val);
  10728. LLVMTypeRef sz_type = LLVMTypeOf(sz_val);
  10729. gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type));
  10730. unsigned long long sz = LLVMConstIntGetZExtValue(sz_val);
  10731. // long long sz = LLVMConstIntGetSExtValue(sz_val);
  10732. gb_printf_err(">> %ll\n", sz);
  10733. }
  10734. }
  10735. }*/
  10736. }
  10737. if (!(build_context.build_mode == BuildMode_DynamicLibrary && !has_dll_main)) {
  10738. TIME_SECTION("LLVM DLL main");
  10739. Type *params = alloc_type_tuple();
  10740. Type *results = alloc_type_tuple();
  10741. String name = str_lit("main");
  10742. if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_386) {
  10743. name = str_lit("mainCRTStartup");
  10744. } else {
  10745. array_init(&params->Tuple.variables, permanent_allocator(), 2);
  10746. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  10747. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true);
  10748. }
  10749. array_init(&results->Tuple.variables, permanent_allocator(), 1);
  10750. results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true);
  10751. Type *proc_type = alloc_type_proc(nullptr,
  10752. params, params->Tuple.variables.count,
  10753. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  10754. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  10755. p->is_startup = true;
  10756. lb_begin_procedure_body(p);
  10757. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, "");
  10758. if (build_context.command_kind == Command_test) {
  10759. for_array(i, m->info->testing_procedures) {
  10760. Entity *e = m->info->testing_procedures[i];
  10761. lbValue *found = map_get(&m->values, hash_entity(e));
  10762. GB_ASSERT(found != nullptr);
  10763. lb_emit_call(p, *found, {});
  10764. }
  10765. } else {
  10766. lbValue *found = map_get(&m->values, hash_entity(entry_point));
  10767. GB_ASSERT(found != nullptr);
  10768. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, "");
  10769. }
  10770. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  10771. lb_end_procedure_body(p);
  10772. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10773. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  10774. LLVMDumpValue(p->value);
  10775. gb_printf_err("\n\n\n\n");
  10776. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  10777. }
  10778. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10779. }
  10780. String filepath_ll = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".ll"));
  10781. TIME_SECTION("LLVM Procedure Generation");
  10782. for_array(i, m->procedures_to_generate) {
  10783. lbProcedure *p = m->procedures_to_generate[i];
  10784. if (p->is_done) {
  10785. continue;
  10786. }
  10787. if (p->body != nullptr) { // Build Procedure
  10788. m->curr_procedure = p;
  10789. lb_begin_procedure_body(p);
  10790. lb_build_stmt(p, p->body);
  10791. lb_end_procedure_body(p);
  10792. p->is_done = true;
  10793. m->curr_procedure = nullptr;
  10794. }
  10795. lb_end_procedure(p);
  10796. // Add Flags
  10797. if (p->body != nullptr) {
  10798. if (p->name == "memcpy" || p->name == "memmove" ||
  10799. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  10800. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  10801. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  10802. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  10803. }
  10804. }
  10805. if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  10806. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  10807. LLVMDumpValue(p->value);
  10808. gb_printf_err("\n\n\n\n");
  10809. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10810. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10811. }
  10812. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  10813. gb_exit(1);
  10814. }
  10815. }
  10816. TIME_SECTION("LLVM Function Pass");
  10817. {
  10818. for_array(i, m->procedures_to_generate) {
  10819. lbProcedure *p = m->procedures_to_generate[i];
  10820. if (p->body != nullptr) { // Build Procedure
  10821. for (i32 i = 0; i <= build_context.optimization_level; i++) {
  10822. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  10823. LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value);
  10824. } else {
  10825. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10826. }
  10827. }
  10828. }
  10829. }
  10830. for_array(i, m->equal_procs.entries) {
  10831. lbProcedure *p = m->equal_procs.entries[i].value;
  10832. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10833. }
  10834. for_array(i, m->hasher_procs.entries) {
  10835. lbProcedure *p = m->hasher_procs.entries[i].value;
  10836. LLVMRunFunctionPassManager(default_function_pass_manager, p->value);
  10837. }
  10838. }
  10839. TIME_SECTION("LLVM Module Pass");
  10840. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  10841. defer (LLVMDisposePassManager(module_pass_manager));
  10842. LLVMAddAlwaysInlinerPass(module_pass_manager);
  10843. LLVMAddStripDeadPrototypesPass(module_pass_manager);
  10844. LLVMAddAnalysisPasses(target_machine, module_pass_manager);
  10845. if (build_context.optimization_level >= 2) {
  10846. LLVMAddArgumentPromotionPass(module_pass_manager);
  10847. LLVMAddConstantMergePass(module_pass_manager);
  10848. LLVMAddGlobalDCEPass(module_pass_manager);
  10849. LLVMAddDeadArgEliminationPass(module_pass_manager);
  10850. }
  10851. LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate();
  10852. defer (LLVMPassManagerBuilderDispose(pass_manager_builder));
  10853. LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level);
  10854. LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level);
  10855. LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false);
  10856. LLVMRunPassManager(module_pass_manager, mod);
  10857. llvm_error = nullptr;
  10858. defer (LLVMDisposeMessage(llvm_error));
  10859. String filepath_obj = {};
  10860. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  10861. if (build_context.build_mode == BuildMode_Assembly) {
  10862. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".S"));
  10863. code_gen_file_type = LLVMAssemblyFile;
  10864. } else {
  10865. switch (build_context.metrics.os) {
  10866. case TargetOs_windows:
  10867. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".obj"));
  10868. break;
  10869. case TargetOs_darwin:
  10870. case TargetOs_linux:
  10871. case TargetOs_essence:
  10872. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".o"));
  10873. break;
  10874. case TargetOs_js:
  10875. filepath_obj = concatenate_strings(permanent_allocator(), gen->output_base, STR_LIT(".wasm-obj"));
  10876. break;
  10877. }
  10878. }
  10879. LLVMDIBuilderFinalize(m->debug_builder);
  10880. if (LLVMVerifyModule(mod, LLVMReturnStatusAction, &llvm_error)) {
  10881. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  10882. if (build_context.keep_temp_files) {
  10883. TIME_SECTION("LLVM Print Module to File");
  10884. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10885. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10886. gb_exit(1);
  10887. return;
  10888. }
  10889. }
  10890. gb_exit(1);
  10891. return;
  10892. }
  10893. llvm_error = nullptr;
  10894. if (build_context.keep_temp_files) {
  10895. TIME_SECTION("LLVM Print Module to File");
  10896. if (LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  10897. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10898. gb_exit(1);
  10899. return;
  10900. }
  10901. }
  10902. TIME_SECTION("LLVM Object Generation");
  10903. if (LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  10904. gb_printf_err("LLVM Error: %s\n", llvm_error);
  10905. gb_exit(1);
  10906. return;
  10907. }
  10908. array_add(&gen->output_object_paths, filepath_obj);
  10909. for_array(i, m->info->required_foreign_imports_through_force) {
  10910. Entity *e = m->info->required_foreign_imports_through_force[i];
  10911. lb_add_foreign_library_path(m, e);
  10912. }
  10913. #undef TIME_SECTION
  10914. }