llvm_backend_expr.cpp 155 KB

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