llvm_backend_expr.cpp 153 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882
  1. gb_internal lbValue lb_emit_arith_matrix(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type, bool component_wise);
  2. gb_internal lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *final_type) {
  3. lbModule *m = p->module;
  4. lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs");
  5. lbBlock *done = lb_create_block(p, "logical.cmp.done");
  6. lbValue short_circuit = {};
  7. if (op == Token_CmpAnd) {
  8. lb_build_cond(p, left, rhs, done);
  9. short_circuit = lb_const_bool(m, t_llvm_bool, false);
  10. } else if (op == Token_CmpOr) {
  11. lb_build_cond(p, left, done, rhs);
  12. short_circuit = lb_const_bool(m, t_llvm_bool, true);
  13. }
  14. if (rhs->preds.count == 0) {
  15. lb_start_block(p, done);
  16. return short_circuit;
  17. }
  18. if (done->preds.count == 0) {
  19. lb_start_block(p, rhs);
  20. if (lb_is_expr_untyped_const(right)) {
  21. return lb_expr_untyped_const_to_typed(m, right, default_type(final_type));
  22. }
  23. return lb_build_expr(p, right);
  24. }
  25. Array<LLVMValueRef> incoming_values = {};
  26. Array<LLVMBasicBlockRef> incoming_blocks = {};
  27. array_init(&incoming_values, heap_allocator(), done->preds.count+1);
  28. array_init(&incoming_blocks, heap_allocator(), done->preds.count+1);
  29. for_array(i, done->preds) {
  30. incoming_values[i] = short_circuit.value;
  31. incoming_blocks[i] = done->preds[i]->block;
  32. }
  33. lb_start_block(p, rhs);
  34. lbValue edge = {};
  35. if (lb_is_expr_untyped_const(right)) {
  36. edge = lb_expr_untyped_const_to_typed(m, right, t_llvm_bool);
  37. } else {
  38. edge = lb_emit_conv(p, lb_build_expr(p, right), t_llvm_bool);
  39. }
  40. GB_ASSERT(edge.type == t_llvm_bool);
  41. incoming_values[done->preds.count] = edge.value;
  42. incoming_blocks[done->preds.count] = p->curr_block->block;
  43. lb_emit_jump(p, done);
  44. lb_start_block(p, done);
  45. LLVMTypeRef dst_type = lb_type(m, t_llvm_bool);
  46. LLVMValueRef phi = nullptr;
  47. GB_ASSERT(incoming_values.count == incoming_blocks.count);
  48. GB_ASSERT(incoming_values.count > 0);
  49. LLVMTypeRef phi_type = nullptr;
  50. for (LLVMValueRef incoming_value : incoming_values) {
  51. if (!LLVMIsConstant(incoming_value)) {
  52. phi_type = LLVMTypeOf(incoming_value);
  53. break;
  54. }
  55. }
  56. lbValue res = {};
  57. if (phi_type == nullptr) {
  58. phi = LLVMBuildPhi(p->builder, dst_type, "");
  59. LLVMAddIncoming(phi, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  60. res.value = phi;
  61. res.type = t_llvm_bool;
  62. } else {
  63. for_array(i, incoming_values) {
  64. LLVMValueRef incoming_value = incoming_values[i];
  65. LLVMTypeRef incoming_type = LLVMTypeOf(incoming_value);
  66. if (phi_type != incoming_type) {
  67. GB_ASSERT_MSG(LLVMIsConstant(incoming_value), "%s vs %s", LLVMPrintTypeToString(phi_type), LLVMPrintTypeToString(incoming_type));
  68. bool ok = !!LLVMConstIntGetZExtValue(incoming_value);
  69. incoming_values[i] = LLVMConstInt(phi_type, ok, false);
  70. }
  71. }
  72. // NOTE(bill): this now only uses i1 for the logic to prevent issues with corrupted booleans which are not of value 0 or 1 (e.g. 2)
  73. // Doing this may produce slightly worse code as a result but it will be correct behaviour
  74. phi = LLVMBuildPhi(p->builder, phi_type, "");
  75. LLVMAddIncoming(phi, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count);
  76. res.value = phi;
  77. res.type = t_llvm_bool;
  78. }
  79. return lb_emit_conv(p, res, default_type(final_type));
  80. }
  81. gb_internal lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) {
  82. switch (op) {
  83. case Token_Add:
  84. return x;
  85. case Token_Not: // Boolean not
  86. case Token_Xor: // Bitwise not
  87. case Token_Sub: // Number negation
  88. break;
  89. case Token_Pointer:
  90. GB_PANIC("This should be handled elsewhere");
  91. break;
  92. }
  93. if (is_type_array_like(x.type)) {
  94. // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory
  95. Type *tl = base_type(x.type);
  96. lbValue val = lb_address_from_load_or_generate_local(p, x);
  97. GB_ASSERT(is_type_array_like(type));
  98. Type *elem_type = base_array_type(type);
  99. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  100. lbAddr res_addr = lb_add_local(p, type, nullptr, false, true);
  101. lbValue res = lb_addr_get_ptr(p, res_addr);
  102. bool inline_array_arith = lb_can_try_to_inline_array_arith(type);
  103. i32 count = cast(i32)get_array_type_count(tl);
  104. LLVMTypeRef vector_type = nullptr;
  105. if (op != Token_Not && lb_try_vector_cast(p->module, val, &vector_type)) {
  106. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, val.value, LLVMPointerType(vector_type, 0), "");
  107. LLVMValueRef v = LLVMBuildLoad2(p->builder, vector_type, vp, "");
  108. LLVMValueRef opv = nullptr;
  109. switch (op) {
  110. case Token_Xor:
  111. opv = LLVMBuildNot(p->builder, v, "");
  112. break;
  113. case Token_Sub:
  114. if (is_type_float(elem_type)) {
  115. opv = LLVMBuildFNeg(p->builder, v, "");
  116. } else {
  117. opv = LLVMBuildNeg(p->builder, v, "");
  118. }
  119. break;
  120. }
  121. if (opv != nullptr) {
  122. LLVMSetAlignment(res.value, cast(unsigned)lb_alignof(vector_type));
  123. LLVMValueRef res_ptr = LLVMBuildPointerCast(p->builder, res.value, LLVMPointerType(vector_type, 0), "");
  124. LLVMBuildStore(p->builder, opv, res_ptr);
  125. return lb_emit_conv(p, lb_emit_load(p, res), type);
  126. }
  127. }
  128. if (inline_array_arith) {
  129. // inline
  130. for (i32 i = 0; i < count; i++) {
  131. lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i));
  132. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  133. lb_emit_store(p, lb_emit_array_epi(p, res, i), z);
  134. }
  135. } else {
  136. auto loop_data = lb_loop_start(p, count, t_i32);
  137. lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx));
  138. lbValue z = lb_emit_unary_arith(p, op, e, elem_type);
  139. lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z);
  140. lb_loop_end(p, loop_data);
  141. }
  142. return lb_emit_load(p, res);
  143. }
  144. if (op == Token_Xor) {
  145. lbValue cmp = {};
  146. cmp.value = LLVMBuildNot(p->builder, x.value, "");
  147. cmp.type = x.type;
  148. return lb_emit_conv(p, cmp, type);
  149. }
  150. if (op == Token_Not) {
  151. lbValue cmp = {};
  152. LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false);
  153. cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, "");
  154. cmp.type = t_llvm_bool;
  155. return lb_emit_conv(p, cmp, type);
  156. }
  157. if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  158. Type *platform_type = integer_endian_type_to_platform_type(type);
  159. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  160. lbValue res = {};
  161. res.value = LLVMBuildNeg(p->builder, v.value, "");
  162. res.type = platform_type;
  163. return lb_emit_byte_swap(p, res, type);
  164. }
  165. if (op == Token_Sub && is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  166. Type *platform_type = integer_endian_type_to_platform_type(type);
  167. lbValue v = lb_emit_byte_swap(p, x, platform_type);
  168. lbValue res = {};
  169. res.value = LLVMBuildFNeg(p->builder, v.value, "");
  170. res.type = platform_type;
  171. return lb_emit_byte_swap(p, res, type);
  172. }
  173. lbValue res = {};
  174. switch (op) {
  175. case Token_Not: // Boolean not
  176. case Token_Xor: // Bitwise not
  177. res.value = LLVMBuildNot(p->builder, x.value, "");
  178. res.type = x.type;
  179. return res;
  180. case Token_Sub: // Number negation
  181. if (is_type_integer(x.type)) {
  182. res.value = LLVMBuildNeg(p->builder, x.value, "");
  183. } else if (is_type_float(x.type)) {
  184. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  185. } else if (is_type_complex(x.type)) {
  186. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  187. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  188. lbAddr addr = lb_add_local_generated(p, x.type, false);
  189. LLVMTypeRef type = llvm_addr_type(p->module, addr.addr);
  190. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP2(p->builder, type, addr.addr.value, 0, ""));
  191. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP2(p->builder, type, addr.addr.value, 1, ""));
  192. return lb_addr_load(p, addr);
  193. } else if (is_type_quaternion(x.type)) {
  194. LLVMValueRef v0 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 0, ""), "");
  195. LLVMValueRef v1 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 1, ""), "");
  196. LLVMValueRef v2 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 2, ""), "");
  197. LLVMValueRef v3 = LLVMBuildFNeg(p->builder, LLVMBuildExtractValue(p->builder, x.value, 3, ""), "");
  198. lbAddr addr = lb_add_local_generated(p, x.type, false);
  199. LLVMTypeRef type = llvm_addr_type(p->module, addr.addr);
  200. LLVMBuildStore(p->builder, v0, LLVMBuildStructGEP2(p->builder, type, addr.addr.value, 0, ""));
  201. LLVMBuildStore(p->builder, v1, LLVMBuildStructGEP2(p->builder, type, addr.addr.value, 1, ""));
  202. LLVMBuildStore(p->builder, v2, LLVMBuildStructGEP2(p->builder, type, addr.addr.value, 2, ""));
  203. LLVMBuildStore(p->builder, v3, LLVMBuildStructGEP2(p->builder, type, addr.addr.value, 3, ""));
  204. return lb_addr_load(p, addr);
  205. } else if (is_type_simd_vector(x.type)) {
  206. Type *elem = base_array_type(x.type);
  207. if (is_type_float(elem)) {
  208. res.value = LLVMBuildFNeg(p->builder, x.value, "");
  209. } else {
  210. res.value = LLVMBuildNeg(p->builder, x.value, "");
  211. }
  212. } else if (is_type_matrix(x.type)) {
  213. lbValue zero = {};
  214. zero.value = LLVMConstNull(lb_type(p->module, type));
  215. zero.type = type;
  216. return lb_emit_arith_matrix(p, Token_Sub, zero, x, type, true);
  217. } else {
  218. GB_PANIC("Unhandled type %s", type_to_string(x.type));
  219. }
  220. res.type = x.type;
  221. return res;
  222. }
  223. return res;
  224. }
  225. gb_internal bool lb_try_direct_vector_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type, lbValue *res_) {
  226. GB_ASSERT(is_type_array_like(type));
  227. Type *elem_type = base_array_type(type);
  228. // NOTE(bill): Shift operations cannot be easily dealt with due to Odin's semantics
  229. if (op == Token_Shl || op == Token_Shr) {
  230. return false;
  231. }
  232. if (!LLVMIsALoadInst(lhs.value) || !LLVMIsALoadInst(rhs.value)) {
  233. return false;
  234. }
  235. lbValue lhs_ptr = {};
  236. lbValue rhs_ptr = {};
  237. lhs_ptr.value = LLVMGetOperand(lhs.value, 0);
  238. lhs_ptr.type = alloc_type_pointer(lhs.type);
  239. rhs_ptr.value = LLVMGetOperand(rhs.value, 0);
  240. rhs_ptr.type = alloc_type_pointer(rhs.type);
  241. LLVMTypeRef vector_type0 = nullptr;
  242. LLVMTypeRef vector_type1 = nullptr;
  243. if (lb_try_vector_cast(p->module, lhs_ptr, &vector_type0) &&
  244. lb_try_vector_cast(p->module, rhs_ptr, &vector_type1)) {
  245. GB_ASSERT(vector_type0 == vector_type1);
  246. LLVMTypeRef vector_type = vector_type0;
  247. LLVMValueRef lhs_vp = LLVMBuildPointerCast(p->builder, lhs_ptr.value, LLVMPointerType(vector_type, 0), "");
  248. LLVMValueRef rhs_vp = LLVMBuildPointerCast(p->builder, rhs_ptr.value, LLVMPointerType(vector_type, 0), "");
  249. LLVMValueRef x = LLVMBuildLoad2(p->builder, vector_type, lhs_vp, "");
  250. LLVMValueRef y = LLVMBuildLoad2(p->builder, vector_type, rhs_vp, "");
  251. LLVMValueRef z = nullptr;
  252. Type *integral_type = base_type(elem_type);
  253. if (is_type_simd_vector(integral_type)) {
  254. integral_type = core_array_type(integral_type);
  255. }
  256. if (is_type_bit_set(integral_type)) {
  257. switch (op) {
  258. case Token_Add: op = Token_Or; break;
  259. case Token_Sub: op = Token_AndNot; break;
  260. }
  261. }
  262. if (is_type_float(integral_type)) {
  263. switch (op) {
  264. case Token_Add:
  265. z = LLVMBuildFAdd(p->builder, x, y, "");
  266. break;
  267. case Token_Sub:
  268. z = LLVMBuildFSub(p->builder, x, y, "");
  269. break;
  270. case Token_Mul:
  271. z = LLVMBuildFMul(p->builder, x, y, "");
  272. break;
  273. case Token_Quo:
  274. z = LLVMBuildFDiv(p->builder, x, y, "");
  275. break;
  276. case Token_Mod:
  277. z = LLVMBuildFRem(p->builder, x, y, "");
  278. break;
  279. default:
  280. GB_PANIC("Unsupported vector operation %.*s", LIT(token_strings[op]));
  281. break;
  282. }
  283. } else {
  284. switch (op) {
  285. case Token_Add:
  286. z = LLVMBuildAdd(p->builder, x, y, "");
  287. break;
  288. case Token_Sub:
  289. z = LLVMBuildSub(p->builder, x, y, "");
  290. break;
  291. case Token_Mul:
  292. z = LLVMBuildMul(p->builder, x, y, "");
  293. break;
  294. case Token_Quo:
  295. if (is_type_unsigned(integral_type)) {
  296. z = LLVMBuildUDiv(p->builder, x, y, "");
  297. } else {
  298. z = LLVMBuildSDiv(p->builder, x, y, "");
  299. }
  300. break;
  301. case Token_Mod:
  302. if (is_type_unsigned(integral_type)) {
  303. z = LLVMBuildURem(p->builder, x, y, "");
  304. } else {
  305. z = LLVMBuildSRem(p->builder, x, y, "");
  306. }
  307. break;
  308. case Token_ModMod:
  309. if (is_type_unsigned(integral_type)) {
  310. z = LLVMBuildURem(p->builder, x, y, "");
  311. } else {
  312. LLVMValueRef a = LLVMBuildSRem(p->builder, x, y, "");
  313. LLVMValueRef b = LLVMBuildAdd(p->builder, a, y, "");
  314. z = LLVMBuildSRem(p->builder, b, y, "");
  315. }
  316. break;
  317. case Token_And:
  318. z = LLVMBuildAnd(p->builder, x, y, "");
  319. break;
  320. case Token_AndNot:
  321. z = LLVMBuildAnd(p->builder, x, LLVMBuildNot(p->builder, y, ""), "");
  322. break;
  323. case Token_Or:
  324. z = LLVMBuildOr(p->builder, x, y, "");
  325. break;
  326. case Token_Xor:
  327. z = LLVMBuildXor(p->builder, x, y, "");
  328. break;
  329. default:
  330. GB_PANIC("Unsupported vector operation");
  331. break;
  332. }
  333. }
  334. if (z != nullptr) {
  335. lbAddr res = lb_add_local_generated_temp(p, type, lb_alignof(vector_type));
  336. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, res.addr.value, LLVMPointerType(vector_type, 0), "");
  337. LLVMBuildStore(p->builder, z, vp);
  338. lbValue v = lb_addr_load(p, res);
  339. if (res_) *res_ = v;
  340. return true;
  341. }
  342. }
  343. return false;
  344. }
  345. gb_internal lbValue lb_emit_arith_array(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  346. GB_ASSERT(is_type_array_like(lhs.type) || is_type_array_like(rhs.type));
  347. lhs = lb_emit_conv(p, lhs, type);
  348. rhs = lb_emit_conv(p, rhs, type);
  349. GB_ASSERT(is_type_array_like(type));
  350. Type *elem_type = base_array_type(type);
  351. i64 count = get_array_type_count(type);
  352. unsigned n = cast(unsigned)count;
  353. // NOTE(bill, 2021-06-12): Try to do a direct operation as a vector, if possible
  354. lbValue direct_vector_res = {};
  355. if (lb_try_direct_vector_arith(p, op, lhs, rhs, type, &direct_vector_res)) {
  356. return direct_vector_res;
  357. }
  358. bool inline_array_arith = lb_can_try_to_inline_array_arith(type);
  359. if (inline_array_arith) {
  360. auto dst_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  361. auto a_loads = slice_make<lbValue>(temporary_allocator(), n);
  362. auto b_loads = slice_make<lbValue>(temporary_allocator(), n);
  363. auto c_ops = slice_make<lbValue>(temporary_allocator(), n);
  364. for (unsigned i = 0; i < n; i++) {
  365. a_loads[i].value = LLVMBuildExtractValue(p->builder, lhs.value, i, "");
  366. a_loads[i].type = elem_type;
  367. }
  368. for (unsigned i = 0; i < n; i++) {
  369. b_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  370. b_loads[i].type = elem_type;
  371. }
  372. for (unsigned i = 0; i < n; i++) {
  373. c_ops[i] = lb_emit_arith(p, op, a_loads[i], b_loads[i], elem_type);
  374. }
  375. lbAddr res = lb_add_local_generated(p, type, false);
  376. for (unsigned i = 0; i < n; i++) {
  377. dst_ptrs[i] = lb_emit_array_epi(p, res.addr, i);
  378. }
  379. for (unsigned i = 0; i < n; i++) {
  380. lb_emit_store(p, dst_ptrs[i], c_ops[i]);
  381. }
  382. return lb_addr_load(p, res);
  383. } else {
  384. lbValue x = lb_address_from_load_or_generate_local(p, lhs);
  385. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  386. lbAddr res = lb_add_local_generated(p, type, false);
  387. auto loop_data = lb_loop_start(p, cast(isize)count, t_i32);
  388. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  389. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  390. lbValue dst_ptr = lb_emit_array_ep(p, res.addr, loop_data.idx);
  391. lbValue a = lb_emit_load(p, a_ptr);
  392. lbValue b = lb_emit_load(p, b_ptr);
  393. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  394. lb_emit_store(p, dst_ptr, c);
  395. lb_loop_end(p, loop_data);
  396. return lb_addr_load(p, res);
  397. }
  398. }
  399. gb_internal bool lb_is_matrix_simdable(Type *t) {
  400. Type *mt = base_type(t);
  401. GB_ASSERT(mt->kind == Type_Matrix);
  402. Type *elem = core_type(mt->Matrix.elem);
  403. if (is_type_complex(elem)) {
  404. return false;
  405. }
  406. if (is_type_different_to_arch_endianness(elem)) {
  407. return false;
  408. }
  409. switch (build_context.metrics.arch) {
  410. default:
  411. return false;
  412. case TargetArch_amd64:
  413. case TargetArch_arm64:
  414. break;
  415. }
  416. if (type_align_of(t) < 16) {
  417. // it's not aligned well enough to use the vector instructions
  418. return false;
  419. }
  420. if ((mt->Matrix.row_count & 1) ^ (mt->Matrix.column_count & 1)) {
  421. return false;
  422. }
  423. if (elem->kind == Type_Basic) {
  424. switch (elem->Basic.kind) {
  425. case Basic_f16:
  426. case Basic_f16le:
  427. case Basic_f16be:
  428. switch (build_context.metrics.arch) {
  429. case TargetArch_amd64:
  430. return false;
  431. case TargetArch_arm64:
  432. // TODO(bill): determine when this is fine
  433. return true;
  434. case TargetArch_i386:
  435. case TargetArch_wasm32:
  436. case TargetArch_wasm64p32:
  437. return false;
  438. }
  439. }
  440. }
  441. return true;
  442. }
  443. gb_internal LLVMValueRef lb_matrix_to_vector(lbProcedure *p, lbValue matrix) {
  444. Type *mt = base_type(matrix.type);
  445. GB_ASSERT(mt->kind == Type_Matrix);
  446. LLVMTypeRef elem_type = lb_type(p->module, mt->Matrix.elem);
  447. unsigned total_count = cast(unsigned)matrix_type_total_internal_elems(mt);
  448. LLVMTypeRef total_matrix_type = LLVMVectorType(elem_type, total_count);
  449. #if 1
  450. LLVMValueRef ptr = lb_address_from_load_or_generate_local(p, matrix).value;
  451. LLVMValueRef matrix_vector_ptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(total_matrix_type, 0), "");
  452. LLVMValueRef matrix_vector = LLVMBuildLoad2(p->builder, total_matrix_type, matrix_vector_ptr, "");
  453. LLVMSetAlignment(matrix_vector, cast(unsigned)type_align_of(mt));
  454. return matrix_vector;
  455. #else
  456. LLVMValueRef matrix_vector = LLVMBuildBitCast(p->builder, matrix.value, total_matrix_type, "");
  457. return matrix_vector;
  458. #endif
  459. }
  460. gb_internal LLVMValueRef lb_matrix_trimmed_vector_mask(lbProcedure *p, Type *mt) {
  461. mt = base_type(mt);
  462. GB_ASSERT(mt->kind == Type_Matrix);
  463. unsigned stride = cast(unsigned)matrix_type_stride_in_elems(mt);
  464. unsigned row_count = cast(unsigned)mt->Matrix.row_count;
  465. unsigned column_count = cast(unsigned)mt->Matrix.column_count;
  466. unsigned mask_elems_index = 0;
  467. auto mask_elems = slice_make<LLVMValueRef>(permanent_allocator(), row_count*column_count);
  468. for (unsigned j = 0; j < column_count; j++) {
  469. for (unsigned i = 0; i < row_count; i++) {
  470. unsigned offset = stride*j + i;
  471. mask_elems[mask_elems_index++] = lb_const_int(p->module, t_u32, offset).value;
  472. }
  473. }
  474. LLVMValueRef mask = LLVMConstVector(mask_elems.data, cast(unsigned)mask_elems.count);
  475. return mask;
  476. }
  477. gb_internal LLVMValueRef lb_matrix_to_trimmed_vector(lbProcedure *p, lbValue m) {
  478. LLVMValueRef vector = lb_matrix_to_vector(p, m);
  479. Type *mt = base_type(m.type);
  480. GB_ASSERT(mt->kind == Type_Matrix);
  481. unsigned stride = cast(unsigned)matrix_type_stride_in_elems(mt);
  482. unsigned row_count = cast(unsigned)mt->Matrix.row_count;
  483. if (stride == row_count) {
  484. return vector;
  485. }
  486. LLVMValueRef mask = lb_matrix_trimmed_vector_mask(p, mt);
  487. LLVMValueRef trimmed_vector = llvm_basic_shuffle(p, vector, mask);
  488. return trimmed_vector;
  489. }
  490. gb_internal lbValue lb_emit_matrix_tranpose(lbProcedure *p, lbValue m, Type *type) {
  491. if (is_type_array(m.type)) {
  492. i32 rank = type_math_rank(m.type);
  493. if (rank == 2) {
  494. lbAddr addr = lb_add_local_generated(p, type, false);
  495. lbValue dst = addr.addr;
  496. lbValue src = m;
  497. i32 n = cast(i32)get_array_type_count(m.type);
  498. i32 m = cast(i32)get_array_type_count(type);
  499. // m.type == [n][m]T
  500. // type == [m][n]T
  501. for (i32 j = 0; j < m; j++) {
  502. lbValue dst_col = lb_emit_struct_ep(p, dst, j);
  503. for (i32 i = 0; i < n; i++) {
  504. lbValue dst_row = lb_emit_struct_ep(p, dst_col, i);
  505. lbValue src_col = lb_emit_struct_ev(p, src, i);
  506. lbValue src_row = lb_emit_struct_ev(p, src_col, j);
  507. lb_emit_store(p, dst_row, src_row);
  508. }
  509. }
  510. return lb_addr_load(p, addr);
  511. }
  512. // no-op
  513. m.type = type;
  514. return m;
  515. }
  516. Type *mt = base_type(m.type);
  517. GB_ASSERT(mt->kind == Type_Matrix);
  518. if (lb_is_matrix_simdable(mt)) {
  519. unsigned stride = cast(unsigned)matrix_type_stride_in_elems(mt);
  520. unsigned row_count = cast(unsigned)mt->Matrix.row_count;
  521. unsigned column_count = cast(unsigned)mt->Matrix.column_count;
  522. auto rows = slice_make<LLVMValueRef>(permanent_allocator(), row_count);
  523. auto mask_elems = slice_make<LLVMValueRef>(permanent_allocator(), column_count);
  524. LLVMValueRef vector = lb_matrix_to_vector(p, m);
  525. for (unsigned i = 0; i < row_count; i++) {
  526. for (unsigned j = 0; j < column_count; j++) {
  527. unsigned offset = stride*j + i;
  528. mask_elems[j] = lb_const_int(p->module, t_u32, offset).value;
  529. }
  530. // transpose mask
  531. LLVMValueRef mask = LLVMConstVector(mask_elems.data, column_count);
  532. LLVMValueRef row = llvm_basic_shuffle(p, vector, mask);
  533. rows[i] = row;
  534. }
  535. lbAddr res = lb_add_local_generated(p, type, true);
  536. for_array(i, rows) {
  537. LLVMValueRef row = rows[i];
  538. lbValue dst_row_ptr = lb_emit_matrix_epi(p, res.addr, 0, i);
  539. LLVMValueRef ptr = dst_row_ptr.value;
  540. ptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(LLVMTypeOf(row), 0), "");
  541. LLVMBuildStore(p->builder, row, ptr);
  542. }
  543. return lb_addr_load(p, res);
  544. }
  545. lbAddr res = lb_add_local_generated(p, type, true);
  546. i64 row_count = mt->Matrix.row_count;
  547. i64 column_count = mt->Matrix.column_count;
  548. for (i64 j = 0; j < column_count; j++) {
  549. for (i64 i = 0; i < row_count; i++) {
  550. lbValue src = lb_emit_matrix_ev(p, m, i, j);
  551. lbValue dst = lb_emit_matrix_epi(p, res.addr, j, i);
  552. lb_emit_store(p, dst, src);
  553. }
  554. }
  555. return lb_addr_load(p, res);
  556. }
  557. gb_internal lbValue lb_matrix_cast_vector_to_type(lbProcedure *p, LLVMValueRef vector, Type *type) {
  558. lbAddr res = lb_add_local_generated(p, type, true);
  559. LLVMValueRef res_ptr = res.addr.value;
  560. unsigned alignment = cast(unsigned)gb_max(type_align_of(type), lb_alignof(LLVMTypeOf(vector)));
  561. LLVMSetAlignment(res_ptr, alignment);
  562. res_ptr = LLVMBuildPointerCast(p->builder, res_ptr, LLVMPointerType(LLVMTypeOf(vector), 0), "");
  563. LLVMBuildStore(p->builder, vector, res_ptr);
  564. return lb_addr_load(p, res);
  565. }
  566. gb_internal lbValue lb_emit_matrix_flatten(lbProcedure *p, lbValue m, Type *type) {
  567. if (is_type_array(m.type)) {
  568. // no-op
  569. m.type = type;
  570. return m;
  571. }
  572. Type *mt = base_type(m.type);
  573. GB_ASSERT(mt->kind == Type_Matrix);
  574. if (lb_is_matrix_simdable(mt)) {
  575. LLVMValueRef vector = lb_matrix_to_trimmed_vector(p, m);
  576. return lb_matrix_cast_vector_to_type(p, vector, type);
  577. }
  578. lbAddr res = lb_add_local_generated(p, type, true);
  579. i64 row_count = mt->Matrix.row_count;
  580. i64 column_count = mt->Matrix.column_count;
  581. for (i64 j = 0; j < column_count; j++) {
  582. for (i64 i = 0; i < row_count; i++) {
  583. lbValue src = lb_emit_matrix_ev(p, m, i, j);
  584. lbValue dst = lb_emit_array_epi(p, res.addr, i + j*row_count);
  585. lb_emit_store(p, dst, src);
  586. }
  587. }
  588. return lb_addr_load(p, res);
  589. }
  590. gb_internal lbValue lb_emit_outer_product(lbProcedure *p, lbValue a, lbValue b, Type *type) {
  591. Type *mt = base_type(type);
  592. Type *at = base_type(a.type);
  593. Type *bt = base_type(b.type);
  594. GB_ASSERT(mt->kind == Type_Matrix);
  595. GB_ASSERT(at->kind == Type_Array);
  596. GB_ASSERT(bt->kind == Type_Array);
  597. i64 row_count = mt->Matrix.row_count;
  598. i64 column_count = mt->Matrix.column_count;
  599. GB_ASSERT(row_count == at->Array.count);
  600. GB_ASSERT(column_count == bt->Array.count);
  601. lbAddr res = lb_add_local_generated(p, type, true);
  602. for (i64 j = 0; j < column_count; j++) {
  603. for (i64 i = 0; i < row_count; i++) {
  604. lbValue x = lb_emit_struct_ev(p, a, cast(i32)i);
  605. lbValue y = lb_emit_struct_ev(p, b, cast(i32)j);
  606. lbValue src = lb_emit_arith(p, Token_Mul, x, y, mt->Matrix.elem);
  607. lbValue dst = lb_emit_matrix_epi(p, res.addr, i, j);
  608. lb_emit_store(p, dst, src);
  609. }
  610. }
  611. return lb_addr_load(p, res);
  612. }
  613. gb_internal lbValue lb_emit_matrix_mul(lbProcedure *p, lbValue lhs, lbValue rhs, Type *type) {
  614. // TODO(bill): Handle edge case for f16 types on x86(-64) platforms
  615. Type *xt = base_type(lhs.type);
  616. Type *yt = base_type(rhs.type);
  617. GB_ASSERT(is_type_matrix(type));
  618. GB_ASSERT(is_type_matrix(xt));
  619. GB_ASSERT(is_type_matrix(yt));
  620. GB_ASSERT(xt->Matrix.column_count == yt->Matrix.row_count);
  621. GB_ASSERT(are_types_identical(xt->Matrix.elem, yt->Matrix.elem));
  622. Type *elem = xt->Matrix.elem;
  623. unsigned outer_rows = cast(unsigned)xt->Matrix.row_count;
  624. unsigned inner = cast(unsigned)xt->Matrix.column_count;
  625. unsigned outer_columns = cast(unsigned)yt->Matrix.column_count;
  626. if (lb_is_matrix_simdable(xt)) {
  627. unsigned x_stride = cast(unsigned)matrix_type_stride_in_elems(xt);
  628. unsigned y_stride = cast(unsigned)matrix_type_stride_in_elems(yt);
  629. auto x_rows = slice_make<LLVMValueRef>(permanent_allocator(), outer_rows);
  630. auto y_columns = slice_make<LLVMValueRef>(permanent_allocator(), outer_columns);
  631. LLVMValueRef x_vector = lb_matrix_to_vector(p, lhs);
  632. LLVMValueRef y_vector = lb_matrix_to_vector(p, rhs);
  633. auto mask_elems = slice_make<LLVMValueRef>(permanent_allocator(), inner);
  634. for (unsigned i = 0; i < outer_rows; i++) {
  635. for (unsigned j = 0; j < inner; j++) {
  636. unsigned offset = x_stride*j + i;
  637. mask_elems[j] = lb_const_int(p->module, t_u32, offset).value;
  638. }
  639. // transpose mask
  640. LLVMValueRef mask = LLVMConstVector(mask_elems.data, inner);
  641. LLVMValueRef row = llvm_basic_shuffle(p, x_vector, mask);
  642. x_rows[i] = row;
  643. }
  644. for (unsigned i = 0; i < outer_columns; i++) {
  645. LLVMValueRef mask = llvm_mask_iota(p->module, y_stride*i, inner);
  646. LLVMValueRef column = llvm_basic_shuffle(p, y_vector, mask);
  647. y_columns[i] = column;
  648. }
  649. lbAddr res = lb_add_local_generated(p, type, true);
  650. for_array(i, x_rows) {
  651. LLVMValueRef x_row = x_rows[i];
  652. for_array(j, y_columns) {
  653. LLVMValueRef y_column = y_columns[j];
  654. LLVMValueRef elem = llvm_vector_dot(p, x_row, y_column);
  655. lbValue dst = lb_emit_matrix_epi(p, res.addr, i, j);
  656. LLVMBuildStore(p->builder, elem, dst.value);
  657. }
  658. }
  659. return lb_addr_load(p, res);
  660. }
  661. {
  662. lbAddr res = lb_add_local_generated(p, type, true);
  663. auto inners = slice_make<lbValue[2]>(permanent_allocator(), inner);
  664. for (unsigned j = 0; j < outer_columns; j++) {
  665. for (unsigned i = 0; i < outer_rows; i++) {
  666. lbValue dst = lb_emit_matrix_epi(p, res.addr, i, j);
  667. for (unsigned k = 0; k < inner; k++) {
  668. inners[k][0] = lb_emit_matrix_ev(p, lhs, i, k);
  669. inners[k][1] = lb_emit_matrix_ev(p, rhs, k, j);
  670. }
  671. lbValue sum = lb_const_nil(p->module, elem);
  672. for (unsigned k = 0; k < inner; k++) {
  673. lbValue a = inners[k][0];
  674. lbValue b = inners[k][1];
  675. sum = lb_emit_mul_add(p, a, b, sum, elem);
  676. }
  677. lb_emit_store(p, dst, sum);
  678. }
  679. }
  680. return lb_addr_load(p, res);
  681. }
  682. }
  683. gb_internal lbValue lb_emit_matrix_mul_vector(lbProcedure *p, lbValue lhs, lbValue rhs, Type *type) {
  684. // TODO(bill): Handle edge case for f16 types on x86(-64) platforms
  685. Type *mt = base_type(lhs.type);
  686. Type *vt = base_type(rhs.type);
  687. GB_ASSERT(is_type_matrix(mt));
  688. GB_ASSERT(is_type_array_like(vt));
  689. i64 vector_count = get_array_type_count(vt);
  690. GB_ASSERT(mt->Matrix.column_count == vector_count);
  691. GB_ASSERT(are_types_identical(mt->Matrix.elem, base_array_type(vt)));
  692. Type *elem = mt->Matrix.elem;
  693. if (lb_is_matrix_simdable(mt)) {
  694. unsigned stride = cast(unsigned)matrix_type_stride_in_elems(mt);
  695. unsigned row_count = cast(unsigned)mt->Matrix.row_count;
  696. unsigned column_count = cast(unsigned)mt->Matrix.column_count;
  697. auto m_columns = slice_make<LLVMValueRef>(permanent_allocator(), column_count);
  698. auto v_rows = slice_make<LLVMValueRef>(permanent_allocator(), column_count);
  699. LLVMValueRef matrix_vector = lb_matrix_to_vector(p, lhs);
  700. for (unsigned column_index = 0; column_index < column_count; column_index++) {
  701. LLVMValueRef mask = llvm_mask_iota(p->module, stride*column_index, row_count);
  702. LLVMValueRef column = llvm_basic_shuffle(p, matrix_vector, mask);
  703. m_columns[column_index] = column;
  704. }
  705. for (unsigned row_index = 0; row_index < column_count; row_index++) {
  706. LLVMValueRef value = lb_emit_struct_ev(p, rhs, row_index).value;
  707. LLVMValueRef row = llvm_vector_broadcast(p, value, row_count);
  708. v_rows[row_index] = row;
  709. }
  710. GB_ASSERT(column_count > 0);
  711. LLVMValueRef vector = nullptr;
  712. for (i64 i = 0; i < column_count; i++) {
  713. if (i == 0) {
  714. vector = llvm_vector_mul(p, m_columns[i], v_rows[i]);
  715. } else {
  716. vector = llvm_vector_mul_add(p, m_columns[i], v_rows[i], vector);
  717. }
  718. }
  719. return lb_matrix_cast_vector_to_type(p, vector, type);
  720. }
  721. lbAddr res = lb_add_local_generated(p, type, true);
  722. for (i64 i = 0; i < mt->Matrix.row_count; i++) {
  723. for (i64 j = 0; j < mt->Matrix.column_count; j++) {
  724. lbValue dst = lb_emit_matrix_epi(p, res.addr, i, 0);
  725. lbValue d0 = lb_emit_load(p, dst);
  726. lbValue a = lb_emit_matrix_ev(p, lhs, i, j);
  727. lbValue b = lb_emit_struct_ev(p, rhs, cast(i32)j);
  728. lbValue c = lb_emit_mul_add(p, a, b, d0, elem);
  729. lb_emit_store(p, dst, c);
  730. }
  731. }
  732. return lb_addr_load(p, res);
  733. }
  734. gb_internal lbValue lb_emit_vector_mul_matrix(lbProcedure *p, lbValue lhs, lbValue rhs, Type *type) {
  735. // TODO(bill): Handle edge case for f16 types on x86(-64) platforms
  736. Type *mt = base_type(rhs.type);
  737. Type *vt = base_type(lhs.type);
  738. GB_ASSERT(is_type_matrix(mt));
  739. GB_ASSERT(is_type_array_like(vt));
  740. i64 vector_count = get_array_type_count(vt);
  741. GB_ASSERT(vector_count == mt->Matrix.row_count);
  742. GB_ASSERT(are_types_identical(mt->Matrix.elem, base_array_type(vt)));
  743. Type *elem = mt->Matrix.elem;
  744. if (lb_is_matrix_simdable(mt)) {
  745. unsigned stride = cast(unsigned)matrix_type_stride_in_elems(mt);
  746. unsigned row_count = cast(unsigned)mt->Matrix.row_count;
  747. unsigned column_count = cast(unsigned)mt->Matrix.column_count; gb_unused(column_count);
  748. auto m_columns = slice_make<LLVMValueRef>(permanent_allocator(), row_count);
  749. auto v_rows = slice_make<LLVMValueRef>(permanent_allocator(), row_count);
  750. LLVMValueRef matrix_vector = lb_matrix_to_vector(p, rhs);
  751. auto mask_elems = slice_make<LLVMValueRef>(permanent_allocator(), column_count);
  752. for (unsigned row_index = 0; row_index < row_count; row_index++) {
  753. for (unsigned column_index = 0; column_index < column_count; column_index++) {
  754. unsigned offset = row_index + column_index*stride;
  755. mask_elems[column_index] = lb_const_int(p->module, t_u32, offset).value;
  756. }
  757. // transpose mask
  758. LLVMValueRef mask = LLVMConstVector(mask_elems.data, column_count);
  759. LLVMValueRef column = llvm_basic_shuffle(p, matrix_vector, mask);
  760. m_columns[row_index] = column;
  761. }
  762. for (unsigned column_index = 0; column_index < row_count; column_index++) {
  763. LLVMValueRef value = lb_emit_struct_ev(p, lhs, column_index).value;
  764. LLVMValueRef row = llvm_vector_broadcast(p, value, column_count);
  765. v_rows[column_index] = row;
  766. }
  767. GB_ASSERT(row_count > 0);
  768. LLVMValueRef vector = nullptr;
  769. for (i64 i = 0; i < row_count; i++) {
  770. if (i == 0) {
  771. vector = llvm_vector_mul(p, v_rows[i], m_columns[i]);
  772. } else {
  773. vector = llvm_vector_mul_add(p, v_rows[i], m_columns[i], vector);
  774. }
  775. }
  776. lbAddr res = lb_add_local_generated(p, type, true);
  777. LLVMValueRef res_ptr = res.addr.value;
  778. unsigned alignment = cast(unsigned)gb_max(type_align_of(type), lb_alignof(LLVMTypeOf(vector)));
  779. LLVMSetAlignment(res_ptr, alignment);
  780. res_ptr = LLVMBuildPointerCast(p->builder, res_ptr, LLVMPointerType(LLVMTypeOf(vector), 0), "");
  781. LLVMBuildStore(p->builder, vector, res_ptr);
  782. return lb_addr_load(p, res);
  783. }
  784. lbAddr res = lb_add_local_generated(p, type, true);
  785. for (i64 j = 0; j < mt->Matrix.column_count; j++) {
  786. for (i64 k = 0; k < mt->Matrix.row_count; k++) {
  787. lbValue dst = lb_emit_matrix_epi(p, res.addr, 0, j);
  788. lbValue d0 = lb_emit_load(p, dst);
  789. lbValue a = lb_emit_struct_ev(p, lhs, cast(i32)k);
  790. lbValue b = lb_emit_matrix_ev(p, rhs, k, j);
  791. lbValue c = lb_emit_mul_add(p, a, b, d0, elem);
  792. lb_emit_store(p, dst, c);
  793. }
  794. }
  795. return lb_addr_load(p, res);
  796. }
  797. gb_internal lbValue lb_emit_arith_matrix(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type, bool component_wise) {
  798. GB_ASSERT(is_type_matrix(lhs.type) || is_type_matrix(rhs.type));
  799. if (op == Token_Mul && !component_wise) {
  800. Type *xt = base_type(lhs.type);
  801. Type *yt = base_type(rhs.type);
  802. if (xt->kind == Type_Matrix) {
  803. if (yt->kind == Type_Matrix) {
  804. return lb_emit_matrix_mul(p, lhs, rhs, type);
  805. } else if (is_type_array_like(yt)) {
  806. return lb_emit_matrix_mul_vector(p, lhs, rhs, type);
  807. }
  808. } else if (is_type_array_like(xt)) {
  809. GB_ASSERT(yt->kind == Type_Matrix);
  810. return lb_emit_vector_mul_matrix(p, lhs, rhs, type);
  811. } else {
  812. GB_ASSERT(xt->kind == Type_Basic);
  813. GB_ASSERT(yt->kind == Type_Matrix);
  814. GB_ASSERT(is_type_matrix(type));
  815. Type *array_type = alloc_type_array(yt->Matrix.elem, matrix_type_total_internal_elems(yt));
  816. GB_ASSERT(type_size_of(array_type) == type_size_of(yt));
  817. lbValue array_lhs = lb_emit_conv(p, lhs, array_type);
  818. lbValue array_rhs = rhs;
  819. array_rhs.type = array_type;
  820. lbValue array = lb_emit_arith(p, op, array_lhs, array_rhs, array_type);
  821. array.type = type;
  822. return array;
  823. }
  824. } else {
  825. if (is_type_matrix(lhs.type)) {
  826. rhs = lb_emit_conv(p, rhs, lhs.type);
  827. } else {
  828. lhs = lb_emit_conv(p, lhs, rhs.type);
  829. }
  830. Type *xt = base_type(lhs.type);
  831. Type *yt = base_type(rhs.type);
  832. GB_ASSERT_MSG(are_types_identical(xt, yt), "%s %.*s %s", type_to_string(lhs.type), LIT(token_strings[op]), type_to_string(rhs.type));
  833. GB_ASSERT(xt->kind == Type_Matrix);
  834. // element-wise arithmetic
  835. // pretend it is an array
  836. lbValue array_lhs = lhs;
  837. lbValue array_rhs = rhs;
  838. Type *array_type = alloc_type_array(xt->Matrix.elem, matrix_type_total_internal_elems(xt));
  839. GB_ASSERT(type_size_of(array_type) == type_size_of(xt));
  840. array_lhs.type = array_type;
  841. array_rhs.type = array_type;
  842. if (token_is_comparison(op)) {
  843. lbValue res = lb_emit_comp(p, op, array_lhs, array_rhs);
  844. return lb_emit_conv(p, res, type);
  845. } else {
  846. lbValue array = lb_emit_arith(p, op, array_lhs, array_rhs, array_type);
  847. array.type = type;
  848. return array;
  849. }
  850. }
  851. GB_PANIC("TODO: lb_emit_arith_matrix");
  852. return {};
  853. }
  854. gb_internal lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) {
  855. if (is_type_array_like(lhs.type) || is_type_array_like(rhs.type)) {
  856. return lb_emit_arith_array(p, op, lhs, rhs, type);
  857. } else if (is_type_matrix(lhs.type) || is_type_matrix(rhs.type)) {
  858. return lb_emit_arith_matrix(p, op, lhs, rhs, type, false);
  859. } else if (is_type_complex(type)) {
  860. lhs = lb_emit_conv(p, lhs, type);
  861. rhs = lb_emit_conv(p, rhs, type);
  862. Type *ft = base_complex_elem_type(type);
  863. if (op == Token_Quo) {
  864. TEMPORARY_ALLOCATOR_GUARD();
  865. auto args = array_make<lbValue>(temporary_allocator(), 2);
  866. args[0] = lhs;
  867. args[1] = rhs;
  868. switch (type_size_of(ft)) {
  869. case 4: return lb_emit_runtime_call(p, "quo_complex64", args);
  870. case 8: return lb_emit_runtime_call(p, "quo_complex128", args);
  871. default: GB_PANIC("Unknown float type"); break;
  872. }
  873. }
  874. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  875. lbValue a = lb_emit_struct_ev(p, lhs, 0);
  876. lbValue b = lb_emit_struct_ev(p, lhs, 1);
  877. lbValue c = lb_emit_struct_ev(p, rhs, 0);
  878. lbValue d = lb_emit_struct_ev(p, rhs, 1);
  879. lbValue real = {};
  880. lbValue imag = {};
  881. switch (op) {
  882. case Token_Add:
  883. real = lb_emit_arith(p, Token_Add, a, c, ft);
  884. imag = lb_emit_arith(p, Token_Add, b, d, ft);
  885. break;
  886. case Token_Sub:
  887. real = lb_emit_arith(p, Token_Sub, a, c, ft);
  888. imag = lb_emit_arith(p, Token_Sub, b, d, ft);
  889. break;
  890. case Token_Mul: {
  891. lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft);
  892. lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft);
  893. real = lb_emit_arith(p, Token_Sub, x, y, ft);
  894. lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft);
  895. lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft);
  896. imag = lb_emit_arith(p, Token_Add, z, w, ft);
  897. break;
  898. }
  899. }
  900. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real);
  901. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag);
  902. return lb_addr_load(p, res);
  903. } else if (is_type_quaternion(type)) {
  904. lhs = lb_emit_conv(p, lhs, type);
  905. rhs = lb_emit_conv(p, rhs, type);
  906. Type *ft = base_complex_elem_type(type);
  907. if (op == Token_Add || op == Token_Sub) {
  908. lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later
  909. lbValue x0 = lb_emit_struct_ev(p, lhs, 0);
  910. lbValue x1 = lb_emit_struct_ev(p, lhs, 1);
  911. lbValue x2 = lb_emit_struct_ev(p, lhs, 2);
  912. lbValue x3 = lb_emit_struct_ev(p, lhs, 3);
  913. lbValue y0 = lb_emit_struct_ev(p, rhs, 0);
  914. lbValue y1 = lb_emit_struct_ev(p, rhs, 1);
  915. lbValue y2 = lb_emit_struct_ev(p, rhs, 2);
  916. lbValue y3 = lb_emit_struct_ev(p, rhs, 3);
  917. lbValue z0 = lb_emit_arith(p, op, x0, y0, ft);
  918. lbValue z1 = lb_emit_arith(p, op, x1, y1, ft);
  919. lbValue z2 = lb_emit_arith(p, op, x2, y2, ft);
  920. lbValue z3 = lb_emit_arith(p, op, x3, y3, ft);
  921. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0);
  922. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1);
  923. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2);
  924. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3);
  925. return lb_addr_load(p, res);
  926. } else if (op == Token_Mul) {
  927. TEMPORARY_ALLOCATOR_GUARD();
  928. auto args = array_make<lbValue>(temporary_allocator(), 2);
  929. args[0] = lhs;
  930. args[1] = rhs;
  931. switch (8*type_size_of(ft)) {
  932. case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args);
  933. case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args);
  934. default: GB_PANIC("Unknown float type"); break;
  935. }
  936. } else if (op == Token_Quo) {
  937. TEMPORARY_ALLOCATOR_GUARD();
  938. auto args = array_make<lbValue>(temporary_allocator(), 2);
  939. args[0] = lhs;
  940. args[1] = rhs;
  941. switch (8*type_size_of(ft)) {
  942. case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args);
  943. case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args);
  944. default: GB_PANIC("Unknown float type"); break;
  945. }
  946. }
  947. }
  948. lhs = lb_emit_conv(p, lhs, type);
  949. rhs = lb_emit_conv(p, rhs, type);
  950. if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) {
  951. switch (op) {
  952. case Token_AndNot:
  953. case Token_And:
  954. case Token_Or:
  955. case Token_Xor:
  956. goto handle_op;
  957. }
  958. Type *platform_type = integer_endian_type_to_platform_type(type);
  959. lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  960. lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  961. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  962. return lb_emit_byte_swap(p, res, type);
  963. }
  964. if (is_type_float(type) && is_type_different_to_arch_endianness(type)) {
  965. Type *platform_type = integer_endian_type_to_platform_type(type);
  966. lbValue x = lb_emit_conv(p, lhs, integer_endian_type_to_platform_type(lhs.type));
  967. lbValue y = lb_emit_conv(p, rhs, integer_endian_type_to_platform_type(rhs.type));
  968. lbValue res = lb_emit_arith(p, op, x, y, platform_type);
  969. return lb_emit_byte_swap(p, res, type);
  970. }
  971. handle_op:;
  972. lbValue res = {};
  973. res.type = type;
  974. // NOTE(bill): Bit Set Aliases for + and -
  975. if (is_type_bit_set(type)) {
  976. switch (op) {
  977. case Token_Add: op = Token_Or; break;
  978. case Token_Sub: op = Token_AndNot; break;
  979. }
  980. }
  981. Type *integral_type = type;
  982. if (is_type_simd_vector(integral_type)) {
  983. integral_type = core_array_type(integral_type);
  984. }
  985. switch (op) {
  986. case Token_Add:
  987. if (is_type_float(integral_type)) {
  988. res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, "");
  989. return res;
  990. }
  991. res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, "");
  992. return res;
  993. case Token_Sub:
  994. if (is_type_float(integral_type)) {
  995. res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, "");
  996. return res;
  997. }
  998. res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, "");
  999. return res;
  1000. case Token_Mul:
  1001. if (is_type_float(integral_type)) {
  1002. res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, "");
  1003. return res;
  1004. }
  1005. res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, "");
  1006. return res;
  1007. case Token_Quo:
  1008. if (is_type_float(integral_type)) {
  1009. res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, "");
  1010. return res;
  1011. } else if (is_type_unsigned(integral_type)) {
  1012. res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, "");
  1013. return res;
  1014. }
  1015. res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, "");
  1016. return res;
  1017. case Token_Mod:
  1018. if (is_type_float(integral_type)) {
  1019. res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, "");
  1020. return res;
  1021. } else if (is_type_unsigned(integral_type)) {
  1022. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  1023. return res;
  1024. }
  1025. res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  1026. return res;
  1027. case Token_ModMod:
  1028. if (is_type_unsigned(integral_type)) {
  1029. res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, "");
  1030. return res;
  1031. } else {
  1032. LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, "");
  1033. LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, "");
  1034. LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, "");
  1035. res.value = c;
  1036. return res;
  1037. }
  1038. case Token_And:
  1039. res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, "");
  1040. return res;
  1041. case Token_Or:
  1042. res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, "");
  1043. return res;
  1044. case Token_Xor:
  1045. res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, "");
  1046. return res;
  1047. case Token_Shl:
  1048. {
  1049. rhs = lb_emit_conv(p, rhs, lhs.type);
  1050. LLVMValueRef lhsval = lhs.value;
  1051. LLVMValueRef bits = rhs.value;
  1052. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  1053. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  1054. res.value = LLVMBuildShl(p->builder, lhsval, bits, "");
  1055. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  1056. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  1057. return res;
  1058. }
  1059. case Token_Shr:
  1060. {
  1061. rhs = lb_emit_conv(p, rhs, lhs.type);
  1062. LLVMValueRef lhsval = lhs.value;
  1063. LLVMValueRef bits = rhs.value;
  1064. bool is_unsigned = is_type_unsigned(integral_type);
  1065. LLVMValueRef bit_size = LLVMConstInt(lb_type(p->module, rhs.type), 8*type_size_of(lhs.type), false);
  1066. LLVMValueRef width_test = LLVMBuildICmp(p->builder, LLVMIntULT, bits, bit_size, "");
  1067. if (is_unsigned) {
  1068. res.value = LLVMBuildLShr(p->builder, lhsval, bits, "");
  1069. } else {
  1070. res.value = LLVMBuildAShr(p->builder, lhsval, bits, "");
  1071. }
  1072. LLVMValueRef zero = LLVMConstNull(lb_type(p->module, lhs.type));
  1073. res.value = LLVMBuildSelect(p->builder, width_test, res.value, zero, "");
  1074. return res;
  1075. }
  1076. case Token_AndNot:
  1077. {
  1078. LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, "");
  1079. res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, "");
  1080. return res;
  1081. }
  1082. break;
  1083. }
  1084. GB_PANIC("unhandled operator of lb_emit_arith");
  1085. return {};
  1086. }
  1087. gb_internal bool lb_is_empty_string_constant(Ast *expr) {
  1088. if (expr->tav.value.kind == ExactValue_String &&
  1089. is_type_string(expr->tav.type)) {
  1090. String s = expr->tav.value.value_string;
  1091. return s.len == 0;
  1092. }
  1093. return false;
  1094. }
  1095. gb_internal lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) {
  1096. ast_node(be, BinaryExpr, expr);
  1097. TypeAndValue tv = type_and_value_of_expr(expr);
  1098. if (is_type_matrix(be->left->tav.type) || is_type_matrix(be->right->tav.type)) {
  1099. lbValue left = lb_build_expr(p, be->left);
  1100. lbValue right = lb_build_expr(p, be->right);
  1101. return lb_emit_arith_matrix(p, be->op.kind, left, right, default_type(tv.type), false);
  1102. }
  1103. switch (be->op.kind) {
  1104. case Token_Add:
  1105. case Token_Sub:
  1106. case Token_Mul:
  1107. case Token_Quo:
  1108. case Token_Mod:
  1109. case Token_ModMod:
  1110. case Token_And:
  1111. case Token_Or:
  1112. case Token_Xor:
  1113. case Token_AndNot: {
  1114. Type *type = default_type(tv.type);
  1115. lbValue left = lb_build_expr(p, be->left);
  1116. lbValue right = lb_build_expr(p, be->right);
  1117. return lb_emit_arith(p, be->op.kind, left, right, type);
  1118. }
  1119. case Token_Shl:
  1120. case Token_Shr: {
  1121. lbValue left, right;
  1122. Type *type = default_type(tv.type);
  1123. left = lb_build_expr(p, be->left);
  1124. if (lb_is_expr_untyped_const(be->right)) {
  1125. // NOTE(bill): RHS shift operands can still be untyped
  1126. // Just bypass the standard lb_build_expr
  1127. right = lb_expr_untyped_const_to_typed(p->module, be->right, type);
  1128. } else {
  1129. right = lb_build_expr(p, be->right);
  1130. }
  1131. return lb_emit_arith(p, be->op.kind, left, right, type);
  1132. }
  1133. case Token_CmpEq:
  1134. case Token_NotEq:
  1135. if (is_type_untyped_nil(be->right->tav.type)) {
  1136. // `x == nil` or `x != nil`
  1137. lbValue left = lb_build_expr(p, be->left);
  1138. lbValue cmp = lb_emit_comp_against_nil(p, be->op.kind, left);
  1139. Type *type = default_type(tv.type);
  1140. return lb_emit_conv(p, cmp, type);
  1141. } else if (is_type_untyped_nil(be->left->tav.type)) {
  1142. // `nil == x` or `nil != x`
  1143. lbValue right = lb_build_expr(p, be->right);
  1144. lbValue cmp = lb_emit_comp_against_nil(p, be->op.kind, right);
  1145. Type *type = default_type(tv.type);
  1146. return lb_emit_conv(p, cmp, type);
  1147. } else if (lb_is_empty_string_constant(be->right)) {
  1148. // `x == ""` or `x != ""`
  1149. lbValue s = lb_build_expr(p, be->left);
  1150. s = lb_emit_conv(p, s, t_string);
  1151. lbValue len = lb_string_len(p, s);
  1152. lbValue cmp = lb_emit_comp(p, be->op.kind, len, lb_const_int(p->module, t_int, 0));
  1153. Type *type = default_type(tv.type);
  1154. return lb_emit_conv(p, cmp, type);
  1155. } else if (lb_is_empty_string_constant(be->left)) {
  1156. // `"" == x` or `"" != x`
  1157. lbValue s = lb_build_expr(p, be->right);
  1158. s = lb_emit_conv(p, s, t_string);
  1159. lbValue len = lb_string_len(p, s);
  1160. lbValue cmp = lb_emit_comp(p, be->op.kind, len, lb_const_int(p->module, t_int, 0));
  1161. Type *type = default_type(tv.type);
  1162. return lb_emit_conv(p, cmp, type);
  1163. }
  1164. /*fallthrough*/
  1165. case Token_Lt:
  1166. case Token_LtEq:
  1167. case Token_Gt:
  1168. case Token_GtEq:
  1169. {
  1170. lbValue left = {};
  1171. lbValue right = {};
  1172. if (be->left->tav.mode == Addressing_Type) {
  1173. left = lb_typeid(p->module, be->left->tav.type);
  1174. }
  1175. if (be->right->tav.mode == Addressing_Type) {
  1176. right = lb_typeid(p->module, be->right->tav.type);
  1177. }
  1178. if (left.value == nullptr) left = lb_build_expr(p, be->left);
  1179. if (right.value == nullptr) right = lb_build_expr(p, be->right);
  1180. lbValue cmp = lb_emit_comp(p, be->op.kind, left, right);
  1181. Type *type = default_type(tv.type);
  1182. return lb_emit_conv(p, cmp, type);
  1183. }
  1184. case Token_CmpAnd:
  1185. case Token_CmpOr:
  1186. return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type);
  1187. case Token_in:
  1188. case Token_not_in:
  1189. {
  1190. lbValue left = lb_build_expr(p, be->left);
  1191. lbValue right = lb_build_expr(p, be->right);
  1192. Type *rt = base_type(right.type);
  1193. if (is_type_pointer(rt)) {
  1194. right = lb_emit_load(p, right);
  1195. rt = base_type(type_deref(rt));
  1196. }
  1197. switch (rt->kind) {
  1198. case Type_Map:
  1199. {
  1200. lbValue map_ptr = lb_address_from_load_or_generate_local(p, right);
  1201. lbValue key = left;
  1202. lbValue ptr = lb_internal_dynamic_map_get_ptr(p, map_ptr, key);
  1203. if (be->op.kind == Token_in) {
  1204. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  1205. } else {
  1206. return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool);
  1207. }
  1208. }
  1209. break;
  1210. case Type_BitSet:
  1211. {
  1212. Type *key_type = rt->BitSet.elem;
  1213. GB_ASSERT(are_types_identical(left.type, key_type));
  1214. Type *it = bit_set_to_int(rt);
  1215. left = lb_emit_conv(p, left, it);
  1216. if (is_type_different_to_arch_endianness(it)) {
  1217. left = lb_emit_byte_swap(p, left, integer_endian_type_to_platform_type(it));
  1218. }
  1219. lbValue lower = lb_const_value(p->module, left.type, exact_value_i64(rt->BitSet.lower));
  1220. lbValue key = lb_emit_arith(p, Token_Sub, left, lower, left.type);
  1221. lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, left.type, 1), key, left.type);
  1222. bit = lb_emit_conv(p, bit, it);
  1223. lbValue old_value = lb_emit_transmute(p, right, it);
  1224. lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it);
  1225. if (be->op.kind == Token_in) {
  1226. return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  1227. } else {
  1228. return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool);
  1229. }
  1230. }
  1231. break;
  1232. default:
  1233. GB_PANIC("Invalid 'in' type");
  1234. }
  1235. break;
  1236. }
  1237. break;
  1238. default:
  1239. GB_PANIC("Invalid binary expression");
  1240. break;
  1241. }
  1242. return {};
  1243. }
  1244. gb_internal lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) {
  1245. lbModule *m = p->module;
  1246. t = reduce_tuple_to_single_type(t);
  1247. Type *src_type = value.type;
  1248. if (are_types_identical(t, src_type)) {
  1249. return value;
  1250. }
  1251. Type *src = core_type(src_type);
  1252. Type *dst = core_type(t);
  1253. GB_ASSERT(src != nullptr);
  1254. GB_ASSERT(dst != nullptr);
  1255. if (is_type_untyped_uninit(src)) {
  1256. return lb_const_undef(m, t);
  1257. }
  1258. if (is_type_untyped_nil(src)) {
  1259. return lb_const_nil(m, t);
  1260. }
  1261. if (LLVMIsConstant(value.value)) {
  1262. if (is_type_any(dst)) {
  1263. Type *st = default_type(src_type);
  1264. lbAddr default_value = lb_add_local_generated(p, st, false);
  1265. lb_addr_store(p, default_value, value);
  1266. lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr);
  1267. lbValue id = lb_typeid(m, st);
  1268. lbAddr res = lb_add_local_generated(p, t, false);
  1269. lbValue a0 = lb_emit_struct_ep(p, res.addr, 0);
  1270. lbValue a1 = lb_emit_struct_ep(p, res.addr, 1);
  1271. lb_emit_store(p, a0, data);
  1272. lb_emit_store(p, a1, id);
  1273. return lb_addr_load(p, res);
  1274. } else if (dst->kind == Type_Basic) {
  1275. if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) {
  1276. String str = lb_get_const_string(m, value);
  1277. lbValue res = {};
  1278. res.type = t;
  1279. res.value = llvm_cstring(m, str);
  1280. return res;
  1281. }
  1282. // if (is_type_float(dst)) {
  1283. // return value;
  1284. // } else if (is_type_integer(dst)) {
  1285. // return value;
  1286. // }
  1287. // ExactValue ev = value->Constant.value;
  1288. // if (is_type_float(dst)) {
  1289. // ev = exact_value_to_float(ev);
  1290. // } else if (is_type_complex(dst)) {
  1291. // ev = exact_value_to_complex(ev);
  1292. // } else if (is_type_quaternion(dst)) {
  1293. // ev = exact_value_to_quaternion(ev);
  1294. // } else if (is_type_string(dst)) {
  1295. // // Handled elsewhere
  1296. // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind);
  1297. // } else if (is_type_integer(dst)) {
  1298. // ev = exact_value_to_integer(ev);
  1299. // } else if (is_type_pointer(dst)) {
  1300. // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null'
  1301. // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev);
  1302. // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst));
  1303. // }
  1304. // return lb_const_value(p->module, t, ev);
  1305. }
  1306. }
  1307. if (are_types_identical(src, dst)) {
  1308. if (!are_types_identical(src_type, t)) {
  1309. return lb_emit_transmute(p, value, t);
  1310. }
  1311. return value;
  1312. }
  1313. // bool <-> llvm bool
  1314. if (is_type_boolean(src) && dst == t_llvm_bool) {
  1315. lbValue res = {};
  1316. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, src)), "");
  1317. res.type = t;
  1318. return res;
  1319. }
  1320. if (src == t_llvm_bool && is_type_boolean(dst)) {
  1321. lbValue res = {};
  1322. res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), "");
  1323. res.type = t;
  1324. return res;
  1325. }
  1326. // integer -> integer
  1327. if (is_type_integer(src) && is_type_integer(dst)) {
  1328. GB_ASSERT(src->kind == Type_Basic &&
  1329. dst->kind == Type_Basic);
  1330. i64 sz = type_size_of(default_type(src));
  1331. i64 dz = type_size_of(default_type(dst));
  1332. if (sz == dz) {
  1333. if (dz > 1 && !types_have_same_internal_endian(src, dst)) {
  1334. return lb_emit_byte_swap(p, value, t);
  1335. }
  1336. lbValue res = {};
  1337. res.value = value.value;
  1338. res.type = t;
  1339. return res;
  1340. }
  1341. if (sz > 1 && is_type_different_to_arch_endianness(src)) {
  1342. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  1343. value = lb_emit_byte_swap(p, value, platform_src_type);
  1344. }
  1345. LLVMOpcode op = LLVMTrunc;
  1346. if (dz < sz) {
  1347. op = LLVMTrunc;
  1348. } else if (dz == sz) {
  1349. // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment
  1350. // NOTE(bill): Copy the value just for type correctness
  1351. op = LLVMBitCast;
  1352. } else if (dz > sz) {
  1353. op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent
  1354. }
  1355. if (dz > 1 && is_type_different_to_arch_endianness(dst)) {
  1356. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  1357. lbValue res = {};
  1358. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), "");
  1359. res.type = t;
  1360. return lb_emit_byte_swap(p, res, t);
  1361. } else {
  1362. lbValue res = {};
  1363. res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), "");
  1364. res.type = t;
  1365. return res;
  1366. }
  1367. }
  1368. // boolean -> boolean/integer
  1369. if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) {
  1370. LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  1371. lbValue res = {};
  1372. res.value = LLVMBuildIntCast2(p->builder, b, lb_type(m, t), false, "");
  1373. res.type = t;
  1374. return res;
  1375. }
  1376. if (is_type_cstring(src) && is_type_u8_ptr(dst)) {
  1377. return lb_emit_transmute(p, value, dst);
  1378. }
  1379. if (is_type_u8_ptr(src) && is_type_cstring(dst)) {
  1380. return lb_emit_transmute(p, value, dst);
  1381. }
  1382. if (is_type_cstring(src) && is_type_u8_multi_ptr(dst)) {
  1383. return lb_emit_transmute(p, value, dst);
  1384. }
  1385. if (is_type_u8_multi_ptr(src) && is_type_cstring(dst)) {
  1386. return lb_emit_transmute(p, value, dst);
  1387. }
  1388. if (is_type_cstring(src) && is_type_rawptr(dst)) {
  1389. return lb_emit_transmute(p, value, dst);
  1390. }
  1391. if (is_type_rawptr(src) && is_type_cstring(dst)) {
  1392. return lb_emit_transmute(p, value, dst);
  1393. }
  1394. if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) {
  1395. TEMPORARY_ALLOCATOR_GUARD();
  1396. lbValue c = lb_emit_conv(p, value, t_cstring);
  1397. auto args = array_make<lbValue>(temporary_allocator(), 1);
  1398. args[0] = c;
  1399. lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args);
  1400. return lb_emit_conv(p, s, dst);
  1401. }
  1402. // integer -> boolean
  1403. if (is_type_integer(src) && is_type_boolean(dst)) {
  1404. lbValue res = {};
  1405. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), "");
  1406. res.type = t_llvm_bool;
  1407. return lb_emit_conv(p, res, t);
  1408. }
  1409. // float -> float
  1410. if (is_type_float(src) && is_type_float(dst)) {
  1411. i64 sz = type_size_of(src);
  1412. i64 dz = type_size_of(dst);
  1413. if (dz == sz) {
  1414. if (types_have_same_internal_endian(src, dst)) {
  1415. lbValue res = {};
  1416. res.type = t;
  1417. res.value = value.value;
  1418. return res;
  1419. } else {
  1420. return lb_emit_byte_swap(p, value, t);
  1421. }
  1422. }
  1423. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  1424. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  1425. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  1426. lbValue res = {};
  1427. res = lb_emit_conv(p, value, platform_src_type);
  1428. res = lb_emit_conv(p, res, platform_dst_type);
  1429. if (is_type_different_to_arch_endianness(dst)) {
  1430. res = lb_emit_byte_swap(p, res, t);
  1431. }
  1432. return lb_emit_conv(p, res, t);
  1433. }
  1434. lbValue res = {};
  1435. res.type = t;
  1436. if (dz >= sz) {
  1437. res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), "");
  1438. } else {
  1439. res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), "");
  1440. }
  1441. return res;
  1442. }
  1443. if (is_type_complex(src) && is_type_complex(dst)) {
  1444. Type *ft = base_complex_elem_type(dst);
  1445. lbAddr gen = lb_add_local_generated(p, t, false);
  1446. lbValue gp = lb_addr_get_ptr(p, gen);
  1447. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  1448. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  1449. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  1450. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag);
  1451. return lb_addr_load(p, gen);
  1452. }
  1453. if (is_type_quaternion(src) && is_type_quaternion(dst)) {
  1454. // @QuaternionLayout
  1455. Type *ft = base_complex_elem_type(dst);
  1456. lbAddr gen = lb_add_local_generated(p, t, false);
  1457. lbValue gp = lb_addr_get_ptr(p, gen);
  1458. lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  1459. lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  1460. lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft);
  1461. lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft);
  1462. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0);
  1463. lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1);
  1464. lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2);
  1465. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3);
  1466. return lb_addr_load(p, gen);
  1467. }
  1468. if (is_type_integer(src) && is_type_complex(dst)) {
  1469. Type *ft = base_complex_elem_type(dst);
  1470. lbAddr gen = lb_add_local_generated(p, t, true);
  1471. lbValue gp = lb_addr_get_ptr(p, gen);
  1472. lbValue real = lb_emit_conv(p, value, ft);
  1473. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  1474. return lb_addr_load(p, gen);
  1475. }
  1476. if (is_type_float(src) && is_type_complex(dst)) {
  1477. Type *ft = base_complex_elem_type(dst);
  1478. lbAddr gen = lb_add_local_generated(p, t, true);
  1479. lbValue gp = lb_addr_get_ptr(p, gen);
  1480. lbValue real = lb_emit_conv(p, value, ft);
  1481. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real);
  1482. return lb_addr_load(p, gen);
  1483. }
  1484. if (is_type_integer(src) && is_type_quaternion(dst)) {
  1485. Type *ft = base_complex_elem_type(dst);
  1486. lbAddr gen = lb_add_local_generated(p, t, true);
  1487. lbValue gp = lb_addr_get_ptr(p, gen);
  1488. lbValue real = lb_emit_conv(p, value, ft);
  1489. // @QuaternionLayout
  1490. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  1491. return lb_addr_load(p, gen);
  1492. }
  1493. if (is_type_float(src) && is_type_quaternion(dst)) {
  1494. Type *ft = base_complex_elem_type(dst);
  1495. lbAddr gen = lb_add_local_generated(p, t, true);
  1496. lbValue gp = lb_addr_get_ptr(p, gen);
  1497. lbValue real = lb_emit_conv(p, value, ft);
  1498. // @QuaternionLayout
  1499. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  1500. return lb_addr_load(p, gen);
  1501. }
  1502. if (is_type_complex(src) && is_type_quaternion(dst)) {
  1503. Type *ft = base_complex_elem_type(dst);
  1504. lbAddr gen = lb_add_local_generated(p, t, true);
  1505. lbValue gp = lb_addr_get_ptr(p, gen);
  1506. lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft);
  1507. lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft);
  1508. // @QuaternionLayout
  1509. lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real);
  1510. lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag);
  1511. return lb_addr_load(p, gen);
  1512. }
  1513. // float <-> integer
  1514. if (is_type_float(src) && is_type_integer(dst)) {
  1515. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  1516. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  1517. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  1518. lbValue res = {};
  1519. res = lb_emit_conv(p, value, platform_src_type);
  1520. res = lb_emit_conv(p, res, platform_dst_type);
  1521. return lb_emit_conv(p, res, t);
  1522. }
  1523. if (is_type_integer_128bit(dst)) {
  1524. TEMPORARY_ALLOCATOR_GUARD();
  1525. auto args = array_make<lbValue>(temporary_allocator(), 1);
  1526. args[0] = value;
  1527. char const *call = "fixunsdfdi";
  1528. if (is_type_unsigned(dst)) {
  1529. call = "fixunsdfti";
  1530. }
  1531. lbValue res_i128 = lb_emit_runtime_call(p, call, args);
  1532. return lb_emit_conv(p, res_i128, t);
  1533. }
  1534. lbValue res = {};
  1535. res.type = t;
  1536. if (is_type_unsigned(dst)) {
  1537. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  1538. } else {
  1539. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  1540. }
  1541. return res;
  1542. }
  1543. if (is_type_integer(src) && is_type_float(dst)) {
  1544. if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) {
  1545. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  1546. Type *platform_dst_type = integer_endian_type_to_platform_type(dst);
  1547. lbValue res = {};
  1548. res = lb_emit_conv(p, value, platform_src_type);
  1549. res = lb_emit_conv(p, res, platform_dst_type);
  1550. if (is_type_different_to_arch_endianness(dst)) {
  1551. res = lb_emit_byte_swap(p, res, t);
  1552. }
  1553. return lb_emit_conv(p, res, t);
  1554. }
  1555. if (is_type_integer_128bit(src)) {
  1556. TEMPORARY_ALLOCATOR_GUARD();
  1557. auto args = array_make<lbValue>(temporary_allocator(), 1);
  1558. args[0] = value;
  1559. char const *call = "floattidf";
  1560. if (is_type_unsigned(src)) {
  1561. call = "floattidf_unsigned";
  1562. }
  1563. lbValue res_f64 = lb_emit_runtime_call(p, call, args);
  1564. return lb_emit_conv(p, res_f64, t);
  1565. }
  1566. lbValue res = {};
  1567. res.type = t;
  1568. if (is_type_unsigned(src)) {
  1569. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  1570. } else {
  1571. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  1572. }
  1573. return res;
  1574. }
  1575. if (is_type_simd_vector(dst)) {
  1576. Type *et = base_array_type(dst);
  1577. if (is_type_simd_vector(src)) {
  1578. Type *src_elem = core_array_type(src);
  1579. Type *dst_elem = core_array_type(dst);
  1580. GB_ASSERT(src->SimdVector.count == dst->SimdVector.count);
  1581. lbValue res = {};
  1582. res.type = t;
  1583. if (are_types_identical(src_elem, dst_elem)) {
  1584. res.value = value.value;
  1585. } else if (is_type_float(src_elem) && is_type_integer(dst_elem)) {
  1586. if (is_type_unsigned(dst_elem)) {
  1587. res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), "");
  1588. } else {
  1589. res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), "");
  1590. }
  1591. } else if (is_type_integer(src_elem) && is_type_float(dst_elem)) {
  1592. if (is_type_unsigned(src_elem)) {
  1593. res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), "");
  1594. } else {
  1595. res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), "");
  1596. }
  1597. } else if ((is_type_integer(src_elem) || is_type_boolean(src_elem)) && is_type_integer(dst_elem)) {
  1598. res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), !is_type_unsigned(src_elem), "");
  1599. } else if (is_type_float(src_elem) && is_type_float(dst_elem)) {
  1600. res.value = LLVMBuildFPCast(p->builder, value.value, lb_type(m, t), "");
  1601. } else if (is_type_integer(src_elem) && is_type_boolean(dst_elem)) {
  1602. LLVMValueRef i1vector = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(LLVMTypeOf(value.value)), "");
  1603. res.value = LLVMBuildIntCast2(p->builder, i1vector, lb_type(m, t), !is_type_unsigned(src_elem), "");
  1604. } else {
  1605. GB_PANIC("Unhandled simd vector conversion: %s -> %s", type_to_string(src), type_to_string(dst));
  1606. }
  1607. return res;
  1608. } else {
  1609. i64 count = get_array_type_count(dst);
  1610. LLVMTypeRef vt = lb_type(m, t);
  1611. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1612. LLVMValueRef elem = lb_emit_conv(p, value, et).value;
  1613. LLVMValueRef vector = LLVMConstNull(vt);
  1614. for (i64 i = 0; i < count; i++) {
  1615. LLVMValueRef idx = LLVMConstInt(llvm_u32, i, false);
  1616. vector = LLVMBuildInsertElement(p->builder, vector, elem, idx, "");
  1617. }
  1618. lbValue res = {};
  1619. res.type = t;
  1620. res.value = vector;
  1621. return res;
  1622. }
  1623. }
  1624. // Pointer <-> uintptr
  1625. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  1626. lbValue res = {};
  1627. res.type = t;
  1628. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  1629. return res;
  1630. }
  1631. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  1632. lbValue res = {};
  1633. res.type = t;
  1634. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  1635. return res;
  1636. }
  1637. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  1638. lbValue res = {};
  1639. res.type = t;
  1640. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  1641. return res;
  1642. }
  1643. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  1644. lbValue res = {};
  1645. res.type = t;
  1646. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  1647. return res;
  1648. }
  1649. if (is_type_union(dst)) {
  1650. for (Type *vt : dst->Union.variants) {
  1651. if (are_types_identical(vt, src_type)) {
  1652. lbAddr parent = lb_add_local_generated(p, t, true);
  1653. lb_emit_store_union_variant(p, parent.addr, value, vt);
  1654. return lb_addr_load(p, parent);
  1655. }
  1656. }
  1657. if (dst->Union.variants.count == 1) {
  1658. Type *vt = dst->Union.variants[0];
  1659. if (internal_check_is_assignable_to(src_type, vt)) {
  1660. value = lb_emit_conv(p, value, vt);
  1661. lbAddr parent = lb_add_local_generated(p, t, true);
  1662. lb_emit_store_union_variant(p, parent.addr, value, vt);
  1663. return lb_addr_load(p, parent);
  1664. }
  1665. }
  1666. }
  1667. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  1668. // subtype polymorphism casting
  1669. if (check_is_assignable_to_using_subtype(src_type, t)) {
  1670. Type *st = type_deref(src_type);
  1671. st = type_deref(st);
  1672. bool st_is_ptr = is_type_pointer(src_type);
  1673. st = base_type(st);
  1674. Type *dt = t;
  1675. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  1676. Selection sel = {};
  1677. sel.index.allocator = heap_allocator();
  1678. defer (array_free(&sel.index));
  1679. if (lookup_subtype_polymorphic_selection(t, src_type, &sel)) {
  1680. if (sel.entity == nullptr) {
  1681. GB_PANIC("invalid subtype cast %s -> ", type_to_string(src_type), type_to_string(t));
  1682. }
  1683. if (st_is_ptr) {
  1684. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  1685. Type *rt = res.type;
  1686. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  1687. res = lb_emit_load(p, res);
  1688. }
  1689. return res;
  1690. } else {
  1691. if (is_type_pointer(value.type)) {
  1692. Type *rt = value.type;
  1693. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  1694. value = lb_emit_load(p, value);
  1695. } else {
  1696. value = lb_emit_deep_field_gep(p, value, sel);
  1697. return lb_emit_load(p, value);
  1698. }
  1699. }
  1700. return lb_emit_deep_field_ev(p, value, sel);
  1701. }
  1702. }
  1703. }
  1704. // Pointer <-> Pointer
  1705. if (is_type_pointer(src) && is_type_pointer(dst)) {
  1706. lbValue res = {};
  1707. res.type = t;
  1708. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1709. return res;
  1710. }
  1711. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  1712. lbValue res = {};
  1713. res.type = t;
  1714. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1715. return res;
  1716. }
  1717. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  1718. lbValue res = {};
  1719. res.type = t;
  1720. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1721. return res;
  1722. }
  1723. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  1724. lbValue res = {};
  1725. res.type = t;
  1726. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1727. return res;
  1728. }
  1729. // proc <-> proc
  1730. if (is_type_proc(src) && is_type_proc(dst)) {
  1731. lbValue res = {};
  1732. res.type = t;
  1733. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1734. return res;
  1735. }
  1736. // pointer -> proc
  1737. if (is_type_pointer(src) && is_type_proc(dst)) {
  1738. lbValue res = {};
  1739. res.type = t;
  1740. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1741. return res;
  1742. }
  1743. // proc -> pointer
  1744. if (is_type_proc(src) && is_type_pointer(dst)) {
  1745. lbValue res = {};
  1746. res.type = t;
  1747. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1748. return res;
  1749. }
  1750. // []byte/[]u8 <-> string
  1751. if (is_type_u8_slice(src) && is_type_string(dst)) {
  1752. return lb_emit_transmute(p, value, t);
  1753. }
  1754. if (is_type_string(src) && is_type_u8_slice(dst)) {
  1755. return lb_emit_transmute(p, value, t);
  1756. }
  1757. if (is_type_array_like(dst)) {
  1758. Type *elem = base_array_type(dst);
  1759. lbValue e = lb_emit_conv(p, value, elem);
  1760. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1761. lbAddr v = lb_add_local_generated(p, t, false);
  1762. isize index_count = cast(isize)get_array_type_count(dst);
  1763. for (isize i = 0; i < index_count; i++) {
  1764. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  1765. lb_emit_store(p, elem, e);
  1766. }
  1767. return lb_addr_load(p, v);
  1768. }
  1769. if (is_type_matrix(dst) && !is_type_matrix(src)) {
  1770. GB_ASSERT_MSG(dst->Matrix.row_count == dst->Matrix.column_count, "%s <- %s", type_to_string(dst), type_to_string(src));
  1771. Type *elem = base_array_type(dst);
  1772. lbValue e = lb_emit_conv(p, value, elem);
  1773. lbAddr v = lb_add_local_generated(p, t, false);
  1774. lbValue zero = lb_const_value(p->module, elem, exact_value_i64(0), true);
  1775. for (i64 j = 0; j < dst->Matrix.column_count; j++) {
  1776. for (i64 i = 0; i < dst->Matrix.row_count; i++) {
  1777. lbValue ptr = lb_emit_matrix_epi(p, v.addr, i, j);
  1778. lb_emit_store(p, ptr, i == j ? e : zero);
  1779. }
  1780. }
  1781. return lb_addr_load(p, v);
  1782. }
  1783. if (is_type_matrix(dst) && is_type_matrix(src)) {
  1784. GB_ASSERT(dst->kind == Type_Matrix);
  1785. GB_ASSERT(src->kind == Type_Matrix);
  1786. lbAddr v = lb_add_local_generated(p, t, true);
  1787. if (is_matrix_square(dst) && is_matrix_square(dst)) {
  1788. for (i64 j = 0; j < dst->Matrix.column_count; j++) {
  1789. for (i64 i = 0; i < dst->Matrix.row_count; i++) {
  1790. if (i < src->Matrix.row_count && j < src->Matrix.column_count) {
  1791. lbValue d = lb_emit_matrix_epi(p, v.addr, i, j);
  1792. lbValue s = lb_emit_matrix_ev(p, value, i, j);
  1793. lb_emit_store(p, d, s);
  1794. } else if (i == j) {
  1795. lbValue d = lb_emit_matrix_epi(p, v.addr, i, j);
  1796. lbValue s = lb_const_value(p->module, dst->Matrix.elem, exact_value_i64(1), true);
  1797. lb_emit_store(p, d, s);
  1798. }
  1799. }
  1800. }
  1801. } else {
  1802. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  1803. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  1804. GB_ASSERT(dst_count == src_count);
  1805. lbValue pdst = v.addr;
  1806. lbValue psrc = lb_address_from_load_or_generate_local(p, value);
  1807. bool same_elem_base_types = are_types_identical(
  1808. base_type(dst->Matrix.elem),
  1809. base_type(src->Matrix.elem)
  1810. );
  1811. if (same_elem_base_types && type_size_of(dst) == type_size_of(src)) {
  1812. lb_mem_copy_overlapping(p, v.addr, psrc, lb_const_int(p->module, t_int, type_size_of(dst)));
  1813. } else {
  1814. for (i64 i = 0; i < src_count; i++) {
  1815. lbValue dp = lb_emit_array_epi(p, v.addr, matrix_column_major_index_to_offset(dst, i));
  1816. lbValue sp = lb_emit_array_epi(p, psrc, matrix_column_major_index_to_offset(src, i));
  1817. lbValue s = lb_emit_load(p, sp);
  1818. s = lb_emit_conv(p, s, dst->Matrix.elem);
  1819. lb_emit_store(p, dp, s);
  1820. }
  1821. }
  1822. }
  1823. return lb_addr_load(p, v);
  1824. }
  1825. if (is_type_any(dst)) {
  1826. if (is_type_untyped_uninit(src)) {
  1827. return lb_const_undef(p->module, t);
  1828. }
  1829. if (is_type_untyped_nil(src)) {
  1830. return lb_const_nil(p->module, t);
  1831. }
  1832. lbAddr result = lb_add_local_generated(p, t, true);
  1833. Type *st = default_type(src_type);
  1834. lbValue data = lb_address_from_load_or_generate_local(p, value);
  1835. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  1836. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  1837. data = lb_emit_conv(p, data, t_rawptr);
  1838. lbValue id = lb_typeid(p->module, st);
  1839. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  1840. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  1841. lb_emit_store(p, any_data, data);
  1842. lb_emit_store(p, any_id, id);
  1843. return lb_addr_load(p, result);
  1844. }
  1845. i64 src_sz = type_size_of(src);
  1846. i64 dst_sz = type_size_of(dst);
  1847. if (src_sz == dst_sz) {
  1848. // bit_set <-> integer
  1849. if (is_type_integer(src) && is_type_bit_set(dst)) {
  1850. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  1851. res.type = t;
  1852. return res;
  1853. }
  1854. if (is_type_bit_set(src) && is_type_integer(dst)) {
  1855. lbValue bs = value;
  1856. bs.type = bit_set_to_int(src);
  1857. return lb_emit_conv(p, bs, dst);
  1858. }
  1859. // typeid <-> integer
  1860. if (is_type_integer(src) && is_type_typeid(dst)) {
  1861. return lb_emit_transmute(p, value, dst);
  1862. }
  1863. if (is_type_typeid(src) && is_type_integer(dst)) {
  1864. return lb_emit_transmute(p, value, dst);
  1865. }
  1866. }
  1867. if (is_type_untyped(src)) {
  1868. if (is_type_string(src) && is_type_string(dst)) {
  1869. lbAddr result = lb_add_local_generated(p, t, false);
  1870. lb_addr_store(p, result, value);
  1871. return lb_addr_load(p, result);
  1872. }
  1873. }
  1874. gb_printf_err("%.*s\n", LIT(p->name));
  1875. gb_printf_err("lb_emit_conv: src -> dst\n");
  1876. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  1877. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  1878. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  1879. gb_printf_err("Not Identical %p != %p\n", src, dst);
  1880. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  1881. type_to_string(src_type), type_to_string(t),
  1882. LIT(p->name));
  1883. return {};
  1884. }
  1885. gb_internal lbValue lb_compare_records(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right, Type *type) {
  1886. GB_ASSERT((is_type_struct(type) || is_type_union(type)) && is_type_comparable(type));
  1887. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  1888. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  1889. lbValue res = {};
  1890. if (type_size_of(type) == 0) {
  1891. switch (op_kind) {
  1892. case Token_CmpEq:
  1893. return lb_const_bool(p->module, t_bool, true);
  1894. case Token_NotEq:
  1895. return lb_const_bool(p->module, t_bool, false);
  1896. }
  1897. GB_PANIC("invalid operator");
  1898. }
  1899. TEMPORARY_ALLOCATOR_GUARD();
  1900. if (is_type_simple_compare(type)) {
  1901. // TODO(bill): Test to see if this is actually faster!!!!
  1902. auto args = array_make<lbValue>(temporary_allocator(), 3);
  1903. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  1904. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  1905. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  1906. res = lb_emit_runtime_call(p, "memory_equal", args);
  1907. } else {
  1908. lbValue value = lb_equal_proc_for_type(p->module, type);
  1909. auto args = array_make<lbValue>(temporary_allocator(), 2);
  1910. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  1911. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  1912. res = lb_emit_call(p, value, args);
  1913. }
  1914. if (op_kind == Token_NotEq) {
  1915. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  1916. }
  1917. return res;
  1918. }
  1919. gb_internal lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  1920. Type *a = core_type(left.type);
  1921. Type *b = core_type(right.type);
  1922. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  1923. lbValue nil_check = {};
  1924. if (is_type_array_like(left.type) || is_type_array_like(right.type)) {
  1925. // don't do `nil` check if it is array-like
  1926. } else if (is_type_untyped_nil(left.type)) {
  1927. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  1928. } else if (is_type_untyped_nil(right.type)) {
  1929. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  1930. }
  1931. if (nil_check.value != nullptr) {
  1932. return nil_check;
  1933. }
  1934. if (are_types_identical(a, b)) {
  1935. // NOTE(bill): No need for a conversion
  1936. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  1937. left = lb_emit_conv(p, left, right.type);
  1938. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  1939. right = lb_emit_conv(p, right, left.type);
  1940. } else {
  1941. Type *lt = left.type;
  1942. Type *rt = right.type;
  1943. lt = left.type;
  1944. rt = right.type;
  1945. i64 ls = type_size_of(lt);
  1946. i64 rs = type_size_of(rt);
  1947. // NOTE(bill): Quick heuristic, larger types are usually the target type
  1948. if (ls < rs) {
  1949. left = lb_emit_conv(p, left, rt);
  1950. } else if (ls > rs) {
  1951. right = lb_emit_conv(p, right, lt);
  1952. } else {
  1953. if (is_type_union(rt)) {
  1954. left = lb_emit_conv(p, left, rt);
  1955. } else {
  1956. right = lb_emit_conv(p, right, lt);
  1957. }
  1958. }
  1959. }
  1960. a = core_type(left.type);
  1961. b = core_type(right.type);
  1962. if (is_type_matrix(a) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  1963. Type *tl = base_type(a);
  1964. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  1965. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  1966. // TODO(bill): Test to see if this is actually faster!!!!
  1967. auto args = array_make<lbValue>(permanent_allocator(), 3);
  1968. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  1969. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  1970. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  1971. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  1972. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  1973. return lb_emit_conv(p, res, t_bool);
  1974. }
  1975. if (is_type_array_like(a)) {
  1976. Type *tl = base_type(a);
  1977. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  1978. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  1979. TokenKind cmp_op = Token_And;
  1980. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  1981. if (op_kind == Token_NotEq) {
  1982. res = lb_const_bool(p->module, t_llvm_bool, false);
  1983. cmp_op = Token_Or;
  1984. } else if (op_kind == Token_CmpEq) {
  1985. res = lb_const_bool(p->module, t_llvm_bool, true);
  1986. cmp_op = Token_And;
  1987. }
  1988. bool inline_array_arith = lb_can_try_to_inline_array_arith(tl);
  1989. i32 count = 0;
  1990. switch (tl->kind) {
  1991. case Type_Array: count = cast(i32)tl->Array.count; break;
  1992. case Type_EnumeratedArray: count = cast(i32)tl->EnumeratedArray.count; break;
  1993. }
  1994. if (inline_array_arith) {
  1995. // inline
  1996. lbAddr val = lb_add_local_generated(p, t_bool, false);
  1997. lb_addr_store(p, val, res);
  1998. for (i32 i = 0; i < count; i++) {
  1999. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  2000. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  2001. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  2002. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  2003. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  2004. }
  2005. return lb_addr_load(p, val);
  2006. } else {
  2007. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  2008. // TODO(bill): Test to see if this is actually faster!!!!
  2009. auto args = array_make<lbValue>(permanent_allocator(), 3);
  2010. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  2011. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  2012. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  2013. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  2014. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  2015. return lb_emit_conv(p, res, t_bool);
  2016. } else {
  2017. lbAddr val = lb_add_local_generated(p, t_bool, false);
  2018. lb_addr_store(p, val, res);
  2019. auto loop_data = lb_loop_start(p, count, t_i32);
  2020. {
  2021. lbValue i = loop_data.idx;
  2022. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  2023. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  2024. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  2025. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  2026. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  2027. }
  2028. lb_loop_end(p, loop_data);
  2029. return lb_addr_load(p, val);
  2030. }
  2031. }
  2032. }
  2033. if ((is_type_struct(a) || is_type_union(a)) && is_type_comparable(a)) {
  2034. return lb_compare_records(p, op_kind, left, right, a);
  2035. }
  2036. if ((is_type_struct(b) || is_type_union(b)) && is_type_comparable(b)) {
  2037. return lb_compare_records(p, op_kind, left, right, b);
  2038. }
  2039. if (is_type_string(a)) {
  2040. if (is_type_cstring(a) && is_type_cstring(b)) {
  2041. left = lb_emit_conv(p, left, t_cstring);
  2042. right = lb_emit_conv(p, right, t_cstring);
  2043. char const *runtime_procedure = nullptr;
  2044. switch (op_kind) {
  2045. case Token_CmpEq: runtime_procedure = "cstring_eq"; break;
  2046. case Token_NotEq: runtime_procedure = "cstring_ne"; break;
  2047. case Token_Lt: runtime_procedure = "cstring_lt"; break;
  2048. case Token_Gt: runtime_procedure = "cstring_gt"; break;
  2049. case Token_LtEq: runtime_procedure = "cstring_le"; break;
  2050. case Token_GtEq: runtime_procedure = "cstring_gt"; break;
  2051. }
  2052. GB_ASSERT(runtime_procedure != nullptr);
  2053. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2054. args[0] = left;
  2055. args[1] = right;
  2056. return lb_emit_runtime_call(p, runtime_procedure, args);
  2057. }
  2058. if (is_type_cstring(a) ^ is_type_cstring(b)) {
  2059. left = lb_emit_conv(p, left, t_string);
  2060. right = lb_emit_conv(p, right, t_string);
  2061. }
  2062. char const *runtime_procedure = nullptr;
  2063. switch (op_kind) {
  2064. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  2065. case Token_NotEq: runtime_procedure = "string_ne"; break;
  2066. case Token_Lt: runtime_procedure = "string_lt"; break;
  2067. case Token_Gt: runtime_procedure = "string_gt"; break;
  2068. case Token_LtEq: runtime_procedure = "string_le"; break;
  2069. case Token_GtEq: runtime_procedure = "string_gt"; break;
  2070. }
  2071. GB_ASSERT(runtime_procedure != nullptr);
  2072. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2073. args[0] = left;
  2074. args[1] = right;
  2075. return lb_emit_runtime_call(p, runtime_procedure, args);
  2076. }
  2077. if (is_type_complex(a)) {
  2078. char const *runtime_procedure = "";
  2079. i64 sz = 8*type_size_of(a);
  2080. switch (sz) {
  2081. case 32:
  2082. switch (op_kind) {
  2083. case Token_CmpEq: runtime_procedure = "complex32_eq"; break;
  2084. case Token_NotEq: runtime_procedure = "complex32_ne"; break;
  2085. }
  2086. break;
  2087. case 64:
  2088. switch (op_kind) {
  2089. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  2090. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  2091. }
  2092. break;
  2093. case 128:
  2094. switch (op_kind) {
  2095. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  2096. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  2097. }
  2098. break;
  2099. }
  2100. GB_ASSERT(runtime_procedure != nullptr);
  2101. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2102. args[0] = left;
  2103. args[1] = right;
  2104. return lb_emit_runtime_call(p, runtime_procedure, args);
  2105. }
  2106. if (is_type_quaternion(a)) {
  2107. char const *runtime_procedure = "";
  2108. i64 sz = 8*type_size_of(a);
  2109. switch (sz) {
  2110. case 64:
  2111. switch (op_kind) {
  2112. case Token_CmpEq: runtime_procedure = "quaternion64_eq"; break;
  2113. case Token_NotEq: runtime_procedure = "quaternion64_ne"; break;
  2114. }
  2115. break;
  2116. case 128:
  2117. switch (op_kind) {
  2118. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  2119. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  2120. }
  2121. break;
  2122. case 256:
  2123. switch (op_kind) {
  2124. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  2125. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  2126. }
  2127. break;
  2128. }
  2129. GB_ASSERT(runtime_procedure != nullptr);
  2130. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2131. args[0] = left;
  2132. args[1] = right;
  2133. return lb_emit_runtime_call(p, runtime_procedure, args);
  2134. }
  2135. if (is_type_bit_set(a)) {
  2136. switch (op_kind) {
  2137. case Token_Lt:
  2138. case Token_LtEq:
  2139. case Token_Gt:
  2140. case Token_GtEq:
  2141. {
  2142. Type *it = bit_set_to_int(a);
  2143. lbValue lhs = lb_emit_transmute(p, left, it);
  2144. lbValue rhs = lb_emit_transmute(p, right, it);
  2145. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  2146. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  2147. // (lhs & rhs) == lhs
  2148. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  2149. res.type = t_llvm_bool;
  2150. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  2151. // (lhs & rhs) == rhs
  2152. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  2153. res.type = t_llvm_bool;
  2154. }
  2155. // NOTE(bill): Strict subsets
  2156. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  2157. // res &~ (lhs == rhs)
  2158. lbValue eq = {};
  2159. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  2160. eq.type = t_llvm_bool;
  2161. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  2162. }
  2163. return res;
  2164. }
  2165. case Token_CmpEq:
  2166. case Token_NotEq:
  2167. {
  2168. LLVMIntPredicate pred = {};
  2169. switch (op_kind) {
  2170. case Token_CmpEq: pred = LLVMIntEQ; break;
  2171. case Token_NotEq: pred = LLVMIntNE; break;
  2172. }
  2173. lbValue res = {};
  2174. res.type = t_llvm_bool;
  2175. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  2176. return res;
  2177. }
  2178. }
  2179. }
  2180. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  2181. Type *t = left.type;
  2182. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  2183. Type *platform_type = integer_endian_type_to_platform_type(t);
  2184. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  2185. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  2186. left = x;
  2187. right = y;
  2188. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  2189. Type *platform_type = integer_endian_type_to_platform_type(t);
  2190. lbValue x = lb_emit_conv(p, left, platform_type);
  2191. lbValue y = lb_emit_conv(p, right, platform_type);
  2192. left = x;
  2193. right = y;
  2194. }
  2195. }
  2196. a = core_type(left.type);
  2197. b = core_type(right.type);
  2198. lbValue res = {};
  2199. res.type = t_llvm_bool;
  2200. if (is_type_integer(a) ||
  2201. is_type_boolean(a) ||
  2202. is_type_pointer(a) ||
  2203. is_type_multi_pointer(a) ||
  2204. is_type_proc(a) ||
  2205. is_type_enum(a)) {
  2206. LLVMIntPredicate pred = {};
  2207. if (is_type_unsigned(left.type)) {
  2208. switch (op_kind) {
  2209. case Token_Gt: pred = LLVMIntUGT; break;
  2210. case Token_GtEq: pred = LLVMIntUGE; break;
  2211. case Token_Lt: pred = LLVMIntULT; break;
  2212. case Token_LtEq: pred = LLVMIntULE; break;
  2213. }
  2214. } else {
  2215. switch (op_kind) {
  2216. case Token_Gt: pred = LLVMIntSGT; break;
  2217. case Token_GtEq: pred = LLVMIntSGE; break;
  2218. case Token_Lt: pred = LLVMIntSLT; break;
  2219. case Token_LtEq: pred = LLVMIntSLE; break;
  2220. }
  2221. }
  2222. switch (op_kind) {
  2223. case Token_CmpEq: pred = LLVMIntEQ; break;
  2224. case Token_NotEq: pred = LLVMIntNE; break;
  2225. }
  2226. LLVMValueRef lhs = left.value;
  2227. LLVMValueRef rhs = right.value;
  2228. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  2229. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  2230. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  2231. }
  2232. }
  2233. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  2234. } else if (is_type_float(a)) {
  2235. LLVMRealPredicate pred = {};
  2236. switch (op_kind) {
  2237. case Token_CmpEq: pred = LLVMRealOEQ; break;
  2238. case Token_Gt: pred = LLVMRealOGT; break;
  2239. case Token_GtEq: pred = LLVMRealOGE; break;
  2240. case Token_Lt: pred = LLVMRealOLT; break;
  2241. case Token_LtEq: pred = LLVMRealOLE; break;
  2242. case Token_NotEq: pred = LLVMRealONE; break;
  2243. }
  2244. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  2245. } else if (is_type_typeid(a)) {
  2246. LLVMIntPredicate pred = {};
  2247. switch (op_kind) {
  2248. case Token_Gt: pred = LLVMIntUGT; break;
  2249. case Token_GtEq: pred = LLVMIntUGE; break;
  2250. case Token_Lt: pred = LLVMIntULT; break;
  2251. case Token_LtEq: pred = LLVMIntULE; break;
  2252. case Token_CmpEq: pred = LLVMIntEQ; break;
  2253. case Token_NotEq: pred = LLVMIntNE; break;
  2254. }
  2255. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  2256. } else if (is_type_simd_vector(a)) {
  2257. LLVMValueRef mask = nullptr;
  2258. Type *elem = base_array_type(a);
  2259. if (is_type_float(elem)) {
  2260. LLVMRealPredicate pred = {};
  2261. switch (op_kind) {
  2262. case Token_CmpEq: pred = LLVMRealOEQ; break;
  2263. case Token_NotEq: pred = LLVMRealONE; break;
  2264. }
  2265. mask = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  2266. } else {
  2267. LLVMIntPredicate pred = {};
  2268. switch (op_kind) {
  2269. case Token_CmpEq: pred = LLVMIntEQ; break;
  2270. case Token_NotEq: pred = LLVMIntNE; break;
  2271. }
  2272. mask = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  2273. }
  2274. GB_ASSERT_MSG(mask != nullptr, "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)));
  2275. /* NOTE(bill, 2022-05-28):
  2276. Thanks to Per Vognsen, sign extending <N x i1> to
  2277. a vector of the same width as the input vector, bit casting to an integer,
  2278. and then comparing against zero is the better option
  2279. See: https://lists.llvm.org/pipermail/llvm-dev/2012-September/053046.html
  2280. // Example assuming 128-bit vector
  2281. %1 = <4 x float> ...
  2282. %2 = <4 x float> ...
  2283. %3 = fcmp oeq <4 x float> %1, %2
  2284. %4 = sext <4 x i1> %3 to <4 x i32>
  2285. %5 = bitcast <4 x i32> %4 to i128
  2286. %6 = icmp ne i128 %5, 0
  2287. br i1 %6, label %true1, label %false2
  2288. This will result in 1 cmpps + 1 ptest + 1 br
  2289. (even without SSE4.1, contrary to what the mail list states, because of pmovmskb)
  2290. */
  2291. unsigned count = cast(unsigned)get_array_type_count(a);
  2292. unsigned elem_sz = cast(unsigned)(type_size_of(elem)*8);
  2293. LLVMTypeRef mask_type = LLVMVectorType(LLVMIntTypeInContext(p->module->ctx, elem_sz), count);
  2294. mask = LLVMBuildSExtOrBitCast(p->builder, mask, mask_type, "");
  2295. LLVMTypeRef mask_int_type = LLVMIntTypeInContext(p->module->ctx, cast(unsigned)(8*type_size_of(a)));
  2296. LLVMValueRef mask_int = LLVMBuildBitCast(p->builder, mask, mask_int_type, "");
  2297. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, mask_int, LLVMConstNull(LLVMTypeOf(mask_int)), "");
  2298. return res;
  2299. } else {
  2300. 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)));
  2301. }
  2302. return res;
  2303. }
  2304. gb_internal lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  2305. lbValue res = {};
  2306. res.type = t_llvm_bool;
  2307. Type *t = x.type;
  2308. Type *bt = base_type(t);
  2309. TypeKind type_kind = bt->kind;
  2310. switch (type_kind) {
  2311. case Type_Basic:
  2312. switch (bt->Basic.kind) {
  2313. case Basic_rawptr:
  2314. case Basic_cstring:
  2315. if (op_kind == Token_CmpEq) {
  2316. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  2317. } else if (op_kind == Token_NotEq) {
  2318. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  2319. }
  2320. return res;
  2321. case Basic_any:
  2322. {
  2323. // TODO(bill): is this correct behaviour for nil comparison for any?
  2324. lbValue data = lb_emit_struct_ev(p, x, 0);
  2325. lbValue ti = lb_emit_struct_ev(p, x, 1);
  2326. if (op_kind == Token_CmpEq) {
  2327. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  2328. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  2329. res.value = LLVMBuildOr(p->builder, a, b, "");
  2330. return res;
  2331. } else if (op_kind == Token_NotEq) {
  2332. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  2333. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  2334. res.value = LLVMBuildAnd(p->builder, a, b, "");
  2335. return res;
  2336. }
  2337. }
  2338. break;
  2339. case Basic_typeid:
  2340. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  2341. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  2342. }
  2343. break;
  2344. case Type_Enum:
  2345. case Type_Pointer:
  2346. case Type_MultiPointer:
  2347. case Type_Proc:
  2348. case Type_BitSet:
  2349. if (op_kind == Token_CmpEq) {
  2350. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  2351. } else if (op_kind == Token_NotEq) {
  2352. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  2353. }
  2354. return res;
  2355. case Type_Slice:
  2356. {
  2357. lbValue data = lb_emit_struct_ev(p, x, 0);
  2358. if (op_kind == Token_CmpEq) {
  2359. res.value = LLVMBuildIsNull(p->builder, data.value, "");
  2360. return res;
  2361. } else if (op_kind == Token_NotEq) {
  2362. res.value = LLVMBuildIsNotNull(p->builder, data.value, "");
  2363. return res;
  2364. }
  2365. }
  2366. break;
  2367. case Type_DynamicArray:
  2368. {
  2369. lbValue data = lb_emit_struct_ev(p, x, 0);
  2370. if (op_kind == Token_CmpEq) {
  2371. res.value = LLVMBuildIsNull(p->builder, data.value, "");
  2372. return res;
  2373. } else if (op_kind == Token_NotEq) {
  2374. res.value = LLVMBuildIsNotNull(p->builder, data.value, "");
  2375. return res;
  2376. }
  2377. }
  2378. break;
  2379. case Type_Map:
  2380. {
  2381. lbValue data_ptr = lb_emit_struct_ev(p, x, 0);
  2382. if (op_kind == Token_CmpEq) {
  2383. res.value = LLVMBuildIsNull(p->builder, data_ptr.value, "");
  2384. return res;
  2385. } else {
  2386. res.value = LLVMBuildIsNotNull(p->builder, data_ptr.value, "");
  2387. return res;
  2388. }
  2389. }
  2390. break;
  2391. case Type_Union:
  2392. {
  2393. if (type_size_of(t) == 0) {
  2394. if (op_kind == Token_CmpEq) {
  2395. return lb_const_bool(p->module, t_llvm_bool, true);
  2396. } else if (op_kind == Token_NotEq) {
  2397. return lb_const_bool(p->module, t_llvm_bool, false);
  2398. }
  2399. } else if (is_type_union_maybe_pointer(t)) {
  2400. lbValue tag = lb_emit_transmute(p, x, t_rawptr);
  2401. return lb_emit_comp_against_nil(p, op_kind, tag);
  2402. } else {
  2403. lbValue tag = lb_emit_union_tag_value(p, x);
  2404. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  2405. }
  2406. }
  2407. case Type_Struct:
  2408. if (is_type_soa_struct(t)) {
  2409. Type *bt = base_type(t);
  2410. if (bt->Struct.soa_kind == StructSoa_Slice) {
  2411. LLVMValueRef the_value = {};
  2412. if (bt->Struct.fields.count == 0) {
  2413. lbValue len = lb_soa_struct_len(p, x);
  2414. the_value = len.value;
  2415. } else {
  2416. lbValue first_field = lb_emit_struct_ev(p, x, 0);
  2417. the_value = first_field.value;
  2418. }
  2419. if (op_kind == Token_CmpEq) {
  2420. res.value = LLVMBuildIsNull(p->builder, the_value, "");
  2421. return res;
  2422. } else if (op_kind == Token_NotEq) {
  2423. res.value = LLVMBuildIsNotNull(p->builder, the_value, "");
  2424. return res;
  2425. }
  2426. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  2427. LLVMValueRef the_value = {};
  2428. if (bt->Struct.fields.count == 0) {
  2429. lbValue cap = lb_soa_struct_cap(p, x);
  2430. the_value = cap.value;
  2431. } else {
  2432. lbValue first_field = lb_emit_struct_ev(p, x, 0);
  2433. the_value = first_field.value;
  2434. }
  2435. if (op_kind == Token_CmpEq) {
  2436. res.value = LLVMBuildIsNull(p->builder, the_value, "");
  2437. return res;
  2438. } else if (op_kind == Token_NotEq) {
  2439. res.value = LLVMBuildIsNotNull(p->builder, the_value, "");
  2440. return res;
  2441. }
  2442. }
  2443. } else if (is_type_struct(t) && type_has_nil(t)) {
  2444. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2445. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  2446. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  2447. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  2448. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  2449. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  2450. return res;
  2451. }
  2452. break;
  2453. }
  2454. GB_PANIC("Unknown handled type: %s -> %s", type_to_string(t), type_to_string(bt));
  2455. return {};
  2456. }
  2457. gb_internal lbValue lb_make_soa_pointer(lbProcedure *p, Type *type, lbValue const &addr, lbValue const &index) {
  2458. lbAddr v = lb_add_local_generated(p, type, false);
  2459. lbValue ptr = lb_emit_struct_ep(p, v.addr, 0);
  2460. lbValue idx = lb_emit_struct_ep(p, v.addr, 1);
  2461. lb_emit_store(p, ptr, addr);
  2462. lb_emit_store(p, idx, lb_emit_conv(p, index, t_int));
  2463. return lb_addr_load(p, v);
  2464. }
  2465. gb_internal lbValue lb_build_unary_and(lbProcedure *p, Ast *expr) {
  2466. ast_node(ue, UnaryExpr, expr);
  2467. auto tv = type_and_value_of_expr(expr);
  2468. Ast *ue_expr = unparen_expr(ue->expr);
  2469. if (ue_expr->kind == Ast_IndexExpr && tv.mode == Addressing_OptionalOkPtr && is_type_tuple(tv.type)) {
  2470. Type *tuple = tv.type;
  2471. Type *map_type = type_of_expr(ue_expr->IndexExpr.expr);
  2472. Type *ot = base_type(map_type);
  2473. Type *t = base_type(type_deref(ot));
  2474. bool deref = t != ot;
  2475. GB_ASSERT(t->kind == Type_Map);
  2476. ast_node(ie, IndexExpr, ue_expr);
  2477. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  2478. if (deref) {
  2479. map_val = lb_emit_load(p, map_val);
  2480. }
  2481. lbValue key = lb_build_expr(p, ie->index);
  2482. key = lb_emit_conv(p, key, t->Map.key);
  2483. lbAddr addr = lb_addr_map(map_val, key, t, alloc_type_pointer(t->Map.value));
  2484. lbValue ptr = lb_addr_get_ptr(p, addr);
  2485. lbValue ok = lb_emit_comp_against_nil(p, Token_NotEq, ptr);
  2486. ok = lb_emit_conv(p, ok, tuple->Tuple.variables[1]->type);
  2487. lbAddr res = lb_add_local_generated(p, tuple, false);
  2488. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  2489. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  2490. lb_emit_store(p, gep0, ptr);
  2491. lb_emit_store(p, gep1, ok);
  2492. return lb_addr_load(p, res);
  2493. } else if (is_type_soa_pointer(tv.type)) {
  2494. ast_node(ie, IndexExpr, ue_expr);
  2495. lbValue addr = lb_build_addr_ptr(p, ie->expr);
  2496. lbValue index = lb_build_expr(p, ie->index);
  2497. if (!build_context.no_bounds_check) {
  2498. // TODO(bill): soa bounds checking
  2499. }
  2500. return lb_make_soa_pointer(p, tv.type, addr, index);
  2501. } else if (ue_expr->kind == Ast_CompoundLit) {
  2502. lbValue v = lb_build_expr(p, ue->expr);
  2503. Type *type = v.type;
  2504. lbAddr addr = {};
  2505. if (p->is_startup) {
  2506. addr = lb_add_global_generated(p->module, type, v);
  2507. } else {
  2508. addr = lb_add_local_generated(p, type, false);
  2509. }
  2510. lb_addr_store(p, addr, v);
  2511. return addr.addr;
  2512. } else if (ue_expr->kind == Ast_TypeAssertion) {
  2513. if (is_type_tuple(tv.type)) {
  2514. Type *tuple = tv.type;
  2515. Type *ptr_type = tuple->Tuple.variables[0]->type;
  2516. Type *ok_type = tuple->Tuple.variables[1]->type;
  2517. ast_node(ta, TypeAssertion, ue_expr);
  2518. TokenPos pos = ast_token(expr).pos;
  2519. Type *type = type_of_expr(ue_expr);
  2520. GB_ASSERT(!is_type_tuple(type));
  2521. lbValue e = lb_build_expr(p, ta->expr);
  2522. Type *t = type_deref(e.type);
  2523. if (is_type_union(t)) {
  2524. lbValue v = e;
  2525. if (!is_type_pointer(v.type)) {
  2526. v = lb_address_from_load_or_generate_local(p, v);
  2527. }
  2528. Type *src_type = type_deref(v.type);
  2529. Type *dst_type = type;
  2530. lbValue src_tag = {};
  2531. lbValue dst_tag = {};
  2532. if (is_type_union_maybe_pointer(src_type)) {
  2533. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  2534. dst_tag = lb_const_bool(p->module, t_bool, true);
  2535. } else {
  2536. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  2537. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  2538. }
  2539. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  2540. lbValue data_ptr = lb_emit_conv(p, v, ptr_type);
  2541. lbAddr res = lb_add_local_generated(p, tuple, true);
  2542. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  2543. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  2544. lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type)));
  2545. lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type));
  2546. return lb_addr_load(p, res);
  2547. } else if (is_type_any(t)) {
  2548. lbValue v = e;
  2549. if (is_type_pointer(v.type)) {
  2550. v = lb_emit_load(p, v);
  2551. }
  2552. lbValue data_ptr = lb_emit_conv(p, lb_emit_struct_ev(p, v, 0), ptr_type);
  2553. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  2554. lbValue id = lb_typeid(p->module, type);
  2555. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  2556. lbAddr res = lb_add_local_generated(p, tuple, false);
  2557. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  2558. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  2559. lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type)));
  2560. lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type));
  2561. return lb_addr_load(p, res);
  2562. } else {
  2563. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  2564. }
  2565. } else {
  2566. GB_ASSERT(is_type_pointer(tv.type));
  2567. ast_node(ta, TypeAssertion, ue_expr);
  2568. TokenPos pos = ast_token(expr).pos;
  2569. Type *type = type_of_expr(ue_expr);
  2570. GB_ASSERT(!is_type_tuple(type));
  2571. lbValue e = lb_build_expr(p, ta->expr);
  2572. Type *t = type_deref(e.type);
  2573. if (is_type_union(t)) {
  2574. lbValue v = e;
  2575. if (!is_type_pointer(v.type)) {
  2576. v = lb_address_from_load_or_generate_local(p, v);
  2577. }
  2578. Type *src_type = type_deref(v.type);
  2579. Type *dst_type = type;
  2580. if ((p->state_flags & StateFlag_no_type_assert) == 0) {
  2581. lbValue src_tag = {};
  2582. lbValue dst_tag = {};
  2583. if (is_type_union_maybe_pointer(src_type)) {
  2584. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  2585. dst_tag = lb_const_bool(p->module, t_bool, true);
  2586. } else {
  2587. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  2588. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  2589. }
  2590. isize arg_count = 6;
  2591. if (build_context.no_rtti) {
  2592. arg_count = 4;
  2593. }
  2594. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  2595. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  2596. args[0] = ok;
  2597. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  2598. args[2] = lb_const_int(p->module, t_i32, pos.line);
  2599. args[3] = lb_const_int(p->module, t_i32, pos.column);
  2600. if (!build_context.no_rtti) {
  2601. args[4] = lb_typeid(p->module, src_type);
  2602. args[5] = lb_typeid(p->module, dst_type);
  2603. }
  2604. lb_emit_runtime_call(p, "type_assertion_check", args);
  2605. }
  2606. lbValue data_ptr = v;
  2607. return lb_emit_conv(p, data_ptr, tv.type);
  2608. } else if (is_type_any(t)) {
  2609. lbValue v = e;
  2610. if (is_type_pointer(v.type)) {
  2611. v = lb_emit_load(p, v);
  2612. }
  2613. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  2614. if ((p->state_flags & StateFlag_no_type_assert) == 0) {
  2615. GB_ASSERT(!build_context.no_rtti);
  2616. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  2617. lbValue id = lb_typeid(p->module, type);
  2618. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  2619. auto args = array_make<lbValue>(permanent_allocator(), 6);
  2620. args[0] = ok;
  2621. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  2622. args[2] = lb_const_int(p->module, t_i32, pos.line);
  2623. args[3] = lb_const_int(p->module, t_i32, pos.column);
  2624. args[4] = any_id;
  2625. args[5] = id;
  2626. lb_emit_runtime_call(p, "type_assertion_check", args);
  2627. }
  2628. return lb_emit_conv(p, data_ptr, tv.type);
  2629. } else {
  2630. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  2631. }
  2632. }
  2633. }
  2634. return lb_build_addr_ptr(p, ue->expr);
  2635. }
  2636. gb_internal lbValue lb_build_expr_internal(lbProcedure *p, Ast *expr);
  2637. gb_internal lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  2638. u16 prev_state_flags = p->state_flags;
  2639. defer (p->state_flags = prev_state_flags);
  2640. if (expr->state_flags != 0) {
  2641. u16 in = expr->state_flags;
  2642. u16 out = p->state_flags;
  2643. if (in & StateFlag_bounds_check) {
  2644. out |= StateFlag_bounds_check;
  2645. out &= ~StateFlag_no_bounds_check;
  2646. } else if (in & StateFlag_no_bounds_check) {
  2647. out |= StateFlag_no_bounds_check;
  2648. out &= ~StateFlag_bounds_check;
  2649. }
  2650. if (in & StateFlag_type_assert) {
  2651. out |= StateFlag_type_assert;
  2652. out &= ~StateFlag_no_type_assert;
  2653. } else if (in & StateFlag_no_type_assert) {
  2654. out |= StateFlag_no_type_assert;
  2655. out &= ~StateFlag_type_assert;
  2656. }
  2657. p->state_flags = out;
  2658. }
  2659. // IMPORTANT NOTE(bill):
  2660. // Selector Call Expressions (foo->bar(...))
  2661. // must only evaluate `foo` once as it gets transformed into
  2662. // `foo.bar(foo, ...)`
  2663. // And if `foo` is a procedure call or something more complex, storing the value
  2664. // once is a very good idea
  2665. // If a stored value is found, it must be removed from the cache
  2666. if (expr->state_flags & StateFlag_SelectorCallExpr) {
  2667. lbValue *pp = map_get(&p->selector_values, expr);
  2668. if (pp != nullptr) {
  2669. lbValue res = *pp;
  2670. map_remove(&p->selector_values, expr);
  2671. return res;
  2672. }
  2673. lbAddr *pa = map_get(&p->selector_addr, expr);
  2674. if (pa != nullptr) {
  2675. lbAddr res = *pa;
  2676. map_remove(&p->selector_addr, expr);
  2677. return lb_addr_load(p, res);
  2678. }
  2679. }
  2680. lbValue res = lb_build_expr_internal(p, expr);
  2681. if (expr->state_flags & StateFlag_SelectorCallExpr) {
  2682. map_set(&p->selector_values, expr, res);
  2683. }
  2684. return res;
  2685. }
  2686. gb_internal lbValue lb_build_expr_internal(lbProcedure *p, Ast *expr) {
  2687. lbModule *m = p->module;
  2688. expr = unparen_expr(expr);
  2689. TokenPos expr_pos = ast_token(expr).pos;
  2690. TypeAndValue tv = type_and_value_of_expr(expr);
  2691. Type *type = type_of_expr(expr);
  2692. GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %s\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), token_pos_to_string(expr_pos), LIT(p->name), type_to_string(p->type));
  2693. if (tv.value.kind != ExactValue_Invalid) {
  2694. // NOTE(bill): The commented out code below is just for debug purposes only
  2695. // if (is_type_untyped(type)) {
  2696. // gb_printf_err("%s %s : %s @ %p\n", token_pos_to_string(expr_pos), expr_to_string(expr), type_to_string(expr->tav.type), expr);
  2697. // GB_PANIC("%s\n", type_to_string(tv.type));
  2698. // }
  2699. // NOTE(bill): Short on constant values
  2700. return lb_const_value(p->module, type, tv.value);
  2701. } else if (tv.mode == Addressing_Type) {
  2702. // NOTE(bill, 2023-01-16): is this correct? I hope so at least
  2703. return lb_typeid(m, tv.type);
  2704. }
  2705. switch (expr->kind) {
  2706. case_ast_node(bl, BasicLit, expr);
  2707. TokenPos pos = bl->token.pos;
  2708. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  2709. case_end;
  2710. case_ast_node(bd, BasicDirective, expr);
  2711. TokenPos pos = bd->token.pos;
  2712. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name.string));
  2713. case_end;
  2714. case_ast_node(i, Implicit, expr);
  2715. return lb_addr_load(p, lb_build_addr(p, expr));
  2716. case_end;
  2717. case_ast_node(u, Uninit, expr)
  2718. lbValue res = {};
  2719. if (is_type_untyped(type)) {
  2720. res.value = nullptr;
  2721. res.type = t_untyped_uninit;
  2722. } else {
  2723. res.value = LLVMGetUndef(lb_type(m, type));
  2724. res.type = type;
  2725. }
  2726. return res;
  2727. case_end;
  2728. case_ast_node(i, Ident, expr);
  2729. Entity *e = entity_from_expr(expr);
  2730. e = strip_entity_wrapping(e);
  2731. GB_ASSERT_MSG(e != nullptr, "%s in %.*s %p", expr_to_string(expr), LIT(p->name), expr);
  2732. if (e->kind == Entity_Builtin) {
  2733. Token token = ast_token(expr);
  2734. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  2735. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  2736. token_pos_to_string(token.pos));
  2737. return {};
  2738. } else if (e->kind == Entity_Nil) {
  2739. lbValue res = {};
  2740. res.value = nullptr;
  2741. res.type = e->type;
  2742. return res;
  2743. }
  2744. GB_ASSERT(e->kind != Entity_ProcGroup);
  2745. return lb_find_ident(p, m, e, expr);
  2746. case_end;
  2747. case_ast_node(de, DerefExpr, expr);
  2748. return lb_addr_load(p, lb_build_addr(p, expr));
  2749. case_end;
  2750. case_ast_node(se, SelectorExpr, expr);
  2751. TypeAndValue tav = type_and_value_of_expr(expr);
  2752. GB_ASSERT(tav.mode != Addressing_Invalid);
  2753. return lb_addr_load(p, lb_build_addr(p, expr));
  2754. case_end;
  2755. case_ast_node(ise, ImplicitSelectorExpr, expr);
  2756. TypeAndValue tav = type_and_value_of_expr(expr);
  2757. GB_ASSERT(tav.mode == Addressing_Constant);
  2758. return lb_const_value(p->module, type, tv.value);
  2759. case_end;
  2760. case_ast_node(se, SelectorCallExpr, expr);
  2761. GB_ASSERT(se->modified_call);
  2762. return lb_build_call_expr(p, se->call);
  2763. case_end;
  2764. case_ast_node(te, TernaryIfExpr, expr);
  2765. LLVMValueRef incoming_values[2] = {};
  2766. LLVMBasicBlockRef incoming_blocks[2] = {};
  2767. GB_ASSERT(te->y != nullptr);
  2768. lbBlock *then = lb_create_block(p, "if.then");
  2769. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  2770. lbBlock *else_ = lb_create_block(p, "if.else");
  2771. lb_build_cond(p, te->cond, then, else_);
  2772. lb_start_block(p, then);
  2773. Type *type = default_type(type_of_expr(expr));
  2774. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2775. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  2776. if (is_type_internally_pointer_like(type)) {
  2777. incoming_values[0] = LLVMBuildBitCast(p->builder, incoming_values[0], llvm_type, "");
  2778. }
  2779. lb_emit_jump(p, done);
  2780. lb_start_block(p, else_);
  2781. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  2782. if (is_type_internally_pointer_like(type)) {
  2783. incoming_values[1] = LLVMBuildBitCast(p->builder, incoming_values[1], llvm_type, "");
  2784. }
  2785. lb_emit_jump(p, done);
  2786. lb_start_block(p, done);
  2787. lbValue res = {};
  2788. res.value = LLVMBuildPhi(p->builder, llvm_type, "");
  2789. res.type = type;
  2790. GB_ASSERT(p->curr_block->preds.count >= 2);
  2791. incoming_blocks[0] = p->curr_block->preds[0]->block;
  2792. incoming_blocks[1] = p->curr_block->preds[1]->block;
  2793. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  2794. return res;
  2795. case_end;
  2796. case_ast_node(te, TernaryWhenExpr, expr);
  2797. TypeAndValue tav = type_and_value_of_expr(te->cond);
  2798. GB_ASSERT(tav.mode == Addressing_Constant);
  2799. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  2800. if (tav.value.value_bool) {
  2801. return lb_build_expr(p, te->x);
  2802. } else {
  2803. return lb_build_expr(p, te->y);
  2804. }
  2805. case_end;
  2806. case_ast_node(oe, OrElseExpr, expr);
  2807. return lb_emit_or_else(p, oe->x, oe->y, tv);
  2808. case_end;
  2809. case_ast_node(oe, OrReturnExpr, expr);
  2810. return lb_emit_or_return(p, oe->expr, tv);
  2811. case_end;
  2812. case_ast_node(be, OrBranchExpr, expr);
  2813. lbBlock *block = nullptr;
  2814. if (be->label != nullptr) {
  2815. lbBranchBlocks bb = lb_lookup_branch_blocks(p, be->label);
  2816. switch (be->token.kind) {
  2817. case Token_or_break: block = bb.break_; break;
  2818. case Token_or_continue: block = bb.continue_; break;
  2819. }
  2820. } else {
  2821. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  2822. if (t->is_block) {
  2823. continue;
  2824. }
  2825. switch (be->token.kind) {
  2826. case Token_or_break: block = t->break_; break;
  2827. case Token_or_continue: block = t->continue_; break;
  2828. }
  2829. }
  2830. }
  2831. GB_ASSERT(block != nullptr);
  2832. lbValue lhs = {};
  2833. lbValue rhs = {};
  2834. lb_emit_try_lhs_rhs(p, be->expr, tv, &lhs, &rhs);
  2835. Type *type = default_type(tv.type);
  2836. if (lhs.value) {
  2837. lhs = lb_emit_conv(p, lhs, type);
  2838. } else if (type != nullptr && type != t_invalid) {
  2839. lhs = lb_const_nil(p->module, type);
  2840. }
  2841. lbBlock *then = lb_create_block(p, "or_branch.then");
  2842. lbBlock *else_ = lb_create_block(p, "or_branch.else");
  2843. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  2844. lb_start_block(p, else_);
  2845. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  2846. lb_emit_jump(p, block);
  2847. lb_start_block(p, then);
  2848. return lhs;
  2849. case_end;
  2850. case_ast_node(ta, TypeAssertion, expr);
  2851. TokenPos pos = ast_token(expr).pos;
  2852. lbValue e = lb_build_expr(p, ta->expr);
  2853. Type *t = type_deref(e.type);
  2854. if (is_type_union(t)) {
  2855. if (ta->ignores[0]) {
  2856. // NOTE(bill): This is not needed for optimization levels other than 0
  2857. return lb_emit_union_cast_only_ok_check(p, e, type, pos);
  2858. }
  2859. return lb_emit_union_cast(p, e, type, pos);
  2860. } else if (is_type_any(t)) {
  2861. return lb_emit_any_cast(p, e, type, pos);
  2862. } else {
  2863. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  2864. }
  2865. case_end;
  2866. case_ast_node(tc, TypeCast, expr);
  2867. lbValue e = lb_build_expr(p, tc->expr);
  2868. switch (tc->token.kind) {
  2869. case Token_cast:
  2870. return lb_emit_conv(p, e, type);
  2871. case Token_transmute:
  2872. return lb_emit_transmute(p, e, type);
  2873. }
  2874. GB_PANIC("Invalid AST TypeCast");
  2875. case_end;
  2876. case_ast_node(ac, AutoCast, expr);
  2877. lbValue value = lb_build_expr(p, ac->expr);
  2878. return lb_emit_conv(p, value, type);
  2879. case_end;
  2880. case_ast_node(ue, UnaryExpr, expr);
  2881. switch (ue->op.kind) {
  2882. case Token_And:
  2883. return lb_build_unary_and(p, expr);
  2884. default:
  2885. {
  2886. lbValue v = lb_build_expr(p, ue->expr);
  2887. return lb_emit_unary_arith(p, ue->op.kind, v, type);
  2888. }
  2889. }
  2890. case_end;
  2891. case_ast_node(be, BinaryExpr, expr);
  2892. return lb_build_binary_expr(p, expr);
  2893. case_end;
  2894. case_ast_node(pl, ProcLit, expr);
  2895. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  2896. case_end;
  2897. case_ast_node(cl, CompoundLit, expr);
  2898. return lb_addr_load(p, lb_build_addr(p, expr));
  2899. case_end;
  2900. case_ast_node(ce, CallExpr, expr);
  2901. return lb_build_call_expr(p, expr);
  2902. case_end;
  2903. case_ast_node(se, SliceExpr, expr);
  2904. if (is_type_slice(type_of_expr(se->expr))) {
  2905. // NOTE(bill): Quick optimization
  2906. if (se->high == nullptr &&
  2907. (se->low == nullptr || lb_is_expr_constant_zero(se->low))) {
  2908. return lb_build_expr(p, se->expr);
  2909. }
  2910. }
  2911. return lb_addr_load(p, lb_build_addr(p, expr));
  2912. case_end;
  2913. case_ast_node(ie, IndexExpr, expr);
  2914. return lb_addr_load(p, lb_build_addr(p, expr));
  2915. case_end;
  2916. case_ast_node(ie, MatrixIndexExpr, expr);
  2917. return lb_addr_load(p, lb_build_addr(p, expr));
  2918. case_end;
  2919. case_ast_node(ia, InlineAsmExpr, expr);
  2920. Type *t = type_of_expr(expr);
  2921. GB_ASSERT(is_type_asm_proc(t));
  2922. String asm_string = {};
  2923. String constraints_string = {};
  2924. TypeAndValue tav;
  2925. tav = type_and_value_of_expr(ia->asm_string);
  2926. GB_ASSERT(is_type_string(tav.type));
  2927. GB_ASSERT(tav.value.kind == ExactValue_String);
  2928. asm_string = tav.value.value_string;
  2929. tav = type_and_value_of_expr(ia->constraints_string);
  2930. GB_ASSERT(is_type_string(tav.type));
  2931. GB_ASSERT(tav.value.kind == ExactValue_String);
  2932. constraints_string = tav.value.value_string;
  2933. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  2934. switch (ia->dialect) {
  2935. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  2936. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  2937. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  2938. default: GB_PANIC("Unhandled inline asm dialect"); break;
  2939. }
  2940. LLVMTypeRef func_type = lb_type_internal_for_procedures_raw(p->module, t);
  2941. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, asm_string, constraints_string, ia->has_side_effects, ia->has_side_effects, dialect);
  2942. GB_ASSERT(the_asm != nullptr);
  2943. return {the_asm, t};
  2944. case_end;
  2945. }
  2946. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  2947. return {};
  2948. }
  2949. gb_internal lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  2950. return map_must_get(&p->module->soa_values, e);
  2951. }
  2952. gb_internal lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  2953. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  2954. String name = e->token.string;
  2955. Entity *parent = e->using_parent;
  2956. Selection sel = lookup_field(parent->type, name, false);
  2957. GB_ASSERT(sel.entity != nullptr);
  2958. lbValue *pv = map_get(&p->module->values, parent);
  2959. lbValue v = {};
  2960. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  2961. // NOTE(bill): using SOA value (probably from for-in statement)
  2962. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  2963. v = lb_addr_get_ptr(p, parent_addr);
  2964. } else if (pv != nullptr) {
  2965. v = *pv;
  2966. } else {
  2967. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  2968. v = lb_build_addr_ptr(p, e->using_expr);
  2969. }
  2970. GB_ASSERT(v.value != nullptr);
  2971. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  2972. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  2973. if (parent->scope) {
  2974. if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  2975. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  2976. }
  2977. } else {
  2978. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  2979. }
  2980. return ptr;
  2981. }
  2982. gb_internal lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  2983. GB_ASSERT(e != nullptr);
  2984. if (e->kind == Entity_Constant) {
  2985. Type *t = default_type(type_of_expr(expr));
  2986. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  2987. if (LLVMIsConstant(v.value)) {
  2988. lbAddr g = lb_add_global_generated(p->module, t, v);
  2989. return g;
  2990. }
  2991. GB_ASSERT(LLVMIsALoadInst(v.value));
  2992. lbValue ptr = {};
  2993. ptr.value = LLVMGetOperand(v.value, 0);
  2994. ptr.type = alloc_type_pointer(t);
  2995. return lb_addr(ptr);
  2996. }
  2997. lbValue v = {};
  2998. lbValue *found = map_get(&p->module->values, e);
  2999. if (found) {
  3000. v = *found;
  3001. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  3002. // NOTE(bill): Calculate the using variable every time
  3003. v = lb_get_using_variable(p, e);
  3004. } else if (e->flags & EntityFlag_SoaPtrField) {
  3005. return lb_get_soa_variable_addr(p, e);
  3006. }
  3007. if (v.value == nullptr) {
  3008. return lb_addr(lb_find_value_from_entity(p->module, e));
  3009. // error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  3010. // LIT(p->name),
  3011. // LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  3012. // GB_PANIC("Unknown value");
  3013. }
  3014. return lb_addr(v);
  3015. }
  3016. gb_internal lbAddr lb_build_array_swizzle_addr(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  3017. isize index_count = ce->args.count-1;
  3018. lbAddr addr = lb_build_addr(p, ce->args[0]);
  3019. if (index_count == 0) {
  3020. return addr;
  3021. }
  3022. Type *type = base_type(lb_addr_type(addr));
  3023. GB_ASSERT(type->kind == Type_Array);
  3024. i64 count = type->Array.count;
  3025. if (count <= 4) {
  3026. u8 indices[4] = {};
  3027. u8 index_count = 0;
  3028. for (i32 i = 1; i < ce->args.count; i++) {
  3029. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  3030. GB_ASSERT(is_type_integer(tv.type));
  3031. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  3032. i64 src_index = big_int_to_i64(&tv.value.value_integer);
  3033. indices[index_count++] = cast(u8)src_index;
  3034. }
  3035. return lb_addr_swizzle(lb_addr_get_ptr(p, addr), tv.type, index_count, indices);
  3036. }
  3037. auto indices = slice_make<i32>(permanent_allocator(), ce->args.count-1);
  3038. isize index_index = 0;
  3039. for (i32 i = 1; i < ce->args.count; i++) {
  3040. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  3041. GB_ASSERT(is_type_integer(tv.type));
  3042. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  3043. i64 src_index = big_int_to_i64(&tv.value.value_integer);
  3044. indices[index_index++] = cast(i32)src_index;
  3045. }
  3046. return lb_addr_swizzle_large(lb_addr_get_ptr(p, addr), tv.type, indices);
  3047. }
  3048. gb_internal lbAddr lb_build_addr_internal(lbProcedure *p, Ast *expr);
  3049. gb_internal lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  3050. expr = unparen_expr(expr);
  3051. // IMPORTANT NOTE(bill):
  3052. // Selector Call Expressions (foo->bar(...))
  3053. // must only evaluate `foo` once as it gets transformed into
  3054. // `foo.bar(foo, ...)`
  3055. // And if `foo` is a procedure call or something more complex, storing the value
  3056. // once is a very good idea
  3057. // If a stored value is found, it must be removed from the cache
  3058. if (expr->state_flags & StateFlag_SelectorCallExpr) {
  3059. lbAddr *pp = map_get(&p->selector_addr, expr);
  3060. if (pp != nullptr) {
  3061. lbAddr res = *pp;
  3062. map_remove(&p->selector_addr, expr);
  3063. return res;
  3064. }
  3065. }
  3066. lbAddr addr = lb_build_addr_internal(p, expr);
  3067. if (expr->state_flags & StateFlag_SelectorCallExpr) {
  3068. map_set(&p->selector_addr, expr, addr);
  3069. }
  3070. return addr;
  3071. }
  3072. gb_internal void lb_build_addr_compound_lit_populate(lbProcedure *p, Slice<Ast *> const &elems, Array<lbCompoundLitElemTempData> *temp_data, Type *compound_type) {
  3073. Type *bt = base_type(compound_type);
  3074. Type *et = nullptr;
  3075. switch (bt->kind) {
  3076. case Type_Array: et = bt->Array.elem; break;
  3077. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  3078. case Type_Slice: et = bt->Slice.elem; break;
  3079. case Type_BitSet: et = bt->BitSet.elem; break;
  3080. case Type_DynamicArray: et = bt->DynamicArray.elem; break;
  3081. case Type_SimdVector: et = bt->SimdVector.elem; break;
  3082. case Type_Matrix: et = bt->Matrix.elem; break;
  3083. }
  3084. GB_ASSERT(et != nullptr);
  3085. // NOTE(bill): Separate value, gep, store into their own chunks
  3086. for_array(i, elems) {
  3087. Ast *elem = elems[i];
  3088. if (elem->kind == Ast_FieldValue) {
  3089. ast_node(fv, FieldValue, elem);
  3090. if (lb_is_elem_const(fv->value, et)) {
  3091. continue;
  3092. }
  3093. if (is_ast_range(fv->field)) {
  3094. ast_node(ie, BinaryExpr, fv->field);
  3095. TypeAndValue lo_tav = ie->left->tav;
  3096. TypeAndValue hi_tav = ie->right->tav;
  3097. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3098. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3099. TokenKind op = ie->op.kind;
  3100. i64 lo = exact_value_to_i64(lo_tav.value);
  3101. i64 hi = exact_value_to_i64(hi_tav.value);
  3102. if (op != Token_RangeHalf) {
  3103. hi += 1;
  3104. }
  3105. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  3106. GB_ASSERT((hi-lo) > 0);
  3107. if (bt->kind == Type_Matrix) {
  3108. for (i64 k = lo; k < hi; k++) {
  3109. lbCompoundLitElemTempData data = {};
  3110. data.value = value;
  3111. data.elem_index = matrix_row_major_index_to_offset(bt, k);
  3112. array_add(temp_data, data);
  3113. }
  3114. } else {
  3115. enum {MAX_ELEMENT_AMOUNT = 32};
  3116. if ((hi-lo) <= MAX_ELEMENT_AMOUNT) {
  3117. for (i64 k = lo; k < hi; k++) {
  3118. lbCompoundLitElemTempData data = {};
  3119. data.value = value;
  3120. data.elem_index = k;
  3121. array_add(temp_data, data);
  3122. }
  3123. } else {
  3124. lbCompoundLitElemTempData data = {};
  3125. data.value = value;
  3126. data.elem_index = lo;
  3127. data.elem_length = hi-lo;
  3128. array_add(temp_data, data);
  3129. }
  3130. }
  3131. } else {
  3132. auto tav = fv->field->tav;
  3133. GB_ASSERT(tav.mode == Addressing_Constant);
  3134. i64 index = exact_value_to_i64(tav.value);
  3135. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  3136. GB_ASSERT(!is_type_tuple(value.type));
  3137. lbCompoundLitElemTempData data = {};
  3138. data.value = value;
  3139. data.expr = fv->value;
  3140. if (bt->kind == Type_Matrix) {
  3141. data.elem_index = matrix_row_major_index_to_offset(bt, index);
  3142. } else {
  3143. data.elem_index = index;
  3144. }
  3145. array_add(temp_data, data);
  3146. }
  3147. } else {
  3148. if (bt->kind != Type_DynamicArray && lb_is_elem_const(elem, et)) {
  3149. continue;
  3150. }
  3151. lbValue field_expr = lb_build_expr(p, elem);
  3152. GB_ASSERT(!is_type_tuple(field_expr.type));
  3153. lbValue ev = lb_emit_conv(p, field_expr, et);
  3154. lbCompoundLitElemTempData data = {};
  3155. data.value = ev;
  3156. if (bt->kind == Type_Matrix) {
  3157. data.elem_index = matrix_row_major_index_to_offset(bt, i);
  3158. } else {
  3159. data.elem_index = i;
  3160. }
  3161. array_add(temp_data, data);
  3162. }
  3163. }
  3164. }
  3165. gb_internal void lb_build_addr_compound_lit_assign_array(lbProcedure *p, Array<lbCompoundLitElemTempData> const &temp_data) {
  3166. for (auto const &td : temp_data) {
  3167. if (td.value.value != nullptr) {
  3168. if (td.elem_length > 0) {
  3169. auto loop_data = lb_loop_start(p, cast(isize)td.elem_length, t_i32);
  3170. {
  3171. lbValue dst = td.gep;
  3172. dst = lb_emit_ptr_offset(p, dst, loop_data.idx);
  3173. lb_emit_store(p, dst, td.value);
  3174. }
  3175. lb_loop_end(p, loop_data);
  3176. } else {
  3177. lb_emit_store(p, td.gep, td.value);
  3178. }
  3179. }
  3180. }
  3181. }
  3182. gb_internal lbAddr lb_build_addr_index_expr(lbProcedure *p, Ast *expr) {
  3183. ast_node(ie, IndexExpr, expr);
  3184. Type *t = base_type(type_of_expr(ie->expr));
  3185. bool deref = is_type_pointer(t);
  3186. t = base_type(type_deref(t));
  3187. if (is_type_soa_struct(t)) {
  3188. // SOA STRUCTURES!!!!
  3189. lbValue val = lb_build_addr_ptr(p, ie->expr);
  3190. if (deref) {
  3191. val = lb_emit_load(p, val);
  3192. }
  3193. lbValue index = lb_build_expr(p, ie->index);
  3194. return lb_addr_soa_variable(val, index, ie->index);
  3195. }
  3196. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  3197. // SOA Structures for slices/dynamic arrays
  3198. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  3199. lbValue field = lb_build_expr(p, ie->expr);
  3200. lbValue index = lb_build_expr(p, ie->index);
  3201. if (!build_context.no_bounds_check) {
  3202. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  3203. // GB_ASSERT(LLVMIsALoadInst(field.value));
  3204. // lbValue a = {};
  3205. // a.value = LLVMGetOperand(field.value, 0);
  3206. // a.type = alloc_type_pointer(field.type);
  3207. // irInstr *b = &a->Instr;
  3208. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  3209. // lbValue base_struct = b->StructElementPtr.address;
  3210. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  3211. // lbValue len = ir_soa_struct_len(p, base_struct);
  3212. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3213. }
  3214. lbValue val = lb_emit_ptr_offset(p, field, index);
  3215. return lb_addr(val);
  3216. }
  3217. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  3218. if (is_type_map(t)) {
  3219. lbAddr map_addr = lb_build_addr(p, ie->expr);
  3220. lbValue key = lb_build_expr(p, ie->index);
  3221. key = lb_emit_conv(p, key, t->Map.key);
  3222. Type *result_type = type_of_expr(expr);
  3223. lbValue map_ptr = lb_addr_get_ptr(p, map_addr);
  3224. if (is_type_pointer(type_deref(map_ptr.type))) {
  3225. map_ptr = lb_emit_load(p, map_ptr);
  3226. }
  3227. return lb_addr_map(map_ptr, key, t, result_type);
  3228. }
  3229. switch (t->kind) {
  3230. case Type_Array: {
  3231. lbValue array = {};
  3232. array = lb_build_addr_ptr(p, ie->expr);
  3233. if (deref) {
  3234. array = lb_emit_load(p, array);
  3235. }
  3236. lbValue index = lb_build_expr(p, ie->index);
  3237. index = lb_emit_conv(p, index, t_int);
  3238. lbValue elem = lb_emit_array_ep(p, array, index);
  3239. auto index_tv = type_and_value_of_expr(ie->index);
  3240. if (index_tv.mode != Addressing_Constant) {
  3241. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  3242. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3243. }
  3244. return lb_addr(elem);
  3245. }
  3246. case Type_EnumeratedArray: {
  3247. lbValue array = {};
  3248. array = lb_build_addr_ptr(p, ie->expr);
  3249. if (deref) {
  3250. array = lb_emit_load(p, array);
  3251. }
  3252. Type *index_type = t->EnumeratedArray.index;
  3253. auto index_tv = type_and_value_of_expr(ie->index);
  3254. lbValue index = {};
  3255. if (compare_exact_values(Token_NotEq, *t->EnumeratedArray.min_value, exact_value_i64(0))) {
  3256. if (index_tv.mode == Addressing_Constant) {
  3257. ExactValue idx = exact_value_sub(index_tv.value, *t->EnumeratedArray.min_value);
  3258. index = lb_const_value(p->module, index_type, idx);
  3259. } else {
  3260. index = lb_emit_arith(p, Token_Sub,
  3261. lb_build_expr(p, ie->index),
  3262. lb_const_value(p->module, index_type, *t->EnumeratedArray.min_value),
  3263. index_type);
  3264. index = lb_emit_conv(p, index, t_int);
  3265. }
  3266. } else {
  3267. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  3268. }
  3269. lbValue elem = lb_emit_array_ep(p, array, index);
  3270. if (index_tv.mode != Addressing_Constant) {
  3271. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  3272. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3273. }
  3274. return lb_addr(elem);
  3275. }
  3276. case Type_Slice: {
  3277. lbValue slice = {};
  3278. slice = lb_build_expr(p, ie->expr);
  3279. if (deref) {
  3280. slice = lb_emit_load(p, slice);
  3281. }
  3282. lbValue elem = lb_slice_elem(p, slice);
  3283. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  3284. lbValue len = lb_slice_len(p, slice);
  3285. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3286. lbValue v = lb_emit_ptr_offset(p, elem, index);
  3287. return lb_addr(v);
  3288. }
  3289. case Type_MultiPointer: {
  3290. lbValue multi_ptr = {};
  3291. multi_ptr = lb_build_expr(p, ie->expr);
  3292. if (deref) {
  3293. multi_ptr = lb_emit_load(p, multi_ptr);
  3294. }
  3295. lbValue index = lb_build_expr(p, ie->index);
  3296. index = lb_emit_conv(p, index, t_int);
  3297. lbValue v = {};
  3298. LLVMValueRef indices[1] = {index.value};
  3299. v.value = LLVMBuildGEP2(p->builder, lb_type(p->module, t->MultiPointer.elem), multi_ptr.value, indices, 1, "");
  3300. v.type = alloc_type_pointer(t->MultiPointer.elem);
  3301. return lb_addr(v);
  3302. }
  3303. case Type_RelativeMultiPointer: {
  3304. lbAddr rel_ptr_addr = {};
  3305. if (deref) {
  3306. lbValue rel_ptr_ptr = lb_build_expr(p, ie->expr);
  3307. rel_ptr_addr = lb_addr(rel_ptr_ptr);
  3308. } else {
  3309. rel_ptr_addr = lb_build_addr(p, ie->expr);
  3310. }
  3311. lbValue rel_ptr = lb_relative_pointer_to_pointer(p, rel_ptr_addr);
  3312. lbValue index = lb_build_expr(p, ie->index);
  3313. index = lb_emit_conv(p, index, t_int);
  3314. lbValue v = {};
  3315. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  3316. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  3317. Type *elem = pointer_type->MultiPointer.elem;
  3318. LLVMValueRef indices[1] = {index.value};
  3319. v.value = LLVMBuildGEP2(p->builder, lb_type(p->module, elem), rel_ptr.value, indices, 1, "");
  3320. v.type = alloc_type_pointer(elem);
  3321. return lb_addr(v);
  3322. }
  3323. case Type_DynamicArray: {
  3324. lbValue dynamic_array = {};
  3325. dynamic_array = lb_build_expr(p, ie->expr);
  3326. if (deref) {
  3327. dynamic_array = lb_emit_load(p, dynamic_array);
  3328. }
  3329. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  3330. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  3331. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  3332. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3333. lbValue v = lb_emit_ptr_offset(p, elem, index);
  3334. return lb_addr(v);
  3335. }
  3336. case Type_Matrix: {
  3337. lbValue matrix = {};
  3338. matrix = lb_build_addr_ptr(p, ie->expr);
  3339. if (deref) {
  3340. matrix = lb_emit_load(p, matrix);
  3341. }
  3342. lbValue index = lb_build_expr(p, ie->index);
  3343. index = lb_emit_conv(p, index, t_int);
  3344. lbValue elem = lb_emit_matrix_ep(p, matrix, lb_const_int(p->module, t_int, 0), index);
  3345. elem = lb_emit_conv(p, elem, alloc_type_pointer(type_of_expr(expr)));
  3346. auto index_tv = type_and_value_of_expr(ie->index);
  3347. if (index_tv.mode != Addressing_Constant) {
  3348. lbValue len = lb_const_int(p->module, t_int, t->Matrix.column_count);
  3349. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3350. }
  3351. return lb_addr(elem);
  3352. }
  3353. case Type_Basic: { // Basic_string
  3354. lbValue str;
  3355. lbValue elem;
  3356. lbValue len;
  3357. lbValue index;
  3358. str = lb_build_expr(p, ie->expr);
  3359. if (deref) {
  3360. str = lb_emit_load(p, str);
  3361. }
  3362. elem = lb_string_elem(p, str);
  3363. len = lb_string_len(p, str);
  3364. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  3365. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3366. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  3367. }
  3368. }
  3369. return {};
  3370. }
  3371. gb_internal lbAddr lb_build_addr_slice_expr(lbProcedure *p, Ast *expr) {
  3372. ast_node(se, SliceExpr, expr);
  3373. lbValue low = lb_const_int(p->module, t_int, 0);
  3374. lbValue high = {};
  3375. if (se->low != nullptr) {
  3376. low = lb_correct_endianness(p, lb_build_expr(p, se->low));
  3377. }
  3378. if (se->high != nullptr) {
  3379. high = lb_correct_endianness(p, lb_build_expr(p, se->high));
  3380. }
  3381. bool no_indices = se->low == nullptr && se->high == nullptr;
  3382. lbAddr addr = lb_build_addr(p, se->expr);
  3383. lbValue base = lb_addr_load(p, addr);
  3384. Type *type = base_type(base.type);
  3385. if (is_type_pointer(type)) {
  3386. type = base_type(type_deref(type));
  3387. addr = lb_addr(base);
  3388. base = lb_addr_load(p, addr);
  3389. }
  3390. switch (type->kind) {
  3391. case Type_Slice: {
  3392. Type *slice_type = type;
  3393. lbValue len = lb_slice_len(p, base);
  3394. if (high.value == nullptr) high = len;
  3395. if (!no_indices) {
  3396. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3397. }
  3398. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  3399. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3400. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  3401. lb_fill_slice(p, slice, elem, new_len);
  3402. return slice;
  3403. }
  3404. case Type_RelativePointer:
  3405. GB_PANIC("TODO(bill): Type_RelativePointer should be handled above already on the lb_addr_load");
  3406. break;
  3407. case Type_RelativeMultiPointer:
  3408. GB_PANIC("TODO(bill): Type_RelativeMultiPointer should be handled above already on the lb_addr_load");
  3409. break;
  3410. case Type_DynamicArray: {
  3411. Type *elem_type = type->DynamicArray.elem;
  3412. Type *slice_type = alloc_type_slice(elem_type);
  3413. lbValue len = lb_dynamic_array_len(p, base);
  3414. if (high.value == nullptr) high = len;
  3415. if (!no_indices) {
  3416. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3417. }
  3418. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  3419. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3420. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  3421. lb_fill_slice(p, slice, elem, new_len);
  3422. return slice;
  3423. }
  3424. case Type_MultiPointer: {
  3425. lbAddr res = lb_add_local_generated(p, type_of_expr(expr), false);
  3426. if (se->high == nullptr) {
  3427. lbValue offset = base;
  3428. LLVMValueRef indices[1] = {low.value};
  3429. offset.value = LLVMBuildGEP2(p->builder, lb_type(p->module, offset.type->MultiPointer.elem), offset.value, indices, 1, "");
  3430. lb_addr_store(p, res, offset);
  3431. } else {
  3432. low = lb_emit_conv(p, low, t_int);
  3433. high = lb_emit_conv(p, high, t_int);
  3434. lb_emit_multi_pointer_slice_bounds_check(p, se->open, low, high);
  3435. LLVMValueRef indices[1] = {low.value};
  3436. LLVMValueRef ptr = LLVMBuildGEP2(p->builder, lb_type(p->module, base.type->MultiPointer.elem), base.value, indices, 1, "");
  3437. LLVMValueRef len = LLVMBuildSub(p->builder, high.value, low.value, "");
  3438. LLVMValueRef gep0 = lb_emit_struct_ep(p, res.addr, 0).value;
  3439. LLVMValueRef gep1 = lb_emit_struct_ep(p, res.addr, 1).value;
  3440. LLVMBuildStore(p->builder, ptr, gep0);
  3441. LLVMBuildStore(p->builder, len, gep1);
  3442. }
  3443. return res;
  3444. }
  3445. case Type_Array: {
  3446. Type *slice_type = alloc_type_slice(type->Array.elem);
  3447. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  3448. if (high.value == nullptr) high = len;
  3449. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  3450. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  3451. if (!low_const || !high_const) {
  3452. if (!no_indices) {
  3453. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3454. }
  3455. }
  3456. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  3457. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3458. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  3459. lb_fill_slice(p, slice, elem, new_len);
  3460. return slice;
  3461. }
  3462. case Type_Basic: {
  3463. GB_ASSERT_MSG(type == t_string, "got %s", type_to_string(type));
  3464. lbValue len = lb_string_len(p, base);
  3465. if (high.value == nullptr) high = len;
  3466. if (!no_indices) {
  3467. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3468. }
  3469. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  3470. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3471. lbAddr str = lb_add_local_generated(p, t_string, false);
  3472. lb_fill_string(p, str, elem, new_len);
  3473. return str;
  3474. }
  3475. case Type_Struct:
  3476. if (is_type_soa_struct(type)) {
  3477. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  3478. if (high.value == nullptr) high = len;
  3479. if (!no_indices) {
  3480. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3481. }
  3482. #if 1
  3483. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  3484. if (type->Struct.soa_kind == StructSoa_Fixed) {
  3485. i32 field_count = cast(i32)type->Struct.fields.count;
  3486. for (i32 i = 0; i < field_count; i++) {
  3487. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  3488. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  3489. field_src = lb_emit_array_ep(p, field_src, low);
  3490. lb_emit_store(p, field_dst, field_src);
  3491. }
  3492. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  3493. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3494. lb_emit_store(p, len_dst, new_len);
  3495. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  3496. if (no_indices) {
  3497. lb_addr_store(p, dst, base);
  3498. } else {
  3499. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  3500. for (i32 i = 0; i < field_count; i++) {
  3501. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  3502. lbValue field_src = lb_emit_struct_ev(p, base, i);
  3503. field_src = lb_emit_ptr_offset(p, field_src, low);
  3504. lb_emit_store(p, field_dst, field_src);
  3505. }
  3506. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  3507. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3508. lb_emit_store(p, len_dst, new_len);
  3509. }
  3510. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  3511. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  3512. for (i32 i = 0; i < field_count; i++) {
  3513. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  3514. lbValue field_src = lb_emit_struct_ev(p, base, i);
  3515. field_src = lb_emit_ptr_offset(p, field_src, low);
  3516. lb_emit_store(p, field_dst, field_src);
  3517. }
  3518. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  3519. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3520. lb_emit_store(p, len_dst, new_len);
  3521. }
  3522. return dst;
  3523. #endif
  3524. }
  3525. break;
  3526. }
  3527. GB_PANIC("Unknown slicable type");
  3528. return {};
  3529. }
  3530. gb_internal lbAddr lb_build_addr_compound_lit(lbProcedure *p, Ast *expr) {
  3531. ast_node(cl, CompoundLit, expr);
  3532. Type *type = type_of_expr(expr);
  3533. Type *bt = base_type(type);
  3534. lbAddr v = lb_add_local_generated(p, type, true);
  3535. TEMPORARY_ALLOCATOR_GUARD();
  3536. Type *et = nullptr;
  3537. switch (bt->kind) {
  3538. case Type_Array: et = bt->Array.elem; break;
  3539. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  3540. case Type_Slice: et = bt->Slice.elem; break;
  3541. case Type_BitSet: et = bt->BitSet.elem; break;
  3542. case Type_SimdVector: et = bt->SimdVector.elem; break;
  3543. case Type_Matrix: et = bt->Matrix.elem; break;
  3544. }
  3545. String proc_name = {};
  3546. if (p->entity) {
  3547. proc_name = p->entity->token.string;
  3548. }
  3549. TokenPos pos = ast_token(expr).pos;
  3550. switch (bt->kind) {
  3551. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  3552. case Type_Struct: {
  3553. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  3554. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  3555. bool is_raw_union = is_type_raw_union(bt);
  3556. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  3557. TypeStruct *st = &bt->Struct;
  3558. if (cl->elems.count > 0) {
  3559. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3560. lbValue comp_lit_ptr = lb_addr_get_ptr(p, v);
  3561. for_array(field_index, cl->elems) {
  3562. Ast *elem = cl->elems[field_index];
  3563. lbValue field_expr = {};
  3564. Entity *field = nullptr;
  3565. isize index = field_index;
  3566. if (elem->kind == Ast_FieldValue) {
  3567. ast_node(fv, FieldValue, elem);
  3568. String name = fv->field->Ident.token.string;
  3569. Selection sel = lookup_field(bt, name, false);
  3570. GB_ASSERT(!sel.indirect);
  3571. elem = fv->value;
  3572. if (sel.index.count > 1) {
  3573. if (lb_is_nested_possibly_constant(type, sel, elem)) {
  3574. continue;
  3575. }
  3576. lbValue dst = lb_emit_deep_field_gep(p, comp_lit_ptr, sel);
  3577. field_expr = lb_build_expr(p, elem);
  3578. field_expr = lb_emit_conv(p, field_expr, sel.entity->type);
  3579. lb_emit_store(p, dst, field_expr);
  3580. continue;
  3581. }
  3582. index = sel.index[0];
  3583. } else {
  3584. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_index);
  3585. GB_ASSERT(sel.index.count == 1);
  3586. GB_ASSERT(!sel.indirect);
  3587. index = sel.index[0];
  3588. }
  3589. field = st->fields[index];
  3590. Type *ft = field->type;
  3591. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  3592. continue;
  3593. }
  3594. field_expr = lb_build_expr(p, elem);
  3595. lbValue gep = {};
  3596. if (is_raw_union) {
  3597. gep = lb_emit_conv(p, comp_lit_ptr, alloc_type_pointer(ft));
  3598. } else {
  3599. gep = lb_emit_struct_ep(p, comp_lit_ptr, cast(i32)index);
  3600. }
  3601. Type *fet = field_expr.type;
  3602. GB_ASSERT(fet->kind != Type_Tuple);
  3603. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  3604. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  3605. GB_ASSERT_MSG(union_variant_index(ft, fet) >= 0, "%s", type_to_string(fet));
  3606. lb_emit_store_union_variant(p, gep, field_expr, fet);
  3607. } else {
  3608. lbValue fv = lb_emit_conv(p, field_expr, ft);
  3609. lb_emit_store(p, gep, fv);
  3610. }
  3611. }
  3612. }
  3613. break;
  3614. }
  3615. case Type_Map: {
  3616. if (cl->elems.count == 0) {
  3617. break;
  3618. }
  3619. GB_ASSERT(!build_context.no_dynamic_literals);
  3620. lbValue err = lb_dynamic_map_reserve(p, v.addr, 2*cl->elems.count, pos);
  3621. gb_unused(err);
  3622. for (Ast *elem : cl->elems) {
  3623. ast_node(fv, FieldValue, elem);
  3624. lbValue key = lb_build_expr(p, fv->field);
  3625. lbValue value = lb_build_expr(p, fv->value);
  3626. lb_internal_dynamic_map_set(p, v.addr, type, key, value, elem);
  3627. }
  3628. break;
  3629. }
  3630. case Type_Array: {
  3631. if (cl->elems.count > 0) {
  3632. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3633. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3634. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3635. lbValue dst_ptr = lb_addr_get_ptr(p, v);
  3636. for_array(i, temp_data) {
  3637. i32 index = cast(i32)(temp_data[i].elem_index);
  3638. temp_data[i].gep = lb_emit_array_epi(p, dst_ptr, index);
  3639. }
  3640. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3641. }
  3642. break;
  3643. }
  3644. case Type_EnumeratedArray: {
  3645. if (cl->elems.count > 0) {
  3646. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3647. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3648. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3649. lbValue dst_ptr = lb_addr_get_ptr(p, v);
  3650. i64 index_offset = exact_value_to_i64(*bt->EnumeratedArray.min_value);
  3651. for_array(i, temp_data) {
  3652. i32 index = cast(i32)(temp_data[i].elem_index - index_offset);
  3653. temp_data[i].gep = lb_emit_array_epi(p, dst_ptr, index);
  3654. }
  3655. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3656. }
  3657. break;
  3658. }
  3659. case Type_Slice: {
  3660. if (cl->elems.count > 0) {
  3661. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  3662. lbValue data = lb_slice_elem(p, slice);
  3663. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3664. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3665. for_array(i, temp_data) {
  3666. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  3667. }
  3668. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3669. {
  3670. lbValue count = {};
  3671. count.type = t_int;
  3672. unsigned len_index = lb_convert_struct_index(p->module, type, 1);
  3673. if (lb_is_const(slice)) {
  3674. unsigned indices[1] = {len_index};
  3675. count.value = llvm_const_extract_value(p->module, slice.value, indices, gb_count_of(indices));
  3676. } else {
  3677. count.value = LLVMBuildExtractValue(p->builder, slice.value, len_index, "");
  3678. }
  3679. lb_fill_slice(p, v, data, count);
  3680. }
  3681. }
  3682. break;
  3683. }
  3684. case Type_DynamicArray: {
  3685. if (cl->elems.count == 0) {
  3686. break;
  3687. }
  3688. GB_ASSERT(!build_context.no_dynamic_literals);
  3689. Type *et = bt->DynamicArray.elem;
  3690. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  3691. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  3692. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  3693. {
  3694. auto args = array_make<lbValue>(temporary_allocator(), 5);
  3695. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  3696. args[1] = size;
  3697. args[2] = align;
  3698. args[3] = lb_const_int(p->module, t_int, item_count);
  3699. args[4] = lb_emit_source_code_location_as_global(p, proc_name, pos);
  3700. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  3701. }
  3702. lbValue items = lb_generate_local_array(p, et, item_count);
  3703. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3704. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3705. for_array(i, temp_data) {
  3706. temp_data[i].gep = lb_emit_array_epi(p, items, temp_data[i].elem_index);
  3707. }
  3708. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3709. {
  3710. auto args = array_make<lbValue>(temporary_allocator(), 6);
  3711. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  3712. args[1] = size;
  3713. args[2] = align;
  3714. args[3] = lb_emit_conv(p, items, t_rawptr);
  3715. args[4] = lb_const_int(p->module, t_int, item_count);
  3716. args[5] = lb_emit_source_code_location_as_global(p, proc_name, pos);
  3717. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  3718. }
  3719. break;
  3720. }
  3721. case Type_Basic: {
  3722. GB_ASSERT(is_type_any(bt));
  3723. if (cl->elems.count > 0) {
  3724. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3725. String field_names[2] = {
  3726. str_lit("data"),
  3727. str_lit("id"),
  3728. };
  3729. Type *field_types[2] = {
  3730. t_rawptr,
  3731. t_typeid,
  3732. };
  3733. for_array(field_index, cl->elems) {
  3734. Ast *elem = cl->elems[field_index];
  3735. lbValue field_expr = {};
  3736. isize index = field_index;
  3737. if (elem->kind == Ast_FieldValue) {
  3738. ast_node(fv, FieldValue, elem);
  3739. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  3740. index = sel.index[0];
  3741. elem = fv->value;
  3742. } else {
  3743. TypeAndValue tav = type_and_value_of_expr(elem);
  3744. Selection sel = lookup_field(bt, field_names[field_index], false);
  3745. index = sel.index[0];
  3746. }
  3747. field_expr = lb_build_expr(p, elem);
  3748. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  3749. Type *ft = field_types[index];
  3750. lbValue fv = lb_emit_conv(p, field_expr, ft);
  3751. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  3752. lb_emit_store(p, gep, fv);
  3753. }
  3754. }
  3755. break;
  3756. }
  3757. case Type_BitSet: {
  3758. i64 sz = type_size_of(type);
  3759. if (cl->elems.count > 0 && sz > 0) {
  3760. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3761. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  3762. for (Ast *elem : cl->elems) {
  3763. GB_ASSERT(elem->kind != Ast_FieldValue);
  3764. if (lb_is_elem_const(elem, et)) {
  3765. continue;
  3766. }
  3767. lbValue expr = lb_build_expr(p, elem);
  3768. GB_ASSERT(expr.type->kind != Type_Tuple);
  3769. Type *it = bit_set_to_int(bt);
  3770. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  3771. lbValue e = lb_emit_conv(p, expr, it);
  3772. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  3773. e = lb_emit_arith(p, Token_Shl, one, e, it);
  3774. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  3775. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  3776. new_value = lb_emit_transmute(p, new_value, type);
  3777. lb_addr_store(p, v, new_value);
  3778. }
  3779. }
  3780. break;
  3781. }
  3782. case Type_Matrix: {
  3783. if (cl->elems.count > 0) {
  3784. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3785. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3786. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3787. lbValue dst_ptr = lb_addr_get_ptr(p, v);
  3788. for_array(i, temp_data) {
  3789. temp_data[i].gep = lb_emit_array_epi(p, dst_ptr, temp_data[i].elem_index);
  3790. }
  3791. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3792. }
  3793. break;
  3794. }
  3795. case Type_SimdVector: {
  3796. if (cl->elems.count > 0) {
  3797. lbValue vector_value = lb_const_value(p->module, type, exact_value_compound(expr));
  3798. defer (lb_addr_store(p, v, vector_value));
  3799. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3800. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3801. // TODO(bill): reduce the need for individual `insertelement` if a `shufflevector`
  3802. // might be a better option
  3803. for (auto const &td : temp_data) {
  3804. if (td.value.value != nullptr) {
  3805. if (td.elem_length > 0) {
  3806. for (i64 k = 0; k < td.elem_length; k++) {
  3807. LLVMValueRef index = lb_const_int(p->module, t_u32, td.elem_index + k).value;
  3808. vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, "");
  3809. }
  3810. } else {
  3811. LLVMValueRef index = lb_const_int(p->module, t_u32, td.elem_index).value;
  3812. vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, "");
  3813. }
  3814. }
  3815. }
  3816. }
  3817. break;
  3818. }
  3819. }
  3820. return v;
  3821. }
  3822. gb_internal lbAddr lb_build_addr_internal(lbProcedure *p, Ast *expr) {
  3823. switch (expr->kind) {
  3824. case_ast_node(i, Implicit, expr);
  3825. lbAddr v = {};
  3826. switch (i->kind) {
  3827. case Token_context:
  3828. v = lb_find_or_generate_context_ptr(p);
  3829. break;
  3830. }
  3831. GB_ASSERT(v.addr.value != nullptr);
  3832. return v;
  3833. case_end;
  3834. case_ast_node(i, Ident, expr);
  3835. if (is_blank_ident(expr)) {
  3836. lbAddr val = {};
  3837. return val;
  3838. }
  3839. String name = i->token.string;
  3840. Entity *e = entity_of_node(expr);
  3841. return lb_build_addr_from_entity(p, e, expr);
  3842. case_end;
  3843. case_ast_node(se, SelectorExpr, expr);
  3844. Ast *sel_node = unparen_expr(se->selector);
  3845. if (sel_node->kind == Ast_Ident) {
  3846. String selector = sel_node->Ident.token.string;
  3847. TypeAndValue tav = type_and_value_of_expr(se->expr);
  3848. if (tav.mode == Addressing_Invalid) {
  3849. // NOTE(bill): Imports
  3850. Entity *imp = entity_of_node(se->expr);
  3851. if (imp != nullptr) {
  3852. GB_ASSERT(imp->kind == Entity_ImportName);
  3853. }
  3854. return lb_build_addr(p, unparen_expr(se->selector));
  3855. }
  3856. Type *type = base_type(tav.type);
  3857. if (tav.mode == Addressing_Type) { // Addressing_Type
  3858. Selection sel = lookup_field(tav.type, selector, true);
  3859. if (sel.pseudo_field) {
  3860. GB_ASSERT(sel.entity->kind == Entity_Procedure);
  3861. return lb_addr(lb_find_value_from_entity(p->module, sel.entity));
  3862. }
  3863. GB_PANIC("Unreachable %.*s", LIT(selector));
  3864. }
  3865. if (se->swizzle_count > 0) {
  3866. Type *array_type = base_type(type_deref(tav.type));
  3867. GB_ASSERT(array_type->kind == Type_Array);
  3868. u8 swizzle_count = se->swizzle_count;
  3869. u8 swizzle_indices_raw = se->swizzle_indices;
  3870. u8 swizzle_indices[4] = {};
  3871. for (u8 i = 0; i < swizzle_count; i++) {
  3872. u8 index = swizzle_indices_raw>>(i*2) & 3;
  3873. swizzle_indices[i] = index;
  3874. }
  3875. lbValue a = {};
  3876. if (is_type_pointer(tav.type)) {
  3877. a = lb_build_expr(p, se->expr);
  3878. } else {
  3879. lbAddr addr = lb_build_addr(p, se->expr);
  3880. a = lb_addr_get_ptr(p, addr);
  3881. }
  3882. GB_ASSERT(is_type_array(expr->tav.type));
  3883. return lb_addr_swizzle(a, expr->tav.type, swizzle_count, swizzle_indices);
  3884. }
  3885. Selection sel = lookup_field(type, selector, false);
  3886. GB_ASSERT(sel.entity != nullptr);
  3887. if (sel.pseudo_field) {
  3888. GB_ASSERT(sel.entity->kind == Entity_Procedure || sel.entity->kind == Entity_ProcGroup);
  3889. Entity *e = entity_of_node(sel_node);
  3890. GB_ASSERT(e->kind == Entity_Procedure);
  3891. return lb_addr(lb_find_value_from_entity(p->module, e));
  3892. }
  3893. {
  3894. lbAddr addr = lb_build_addr(p, se->expr);
  3895. if (addr.kind == lbAddr_Map) {
  3896. lbValue v = lb_addr_load(p, addr);
  3897. lbValue a = lb_address_from_load_or_generate_local(p, v);
  3898. a = lb_emit_deep_field_gep(p, a, sel);
  3899. return lb_addr(a);
  3900. } else if (addr.kind == lbAddr_Context) {
  3901. GB_ASSERT(sel.index.count > 0);
  3902. if (addr.ctx.sel.index.count >= 0) {
  3903. sel = selection_combine(addr.ctx.sel, sel);
  3904. }
  3905. addr.ctx.sel = sel;
  3906. addr.kind = lbAddr_Context;
  3907. return addr;
  3908. } else if (addr.kind == lbAddr_SoaVariable) {
  3909. lbValue index = addr.soa.index;
  3910. i32 first_index = sel.index[0];
  3911. Selection sub_sel = sel;
  3912. sub_sel.index.data += 1;
  3913. sub_sel.index.count -= 1;
  3914. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  3915. Type *t = base_type(type_deref(addr.addr.type));
  3916. GB_ASSERT(is_type_soa_struct(t));
  3917. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  3918. lbValue len = lb_soa_struct_len(p, addr.addr);
  3919. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  3920. }
  3921. lbValue item = {};
  3922. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3923. item = lb_emit_array_ep(p, arr, index);
  3924. } else {
  3925. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  3926. }
  3927. if (sub_sel.index.count > 0) {
  3928. item = lb_emit_deep_field_gep(p, item, sub_sel);
  3929. }
  3930. return lb_addr(item);
  3931. } else if (addr.kind == lbAddr_Swizzle) {
  3932. GB_ASSERT(sel.index.count > 0);
  3933. // NOTE(bill): just patch the index in place
  3934. sel.index[0] = addr.swizzle.indices[sel.index[0]];
  3935. } else if (addr.kind == lbAddr_SwizzleLarge) {
  3936. GB_ASSERT(sel.index.count > 0);
  3937. // NOTE(bill): just patch the index in place
  3938. sel.index[0] = addr.swizzle.indices[sel.index[0]];
  3939. }
  3940. lbValue a = lb_addr_get_ptr(p, addr);
  3941. a = lb_emit_deep_field_gep(p, a, sel);
  3942. return lb_addr(a);
  3943. }
  3944. } else {
  3945. GB_PANIC("Unsupported selector expression");
  3946. }
  3947. case_end;
  3948. case_ast_node(se, SelectorCallExpr, expr);
  3949. lbValue e = lb_build_expr(p, expr);
  3950. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  3951. case_end;
  3952. case_ast_node(ta, TypeAssertion, expr);
  3953. TokenPos pos = ast_token(expr).pos;
  3954. lbValue e = lb_build_expr(p, ta->expr);
  3955. Type *t = type_deref(e.type);
  3956. if (is_type_union(t)) {
  3957. Type *type = type_of_expr(expr);
  3958. lbAddr v = lb_add_local_generated(p, type, false);
  3959. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  3960. return v;
  3961. } else if (is_type_any(t)) {
  3962. Type *type = type_of_expr(expr);
  3963. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  3964. } else {
  3965. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  3966. }
  3967. case_end;
  3968. case_ast_node(ue, UnaryExpr, expr);
  3969. switch (ue->op.kind) {
  3970. case Token_And: {
  3971. lbValue ptr = lb_build_expr(p, expr);
  3972. return lb_addr(lb_address_from_load_or_generate_local(p, ptr));
  3973. }
  3974. default:
  3975. GB_PANIC("Invalid unary expression for lb_build_addr");
  3976. }
  3977. case_end;
  3978. case_ast_node(be, BinaryExpr, expr);
  3979. lbValue v = lb_build_expr(p, expr);
  3980. Type *t = v.type;
  3981. if (is_type_pointer(t)) {
  3982. return lb_addr(v);
  3983. }
  3984. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  3985. case_end;
  3986. case_ast_node(ie, IndexExpr, expr);
  3987. return lb_build_addr_index_expr(p, expr);
  3988. case_end;
  3989. case_ast_node(ie, MatrixIndexExpr, expr);
  3990. Type *t = base_type(type_of_expr(ie->expr));
  3991. bool deref = is_type_pointer(t);
  3992. t = base_type(type_deref(t));
  3993. lbValue m = {};
  3994. m = lb_build_addr_ptr(p, ie->expr);
  3995. if (deref) {
  3996. m = lb_emit_load(p, m);
  3997. }
  3998. lbValue row_index = lb_build_expr(p, ie->row_index);
  3999. lbValue column_index = lb_build_expr(p, ie->column_index);
  4000. row_index = lb_emit_conv(p, row_index, t_int);
  4001. column_index = lb_emit_conv(p, column_index, t_int);
  4002. lbValue elem = lb_emit_matrix_ep(p, m, row_index, column_index);
  4003. auto row_index_tv = type_and_value_of_expr(ie->row_index);
  4004. auto column_index_tv = type_and_value_of_expr(ie->column_index);
  4005. if (row_index_tv.mode != Addressing_Constant || column_index_tv.mode != Addressing_Constant) {
  4006. lbValue row_count = lb_const_int(p->module, t_int, t->Matrix.row_count);
  4007. lbValue column_count = lb_const_int(p->module, t_int, t->Matrix.column_count);
  4008. lb_emit_matrix_bounds_check(p, ast_token(ie->row_index), row_index, column_index, row_count, column_count);
  4009. }
  4010. return lb_addr(elem);
  4011. case_end;
  4012. case_ast_node(se, SliceExpr, expr);
  4013. return lb_build_addr_slice_expr(p, expr);
  4014. case_end;
  4015. case_ast_node(de, DerefExpr, expr);
  4016. Type *t = type_of_expr(de->expr);
  4017. if (is_type_relative_pointer(t)) {
  4018. lbAddr addr = lb_build_addr(p, de->expr);
  4019. addr.relative.deref = true;
  4020. return addr;
  4021. } else if (is_type_soa_pointer(t)) {
  4022. lbValue value = lb_build_expr(p, de->expr);
  4023. lbValue ptr = lb_emit_struct_ev(p, value, 0);
  4024. lbValue idx = lb_emit_struct_ev(p, value, 1);
  4025. return lb_addr_soa_variable(ptr, idx, nullptr);
  4026. }
  4027. lbValue addr = lb_build_expr(p, de->expr);
  4028. return lb_addr(addr);
  4029. case_end;
  4030. case_ast_node(ce, CallExpr, expr);
  4031. BuiltinProcId builtin_id = BuiltinProc_Invalid;
  4032. if (ce->proc->tav.mode == Addressing_Builtin) {
  4033. Entity *e = entity_of_node(ce->proc);
  4034. if (e != nullptr) {
  4035. builtin_id = cast(BuiltinProcId)e->Builtin.id;
  4036. } else {
  4037. builtin_id = BuiltinProc_DIRECTIVE;
  4038. }
  4039. }
  4040. auto const &tv = expr->tav;
  4041. if (builtin_id == BuiltinProc_swizzle &&
  4042. is_type_array(tv.type)) {
  4043. // NOTE(bill, 2021-08-09): `swizzle` has some bizarre semantics so it needs to be
  4044. // specialized here for to be addressable
  4045. return lb_build_array_swizzle_addr(p, ce, tv);
  4046. }
  4047. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  4048. lbValue e = lb_build_expr(p, expr);
  4049. #if 1
  4050. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  4051. #else
  4052. lbAddr v = lb_add_local_generated(p, e.type, false);
  4053. lb_addr_store(p, v, e);
  4054. return v;
  4055. #endif
  4056. case_end;
  4057. case_ast_node(cl, CompoundLit, expr);
  4058. return lb_build_addr_compound_lit(p, expr);
  4059. case_end;
  4060. case_ast_node(tc, TypeCast, expr);
  4061. Type *type = type_of_expr(expr);
  4062. lbValue x = lb_build_expr(p, tc->expr);
  4063. lbValue e = {};
  4064. switch (tc->token.kind) {
  4065. case Token_cast:
  4066. e = lb_emit_conv(p, x, type);
  4067. break;
  4068. case Token_transmute:
  4069. e = lb_emit_transmute(p, x, type);
  4070. break;
  4071. default:
  4072. GB_PANIC("Invalid AST TypeCast");
  4073. }
  4074. lbAddr v = lb_add_local_generated(p, type, false);
  4075. lb_addr_store(p, v, e);
  4076. return v;
  4077. case_end;
  4078. case_ast_node(ac, AutoCast, expr);
  4079. return lb_build_addr(p, ac->expr);
  4080. case_end;
  4081. case_ast_node(te, TernaryIfExpr, expr);
  4082. LLVMValueRef incoming_values[2] = {};
  4083. LLVMBasicBlockRef incoming_blocks[2] = {};
  4084. GB_ASSERT(te->y != nullptr);
  4085. lbBlock *then = lb_create_block(p, "if.then");
  4086. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  4087. lbBlock *else_ = lb_create_block(p, "if.else");
  4088. lb_build_cond(p, te->cond, then, else_);
  4089. lb_start_block(p, then);
  4090. Type *ptr_type = alloc_type_pointer(default_type(type_of_expr(expr)));
  4091. incoming_values[0] = lb_emit_conv(p, lb_build_addr_ptr(p, te->x), ptr_type).value;
  4092. lb_emit_jump(p, done);
  4093. lb_start_block(p, else_);
  4094. incoming_values[1] = lb_emit_conv(p, lb_build_addr_ptr(p, te->y), ptr_type).value;
  4095. lb_emit_jump(p, done);
  4096. lb_start_block(p, done);
  4097. lbValue res = {};
  4098. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, ptr_type), "");
  4099. res.type = ptr_type;
  4100. GB_ASSERT(p->curr_block->preds.count >= 2);
  4101. incoming_blocks[0] = p->curr_block->preds[0]->block;
  4102. incoming_blocks[1] = p->curr_block->preds[1]->block;
  4103. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  4104. return lb_addr(res);
  4105. case_end;
  4106. case_ast_node(oe, OrElseExpr, expr);
  4107. lbValue ptr = lb_address_from_load_or_generate_local(p, lb_build_expr(p, expr));
  4108. return lb_addr(ptr);
  4109. case_end;
  4110. case_ast_node(oe, OrReturnExpr, expr);
  4111. lbValue ptr = lb_address_from_load_or_generate_local(p, lb_build_expr(p, expr));
  4112. return lb_addr(ptr);
  4113. case_end;
  4114. }
  4115. TokenPos token_pos = ast_token(expr).pos;
  4116. GB_PANIC("Unexpected address expression\n"
  4117. "\tAst: %.*s @ "
  4118. "%s\n",
  4119. LIT(ast_strings[expr->kind]),
  4120. token_pos_to_string(token_pos));
  4121. return {};
  4122. }