llvm_backend_expr.cpp 153 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908
  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. // Pointer <-> uintptr
  1641. if (is_type_pointer(src) && is_type_uintptr(dst)) {
  1642. lbValue res = {};
  1643. res.type = t;
  1644. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  1645. return res;
  1646. }
  1647. if (is_type_uintptr(src) && is_type_pointer(dst)) {
  1648. lbValue res = {};
  1649. res.type = t;
  1650. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  1651. return res;
  1652. }
  1653. if (is_type_multi_pointer(src) && is_type_uintptr(dst)) {
  1654. lbValue res = {};
  1655. res.type = t;
  1656. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  1657. return res;
  1658. }
  1659. if (is_type_uintptr(src) && is_type_multi_pointer(dst)) {
  1660. lbValue res = {};
  1661. res.type = t;
  1662. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  1663. return res;
  1664. }
  1665. if (is_type_union(dst)) {
  1666. for (Type *vt : dst->Union.variants) {
  1667. if (are_types_identical(vt, src_type)) {
  1668. lbAddr parent = lb_add_local_generated(p, t, true);
  1669. lb_emit_store_union_variant(p, parent.addr, value, vt);
  1670. return lb_addr_load(p, parent);
  1671. }
  1672. }
  1673. if (dst->Union.variants.count == 1) {
  1674. Type *vt = dst->Union.variants[0];
  1675. if (internal_check_is_assignable_to(src_type, vt)) {
  1676. value = lb_emit_conv(p, value, vt);
  1677. lbAddr parent = lb_add_local_generated(p, t, true);
  1678. lb_emit_store_union_variant(p, parent.addr, value, vt);
  1679. return lb_addr_load(p, parent);
  1680. }
  1681. }
  1682. }
  1683. // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's
  1684. // subtype polymorphism casting
  1685. if (check_is_assignable_to_using_subtype(src_type, t)) {
  1686. Type *st = type_deref(src_type);
  1687. st = type_deref(st);
  1688. bool st_is_ptr = is_type_pointer(src_type);
  1689. st = base_type(st);
  1690. Type *dt = t;
  1691. GB_ASSERT(is_type_struct(st) || is_type_raw_union(st));
  1692. Selection sel = {};
  1693. sel.index.allocator = heap_allocator();
  1694. defer (array_free(&sel.index));
  1695. if (lookup_subtype_polymorphic_selection(t, src_type, &sel)) {
  1696. if (sel.entity == nullptr) {
  1697. GB_PANIC("invalid subtype cast %s -> ", type_to_string(src_type), type_to_string(t));
  1698. }
  1699. if (st_is_ptr) {
  1700. lbValue res = lb_emit_deep_field_gep(p, value, sel);
  1701. Type *rt = res.type;
  1702. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  1703. res = lb_emit_load(p, res);
  1704. }
  1705. return res;
  1706. } else {
  1707. if (is_type_pointer(value.type)) {
  1708. Type *rt = value.type;
  1709. if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) {
  1710. value = lb_emit_load(p, value);
  1711. } else {
  1712. value = lb_emit_deep_field_gep(p, value, sel);
  1713. return lb_emit_load(p, value);
  1714. }
  1715. }
  1716. return lb_emit_deep_field_ev(p, value, sel);
  1717. }
  1718. }
  1719. }
  1720. // Pointer <-> Pointer
  1721. if (is_type_pointer(src) && is_type_pointer(dst)) {
  1722. lbValue res = {};
  1723. res.type = t;
  1724. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1725. return res;
  1726. }
  1727. if (is_type_multi_pointer(src) && is_type_pointer(dst)) {
  1728. lbValue res = {};
  1729. res.type = t;
  1730. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1731. return res;
  1732. }
  1733. if (is_type_pointer(src) && is_type_multi_pointer(dst)) {
  1734. lbValue res = {};
  1735. res.type = t;
  1736. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1737. return res;
  1738. }
  1739. if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) {
  1740. lbValue res = {};
  1741. res.type = t;
  1742. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1743. return res;
  1744. }
  1745. // proc <-> proc
  1746. if (is_type_proc(src) && is_type_proc(dst)) {
  1747. lbValue res = {};
  1748. res.type = t;
  1749. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1750. return res;
  1751. }
  1752. // pointer -> proc
  1753. if (is_type_pointer(src) && is_type_proc(dst)) {
  1754. lbValue res = {};
  1755. res.type = t;
  1756. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1757. return res;
  1758. }
  1759. // proc -> pointer
  1760. if (is_type_proc(src) && is_type_pointer(dst)) {
  1761. lbValue res = {};
  1762. res.type = t;
  1763. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), "");
  1764. return res;
  1765. }
  1766. // []byte/[]u8 <-> string
  1767. if (is_type_u8_slice(src) && is_type_string(dst)) {
  1768. return lb_emit_transmute(p, value, t);
  1769. }
  1770. if (is_type_string(src) && is_type_u8_slice(dst)) {
  1771. return lb_emit_transmute(p, value, t);
  1772. }
  1773. if (is_type_array_like(dst)) {
  1774. Type *elem = base_array_type(dst);
  1775. lbValue e = lb_emit_conv(p, value, elem);
  1776. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1777. lbAddr v = lb_add_local_generated(p, t, false);
  1778. isize index_count = cast(isize)get_array_type_count(dst);
  1779. for (isize i = 0; i < index_count; i++) {
  1780. lbValue elem = lb_emit_array_epi(p, v.addr, i);
  1781. lb_emit_store(p, elem, e);
  1782. }
  1783. return lb_addr_load(p, v);
  1784. }
  1785. if (is_type_matrix(dst) && !is_type_matrix(src)) {
  1786. GB_ASSERT_MSG(dst->Matrix.row_count == dst->Matrix.column_count, "%s <- %s", type_to_string(dst), type_to_string(src));
  1787. Type *elem = base_array_type(dst);
  1788. lbValue e = lb_emit_conv(p, value, elem);
  1789. lbAddr v = lb_add_local_generated(p, t, false);
  1790. lbValue zero = lb_const_value(p->module, elem, exact_value_i64(0), true);
  1791. for (i64 j = 0; j < dst->Matrix.column_count; j++) {
  1792. for (i64 i = 0; i < dst->Matrix.row_count; i++) {
  1793. lbValue ptr = lb_emit_matrix_epi(p, v.addr, i, j);
  1794. lb_emit_store(p, ptr, i == j ? e : zero);
  1795. }
  1796. }
  1797. return lb_addr_load(p, v);
  1798. }
  1799. if (is_type_matrix(dst) && is_type_matrix(src)) {
  1800. GB_ASSERT(dst->kind == Type_Matrix);
  1801. GB_ASSERT(src->kind == Type_Matrix);
  1802. lbAddr v = lb_add_local_generated(p, t, true);
  1803. if (is_matrix_square(dst) && is_matrix_square(dst)) {
  1804. for (i64 j = 0; j < dst->Matrix.column_count; j++) {
  1805. for (i64 i = 0; i < dst->Matrix.row_count; i++) {
  1806. if (i < src->Matrix.row_count && j < src->Matrix.column_count) {
  1807. lbValue d = lb_emit_matrix_epi(p, v.addr, i, j);
  1808. lbValue s = lb_emit_matrix_ev(p, value, i, j);
  1809. lb_emit_store(p, d, s);
  1810. } else if (i == j) {
  1811. lbValue d = lb_emit_matrix_epi(p, v.addr, i, j);
  1812. lbValue s = lb_const_value(p->module, dst->Matrix.elem, exact_value_i64(1), true);
  1813. lb_emit_store(p, d, s);
  1814. }
  1815. }
  1816. }
  1817. } else {
  1818. i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count;
  1819. i64 src_count = src->Matrix.row_count*src->Matrix.column_count;
  1820. GB_ASSERT(dst_count == src_count);
  1821. lbValue pdst = v.addr;
  1822. lbValue psrc = lb_address_from_load_or_generate_local(p, value);
  1823. bool same_elem_base_types = are_types_identical(
  1824. base_type(dst->Matrix.elem),
  1825. base_type(src->Matrix.elem)
  1826. );
  1827. if (same_elem_base_types && type_size_of(dst) == type_size_of(src)) {
  1828. lb_mem_copy_overlapping(p, v.addr, psrc, lb_const_int(p->module, t_int, type_size_of(dst)));
  1829. } else {
  1830. for (i64 i = 0; i < src_count; i++) {
  1831. lbValue dp = lb_emit_array_epi(p, v.addr, matrix_column_major_index_to_offset(dst, i));
  1832. lbValue sp = lb_emit_array_epi(p, psrc, matrix_column_major_index_to_offset(src, i));
  1833. lbValue s = lb_emit_load(p, sp);
  1834. s = lb_emit_conv(p, s, dst->Matrix.elem);
  1835. lb_emit_store(p, dp, s);
  1836. }
  1837. }
  1838. }
  1839. return lb_addr_load(p, v);
  1840. }
  1841. if (is_type_any(dst)) {
  1842. if (is_type_untyped_uninit(src)) {
  1843. return lb_const_undef(p->module, t);
  1844. }
  1845. if (is_type_untyped_nil(src)) {
  1846. return lb_const_nil(p->module, t);
  1847. }
  1848. lbAddr result = lb_add_local_generated(p, t, true);
  1849. Type *st = default_type(src_type);
  1850. lbValue data = lb_address_from_load_or_generate_local(p, value);
  1851. GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type));
  1852. GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st));
  1853. data = lb_emit_conv(p, data, t_rawptr);
  1854. lbValue id = lb_typeid(p->module, st);
  1855. lbValue any_data = lb_emit_struct_ep(p, result.addr, 0);
  1856. lbValue any_id = lb_emit_struct_ep(p, result.addr, 1);
  1857. lb_emit_store(p, any_data, data);
  1858. lb_emit_store(p, any_id, id);
  1859. return lb_addr_load(p, result);
  1860. }
  1861. i64 src_sz = type_size_of(src);
  1862. i64 dst_sz = type_size_of(dst);
  1863. if (src_sz == dst_sz) {
  1864. // bit_set <-> integer
  1865. if (is_type_integer(src) && is_type_bit_set(dst)) {
  1866. lbValue res = lb_emit_conv(p, value, bit_set_to_int(dst));
  1867. res.type = t;
  1868. return res;
  1869. }
  1870. if (is_type_bit_set(src) && is_type_integer(dst)) {
  1871. lbValue bs = value;
  1872. bs.type = bit_set_to_int(src);
  1873. return lb_emit_conv(p, bs, dst);
  1874. }
  1875. // typeid <-> integer
  1876. if (is_type_integer(src) && is_type_typeid(dst)) {
  1877. return lb_emit_transmute(p, value, dst);
  1878. }
  1879. if (is_type_typeid(src) && is_type_integer(dst)) {
  1880. return lb_emit_transmute(p, value, dst);
  1881. }
  1882. }
  1883. if (is_type_untyped(src)) {
  1884. if (is_type_string(src) && is_type_string(dst)) {
  1885. lbAddr result = lb_add_local_generated(p, t, false);
  1886. lb_addr_store(p, result, value);
  1887. return lb_addr_load(p, result);
  1888. }
  1889. }
  1890. gb_printf_err("%.*s\n", LIT(p->name));
  1891. gb_printf_err("lb_emit_conv: src -> dst\n");
  1892. gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t));
  1893. gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst));
  1894. gb_printf_err("Not Identical %p != %p\n", src_type, t);
  1895. gb_printf_err("Not Identical %p != %p\n", src, dst);
  1896. GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'",
  1897. type_to_string(src_type), type_to_string(t),
  1898. LIT(p->name));
  1899. return {};
  1900. }
  1901. gb_internal lbValue lb_compare_records(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right, Type *type) {
  1902. GB_ASSERT((is_type_struct(type) || is_type_union(type)) && is_type_comparable(type));
  1903. lbValue left_ptr = lb_address_from_load_or_generate_local(p, left);
  1904. lbValue right_ptr = lb_address_from_load_or_generate_local(p, right);
  1905. lbValue res = {};
  1906. if (type_size_of(type) == 0) {
  1907. switch (op_kind) {
  1908. case Token_CmpEq:
  1909. return lb_const_bool(p->module, t_bool, true);
  1910. case Token_NotEq:
  1911. return lb_const_bool(p->module, t_bool, false);
  1912. }
  1913. GB_PANIC("invalid operator");
  1914. }
  1915. TEMPORARY_ALLOCATOR_GUARD();
  1916. if (is_type_simple_compare(type)) {
  1917. // TODO(bill): Test to see if this is actually faster!!!!
  1918. auto args = array_make<lbValue>(temporary_allocator(), 3);
  1919. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  1920. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  1921. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  1922. res = lb_emit_runtime_call(p, "memory_equal", args);
  1923. } else {
  1924. lbValue value = lb_equal_proc_for_type(p->module, type);
  1925. auto args = array_make<lbValue>(temporary_allocator(), 2);
  1926. args[0] = lb_emit_conv(p, left_ptr, t_rawptr);
  1927. args[1] = lb_emit_conv(p, right_ptr, t_rawptr);
  1928. res = lb_emit_call(p, value, args);
  1929. }
  1930. if (op_kind == Token_NotEq) {
  1931. res = lb_emit_unary_arith(p, Token_Not, res, res.type);
  1932. }
  1933. return res;
  1934. }
  1935. gb_internal lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) {
  1936. Type *a = core_type(left.type);
  1937. Type *b = core_type(right.type);
  1938. GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1));
  1939. lbValue nil_check = {};
  1940. if (is_type_array_like(left.type) || is_type_array_like(right.type)) {
  1941. // don't do `nil` check if it is array-like
  1942. } else if (is_type_untyped_nil(left.type)) {
  1943. nil_check = lb_emit_comp_against_nil(p, op_kind, right);
  1944. } else if (is_type_untyped_nil(right.type)) {
  1945. nil_check = lb_emit_comp_against_nil(p, op_kind, left);
  1946. }
  1947. if (nil_check.value != nullptr) {
  1948. return nil_check;
  1949. }
  1950. if (are_types_identical(a, b)) {
  1951. // NOTE(bill): No need for a conversion
  1952. } else if (lb_is_const(left) || lb_is_const_nil(left)) {
  1953. left = lb_emit_conv(p, left, right.type);
  1954. } else if (lb_is_const(right) || lb_is_const_nil(right)) {
  1955. right = lb_emit_conv(p, right, left.type);
  1956. } else {
  1957. Type *lt = left.type;
  1958. Type *rt = right.type;
  1959. lt = left.type;
  1960. rt = right.type;
  1961. i64 ls = type_size_of(lt);
  1962. i64 rs = type_size_of(rt);
  1963. // NOTE(bill): Quick heuristic, larger types are usually the target type
  1964. if (ls < rs) {
  1965. left = lb_emit_conv(p, left, rt);
  1966. } else if (ls > rs) {
  1967. right = lb_emit_conv(p, right, lt);
  1968. } else {
  1969. if (is_type_union(rt)) {
  1970. left = lb_emit_conv(p, left, rt);
  1971. } else {
  1972. right = lb_emit_conv(p, right, lt);
  1973. }
  1974. }
  1975. }
  1976. a = core_type(left.type);
  1977. b = core_type(right.type);
  1978. if (is_type_matrix(a) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  1979. Type *tl = base_type(a);
  1980. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  1981. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  1982. // TODO(bill): Test to see if this is actually faster!!!!
  1983. auto args = array_make<lbValue>(permanent_allocator(), 3);
  1984. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  1985. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  1986. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  1987. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  1988. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  1989. return lb_emit_conv(p, res, t_bool);
  1990. }
  1991. if (is_type_array_like(a)) {
  1992. Type *tl = base_type(a);
  1993. lbValue lhs = lb_address_from_load_or_generate_local(p, left);
  1994. lbValue rhs = lb_address_from_load_or_generate_local(p, right);
  1995. TokenKind cmp_op = Token_And;
  1996. lbValue res = lb_const_bool(p->module, t_llvm_bool, true);
  1997. if (op_kind == Token_NotEq) {
  1998. res = lb_const_bool(p->module, t_llvm_bool, false);
  1999. cmp_op = Token_Or;
  2000. } else if (op_kind == Token_CmpEq) {
  2001. res = lb_const_bool(p->module, t_llvm_bool, true);
  2002. cmp_op = Token_And;
  2003. }
  2004. bool inline_array_arith = lb_can_try_to_inline_array_arith(tl);
  2005. i32 count = 0;
  2006. switch (tl->kind) {
  2007. case Type_Array: count = cast(i32)tl->Array.count; break;
  2008. case Type_EnumeratedArray: count = cast(i32)tl->EnumeratedArray.count; break;
  2009. }
  2010. if (inline_array_arith) {
  2011. // inline
  2012. lbAddr val = lb_add_local_generated(p, t_bool, false);
  2013. lb_addr_store(p, val, res);
  2014. for (i32 i = 0; i < count; i++) {
  2015. lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i));
  2016. lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i));
  2017. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  2018. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  2019. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  2020. }
  2021. return lb_addr_load(p, val);
  2022. } else {
  2023. if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) {
  2024. // TODO(bill): Test to see if this is actually faster!!!!
  2025. auto args = array_make<lbValue>(permanent_allocator(), 3);
  2026. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  2027. args[1] = lb_emit_conv(p, rhs, t_rawptr);
  2028. args[2] = lb_const_int(p->module, t_int, type_size_of(tl));
  2029. lbValue val = lb_emit_runtime_call(p, "memory_compare", args);
  2030. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type));
  2031. return lb_emit_conv(p, res, t_bool);
  2032. } else {
  2033. lbAddr val = lb_add_local_generated(p, t_bool, false);
  2034. lb_addr_store(p, val, res);
  2035. auto loop_data = lb_loop_start(p, count, t_i32);
  2036. {
  2037. lbValue i = loop_data.idx;
  2038. lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i));
  2039. lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i));
  2040. lbValue cmp = lb_emit_comp(p, op_kind, x, y);
  2041. lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool);
  2042. lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool));
  2043. }
  2044. lb_loop_end(p, loop_data);
  2045. return lb_addr_load(p, val);
  2046. }
  2047. }
  2048. }
  2049. if ((is_type_struct(a) || is_type_union(a)) && is_type_comparable(a)) {
  2050. return lb_compare_records(p, op_kind, left, right, a);
  2051. }
  2052. if ((is_type_struct(b) || is_type_union(b)) && is_type_comparable(b)) {
  2053. return lb_compare_records(p, op_kind, left, right, b);
  2054. }
  2055. if (is_type_string(a)) {
  2056. if (is_type_cstring(a) && is_type_cstring(b)) {
  2057. left = lb_emit_conv(p, left, t_cstring);
  2058. right = lb_emit_conv(p, right, t_cstring);
  2059. char const *runtime_procedure = nullptr;
  2060. switch (op_kind) {
  2061. case Token_CmpEq: runtime_procedure = "cstring_eq"; break;
  2062. case Token_NotEq: runtime_procedure = "cstring_ne"; break;
  2063. case Token_Lt: runtime_procedure = "cstring_lt"; break;
  2064. case Token_Gt: runtime_procedure = "cstring_gt"; break;
  2065. case Token_LtEq: runtime_procedure = "cstring_le"; break;
  2066. case Token_GtEq: runtime_procedure = "cstring_gt"; break;
  2067. }
  2068. GB_ASSERT(runtime_procedure != nullptr);
  2069. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2070. args[0] = left;
  2071. args[1] = right;
  2072. return lb_emit_runtime_call(p, runtime_procedure, args);
  2073. }
  2074. if (is_type_cstring(a) ^ is_type_cstring(b)) {
  2075. left = lb_emit_conv(p, left, t_string);
  2076. right = lb_emit_conv(p, right, t_string);
  2077. }
  2078. char const *runtime_procedure = nullptr;
  2079. switch (op_kind) {
  2080. case Token_CmpEq: runtime_procedure = "string_eq"; break;
  2081. case Token_NotEq: runtime_procedure = "string_ne"; break;
  2082. case Token_Lt: runtime_procedure = "string_lt"; break;
  2083. case Token_Gt: runtime_procedure = "string_gt"; break;
  2084. case Token_LtEq: runtime_procedure = "string_le"; break;
  2085. case Token_GtEq: runtime_procedure = "string_gt"; break;
  2086. }
  2087. GB_ASSERT(runtime_procedure != nullptr);
  2088. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2089. args[0] = left;
  2090. args[1] = right;
  2091. return lb_emit_runtime_call(p, runtime_procedure, args);
  2092. }
  2093. if (is_type_complex(a)) {
  2094. char const *runtime_procedure = "";
  2095. i64 sz = 8*type_size_of(a);
  2096. switch (sz) {
  2097. case 32:
  2098. switch (op_kind) {
  2099. case Token_CmpEq: runtime_procedure = "complex32_eq"; break;
  2100. case Token_NotEq: runtime_procedure = "complex32_ne"; break;
  2101. }
  2102. break;
  2103. case 64:
  2104. switch (op_kind) {
  2105. case Token_CmpEq: runtime_procedure = "complex64_eq"; break;
  2106. case Token_NotEq: runtime_procedure = "complex64_ne"; break;
  2107. }
  2108. break;
  2109. case 128:
  2110. switch (op_kind) {
  2111. case Token_CmpEq: runtime_procedure = "complex128_eq"; break;
  2112. case Token_NotEq: runtime_procedure = "complex128_ne"; break;
  2113. }
  2114. break;
  2115. }
  2116. GB_ASSERT(runtime_procedure != nullptr);
  2117. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2118. args[0] = left;
  2119. args[1] = right;
  2120. return lb_emit_runtime_call(p, runtime_procedure, args);
  2121. }
  2122. if (is_type_quaternion(a)) {
  2123. char const *runtime_procedure = "";
  2124. i64 sz = 8*type_size_of(a);
  2125. switch (sz) {
  2126. case 64:
  2127. switch (op_kind) {
  2128. case Token_CmpEq: runtime_procedure = "quaternion64_eq"; break;
  2129. case Token_NotEq: runtime_procedure = "quaternion64_ne"; break;
  2130. }
  2131. break;
  2132. case 128:
  2133. switch (op_kind) {
  2134. case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break;
  2135. case Token_NotEq: runtime_procedure = "quaternion128_ne"; break;
  2136. }
  2137. break;
  2138. case 256:
  2139. switch (op_kind) {
  2140. case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break;
  2141. case Token_NotEq: runtime_procedure = "quaternion256_ne"; break;
  2142. }
  2143. break;
  2144. }
  2145. GB_ASSERT(runtime_procedure != nullptr);
  2146. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2147. args[0] = left;
  2148. args[1] = right;
  2149. return lb_emit_runtime_call(p, runtime_procedure, args);
  2150. }
  2151. if (is_type_bit_set(a)) {
  2152. switch (op_kind) {
  2153. case Token_Lt:
  2154. case Token_LtEq:
  2155. case Token_Gt:
  2156. case Token_GtEq:
  2157. {
  2158. Type *it = bit_set_to_int(a);
  2159. lbValue lhs = lb_emit_transmute(p, left, it);
  2160. lbValue rhs = lb_emit_transmute(p, right, it);
  2161. lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it);
  2162. if (op_kind == Token_Lt || op_kind == Token_LtEq) {
  2163. // (lhs & rhs) == lhs
  2164. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, "");
  2165. res.type = t_llvm_bool;
  2166. } else if (op_kind == Token_Gt || op_kind == Token_GtEq) {
  2167. // (lhs & rhs) == rhs
  2168. res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, "");
  2169. res.type = t_llvm_bool;
  2170. }
  2171. // NOTE(bill): Strict subsets
  2172. if (op_kind == Token_Lt || op_kind == Token_Gt) {
  2173. // res &~ (lhs == rhs)
  2174. lbValue eq = {};
  2175. eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, "");
  2176. eq.type = t_llvm_bool;
  2177. res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool);
  2178. }
  2179. return res;
  2180. }
  2181. case Token_CmpEq:
  2182. case Token_NotEq:
  2183. {
  2184. LLVMIntPredicate pred = {};
  2185. switch (op_kind) {
  2186. case Token_CmpEq: pred = LLVMIntEQ; break;
  2187. case Token_NotEq: pred = LLVMIntNE; break;
  2188. }
  2189. lbValue res = {};
  2190. res.type = t_llvm_bool;
  2191. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  2192. return res;
  2193. }
  2194. }
  2195. }
  2196. if (op_kind != Token_CmpEq && op_kind != Token_NotEq) {
  2197. Type *t = left.type;
  2198. if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) {
  2199. Type *platform_type = integer_endian_type_to_platform_type(t);
  2200. lbValue x = lb_emit_byte_swap(p, left, platform_type);
  2201. lbValue y = lb_emit_byte_swap(p, right, platform_type);
  2202. left = x;
  2203. right = y;
  2204. } else if (is_type_float(t) && is_type_different_to_arch_endianness(t)) {
  2205. Type *platform_type = integer_endian_type_to_platform_type(t);
  2206. lbValue x = lb_emit_conv(p, left, platform_type);
  2207. lbValue y = lb_emit_conv(p, right, platform_type);
  2208. left = x;
  2209. right = y;
  2210. }
  2211. }
  2212. a = core_type(left.type);
  2213. b = core_type(right.type);
  2214. lbValue res = {};
  2215. res.type = t_llvm_bool;
  2216. if (is_type_integer(a) ||
  2217. is_type_boolean(a) ||
  2218. is_type_pointer(a) ||
  2219. is_type_multi_pointer(a) ||
  2220. is_type_proc(a) ||
  2221. is_type_enum(a)) {
  2222. LLVMIntPredicate pred = {};
  2223. if (is_type_unsigned(left.type)) {
  2224. switch (op_kind) {
  2225. case Token_Gt: pred = LLVMIntUGT; break;
  2226. case Token_GtEq: pred = LLVMIntUGE; break;
  2227. case Token_Lt: pred = LLVMIntULT; break;
  2228. case Token_LtEq: pred = LLVMIntULE; break;
  2229. }
  2230. } else {
  2231. switch (op_kind) {
  2232. case Token_Gt: pred = LLVMIntSGT; break;
  2233. case Token_GtEq: pred = LLVMIntSGE; break;
  2234. case Token_Lt: pred = LLVMIntSLT; break;
  2235. case Token_LtEq: pred = LLVMIntSLE; break;
  2236. }
  2237. }
  2238. switch (op_kind) {
  2239. case Token_CmpEq: pred = LLVMIntEQ; break;
  2240. case Token_NotEq: pred = LLVMIntNE; break;
  2241. }
  2242. LLVMValueRef lhs = left.value;
  2243. LLVMValueRef rhs = right.value;
  2244. if (LLVMTypeOf(lhs) != LLVMTypeOf(rhs)) {
  2245. if (lb_is_type_kind(LLVMTypeOf(lhs), LLVMPointerTypeKind)) {
  2246. rhs = LLVMBuildPointerCast(p->builder, rhs, LLVMTypeOf(lhs), "");
  2247. }
  2248. }
  2249. res.value = LLVMBuildICmp(p->builder, pred, lhs, rhs, "");
  2250. } else if (is_type_float(a)) {
  2251. LLVMRealPredicate pred = {};
  2252. switch (op_kind) {
  2253. case Token_CmpEq: pred = LLVMRealOEQ; break;
  2254. case Token_Gt: pred = LLVMRealOGT; break;
  2255. case Token_GtEq: pred = LLVMRealOGE; break;
  2256. case Token_Lt: pred = LLVMRealOLT; break;
  2257. case Token_LtEq: pred = LLVMRealOLE; break;
  2258. case Token_NotEq: pred = LLVMRealONE; break;
  2259. }
  2260. res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  2261. } else if (is_type_typeid(a)) {
  2262. LLVMIntPredicate pred = {};
  2263. switch (op_kind) {
  2264. case Token_Gt: pred = LLVMIntUGT; break;
  2265. case Token_GtEq: pred = LLVMIntUGE; break;
  2266. case Token_Lt: pred = LLVMIntULT; break;
  2267. case Token_LtEq: pred = LLVMIntULE; break;
  2268. case Token_CmpEq: pred = LLVMIntEQ; break;
  2269. case Token_NotEq: pred = LLVMIntNE; break;
  2270. }
  2271. res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  2272. } else if (is_type_simd_vector(a)) {
  2273. LLVMValueRef mask = nullptr;
  2274. Type *elem = base_array_type(a);
  2275. if (is_type_float(elem)) {
  2276. LLVMRealPredicate pred = {};
  2277. switch (op_kind) {
  2278. case Token_CmpEq: pred = LLVMRealOEQ; break;
  2279. case Token_NotEq: pred = LLVMRealONE; break;
  2280. }
  2281. mask = LLVMBuildFCmp(p->builder, pred, left.value, right.value, "");
  2282. } else {
  2283. LLVMIntPredicate pred = {};
  2284. switch (op_kind) {
  2285. case Token_CmpEq: pred = LLVMIntEQ; break;
  2286. case Token_NotEq: pred = LLVMIntNE; break;
  2287. }
  2288. mask = LLVMBuildICmp(p->builder, pred, left.value, right.value, "");
  2289. }
  2290. 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)));
  2291. /* NOTE(bill, 2022-05-28):
  2292. Thanks to Per Vognsen, sign extending <N x i1> to
  2293. a vector of the same width as the input vector, bit casting to an integer,
  2294. and then comparing against zero is the better option
  2295. See: https://lists.llvm.org/pipermail/llvm-dev/2012-September/053046.html
  2296. // Example assuming 128-bit vector
  2297. %1 = <4 x float> ...
  2298. %2 = <4 x float> ...
  2299. %3 = fcmp oeq <4 x float> %1, %2
  2300. %4 = sext <4 x i1> %3 to <4 x i32>
  2301. %5 = bitcast <4 x i32> %4 to i128
  2302. %6 = icmp ne i128 %5, 0
  2303. br i1 %6, label %true1, label %false2
  2304. This will result in 1 cmpps + 1 ptest + 1 br
  2305. (even without SSE4.1, contrary to what the mail list states, because of pmovmskb)
  2306. */
  2307. unsigned count = cast(unsigned)get_array_type_count(a);
  2308. unsigned elem_sz = cast(unsigned)(type_size_of(elem)*8);
  2309. LLVMTypeRef mask_type = LLVMVectorType(LLVMIntTypeInContext(p->module->ctx, elem_sz), count);
  2310. mask = LLVMBuildSExtOrBitCast(p->builder, mask, mask_type, "");
  2311. LLVMTypeRef mask_int_type = LLVMIntTypeInContext(p->module->ctx, cast(unsigned)(8*type_size_of(a)));
  2312. LLVMValueRef mask_int = LLVMBuildBitCast(p->builder, mask, mask_int_type, "");
  2313. res.value = LLVMBuildICmp(p->builder, LLVMIntNE, mask_int, LLVMConstNull(LLVMTypeOf(mask_int)), "");
  2314. return res;
  2315. } else {
  2316. 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)));
  2317. }
  2318. return res;
  2319. }
  2320. gb_internal lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) {
  2321. lbValue res = {};
  2322. res.type = t_llvm_bool;
  2323. Type *t = x.type;
  2324. Type *bt = base_type(t);
  2325. TypeKind type_kind = bt->kind;
  2326. switch (type_kind) {
  2327. case Type_Basic:
  2328. switch (bt->Basic.kind) {
  2329. case Basic_rawptr:
  2330. case Basic_cstring:
  2331. if (op_kind == Token_CmpEq) {
  2332. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  2333. } else if (op_kind == Token_NotEq) {
  2334. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  2335. }
  2336. return res;
  2337. case Basic_any:
  2338. {
  2339. // TODO(bill): is this correct behaviour for nil comparison for any?
  2340. lbValue data = lb_emit_struct_ev(p, x, 0);
  2341. lbValue ti = lb_emit_struct_ev(p, x, 1);
  2342. if (op_kind == Token_CmpEq) {
  2343. LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, "");
  2344. LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, "");
  2345. res.value = LLVMBuildOr(p->builder, a, b, "");
  2346. return res;
  2347. } else if (op_kind == Token_NotEq) {
  2348. LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, "");
  2349. LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, "");
  2350. res.value = LLVMBuildAnd(p->builder, a, b, "");
  2351. return res;
  2352. }
  2353. }
  2354. break;
  2355. case Basic_typeid:
  2356. lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0));
  2357. return lb_emit_comp(p, op_kind, x, invalid_typeid);
  2358. }
  2359. break;
  2360. case Type_Enum:
  2361. case Type_Pointer:
  2362. case Type_MultiPointer:
  2363. case Type_Proc:
  2364. case Type_BitSet:
  2365. if (op_kind == Token_CmpEq) {
  2366. res.value = LLVMBuildIsNull(p->builder, x.value, "");
  2367. } else if (op_kind == Token_NotEq) {
  2368. res.value = LLVMBuildIsNotNull(p->builder, x.value, "");
  2369. }
  2370. return res;
  2371. case Type_Slice:
  2372. {
  2373. lbValue data = lb_emit_struct_ev(p, x, 0);
  2374. if (op_kind == Token_CmpEq) {
  2375. res.value = LLVMBuildIsNull(p->builder, data.value, "");
  2376. return res;
  2377. } else if (op_kind == Token_NotEq) {
  2378. res.value = LLVMBuildIsNotNull(p->builder, data.value, "");
  2379. return res;
  2380. }
  2381. }
  2382. break;
  2383. case Type_DynamicArray:
  2384. {
  2385. lbValue data = lb_emit_struct_ev(p, x, 0);
  2386. if (op_kind == Token_CmpEq) {
  2387. res.value = LLVMBuildIsNull(p->builder, data.value, "");
  2388. return res;
  2389. } else if (op_kind == Token_NotEq) {
  2390. res.value = LLVMBuildIsNotNull(p->builder, data.value, "");
  2391. return res;
  2392. }
  2393. }
  2394. break;
  2395. case Type_Map:
  2396. {
  2397. lbValue data_ptr = lb_emit_struct_ev(p, x, 0);
  2398. if (op_kind == Token_CmpEq) {
  2399. res.value = LLVMBuildIsNull(p->builder, data_ptr.value, "");
  2400. return res;
  2401. } else {
  2402. res.value = LLVMBuildIsNotNull(p->builder, data_ptr.value, "");
  2403. return res;
  2404. }
  2405. }
  2406. break;
  2407. case Type_Union:
  2408. {
  2409. if (type_size_of(t) == 0) {
  2410. if (op_kind == Token_CmpEq) {
  2411. return lb_const_bool(p->module, t_llvm_bool, true);
  2412. } else if (op_kind == Token_NotEq) {
  2413. return lb_const_bool(p->module, t_llvm_bool, false);
  2414. }
  2415. } else if (is_type_union_maybe_pointer(t)) {
  2416. lbValue tag = lb_emit_transmute(p, x, t_rawptr);
  2417. return lb_emit_comp_against_nil(p, op_kind, tag);
  2418. } else {
  2419. lbValue tag = lb_emit_union_tag_value(p, x);
  2420. return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type));
  2421. }
  2422. }
  2423. case Type_Struct:
  2424. if (is_type_soa_struct(t)) {
  2425. Type *bt = base_type(t);
  2426. if (bt->Struct.soa_kind == StructSoa_Slice) {
  2427. LLVMValueRef the_value = {};
  2428. if (bt->Struct.fields.count == 0) {
  2429. lbValue len = lb_soa_struct_len(p, x);
  2430. the_value = len.value;
  2431. } else {
  2432. lbValue first_field = lb_emit_struct_ev(p, x, 0);
  2433. the_value = first_field.value;
  2434. }
  2435. if (op_kind == Token_CmpEq) {
  2436. res.value = LLVMBuildIsNull(p->builder, the_value, "");
  2437. return res;
  2438. } else if (op_kind == Token_NotEq) {
  2439. res.value = LLVMBuildIsNotNull(p->builder, the_value, "");
  2440. return res;
  2441. }
  2442. } else if (bt->Struct.soa_kind == StructSoa_Dynamic) {
  2443. LLVMValueRef the_value = {};
  2444. if (bt->Struct.fields.count == 0) {
  2445. lbValue cap = lb_soa_struct_cap(p, x);
  2446. the_value = cap.value;
  2447. } else {
  2448. lbValue first_field = lb_emit_struct_ev(p, x, 0);
  2449. the_value = first_field.value;
  2450. }
  2451. if (op_kind == Token_CmpEq) {
  2452. res.value = LLVMBuildIsNull(p->builder, the_value, "");
  2453. return res;
  2454. } else if (op_kind == Token_NotEq) {
  2455. res.value = LLVMBuildIsNotNull(p->builder, the_value, "");
  2456. return res;
  2457. }
  2458. }
  2459. } else if (is_type_struct(t) && type_has_nil(t)) {
  2460. auto args = array_make<lbValue>(permanent_allocator(), 2);
  2461. lbValue lhs = lb_address_from_load_or_generate_local(p, x);
  2462. args[0] = lb_emit_conv(p, lhs, t_rawptr);
  2463. args[1] = lb_const_int(p->module, t_int, type_size_of(t));
  2464. lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args);
  2465. lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0));
  2466. return res;
  2467. }
  2468. break;
  2469. }
  2470. GB_PANIC("Unknown handled type: %s -> %s", type_to_string(t), type_to_string(bt));
  2471. return {};
  2472. }
  2473. gb_internal lbValue lb_make_soa_pointer(lbProcedure *p, Type *type, lbValue const &addr, lbValue const &index) {
  2474. lbAddr v = lb_add_local_generated(p, type, false);
  2475. lbValue ptr = lb_emit_struct_ep(p, v.addr, 0);
  2476. lbValue idx = lb_emit_struct_ep(p, v.addr, 1);
  2477. lb_emit_store(p, ptr, addr);
  2478. lb_emit_store(p, idx, lb_emit_conv(p, index, t_int));
  2479. return lb_addr_load(p, v);
  2480. }
  2481. gb_internal lbValue lb_build_unary_and(lbProcedure *p, Ast *expr) {
  2482. ast_node(ue, UnaryExpr, expr);
  2483. auto tv = type_and_value_of_expr(expr);
  2484. Ast *ue_expr = unparen_expr(ue->expr);
  2485. if (ue_expr->kind == Ast_IndexExpr && tv.mode == Addressing_OptionalOkPtr && is_type_tuple(tv.type)) {
  2486. Type *tuple = tv.type;
  2487. Type *map_type = type_of_expr(ue_expr->IndexExpr.expr);
  2488. Type *ot = base_type(map_type);
  2489. Type *t = base_type(type_deref(ot));
  2490. bool deref = t != ot;
  2491. GB_ASSERT(t->kind == Type_Map);
  2492. ast_node(ie, IndexExpr, ue_expr);
  2493. lbValue map_val = lb_build_addr_ptr(p, ie->expr);
  2494. if (deref) {
  2495. map_val = lb_emit_load(p, map_val);
  2496. }
  2497. lbValue key = lb_build_expr(p, ie->index);
  2498. key = lb_emit_conv(p, key, t->Map.key);
  2499. lbAddr addr = lb_addr_map(map_val, key, t, alloc_type_pointer(t->Map.value));
  2500. lbValue ptr = lb_addr_get_ptr(p, addr);
  2501. lbValue ok = lb_emit_comp_against_nil(p, Token_NotEq, ptr);
  2502. ok = lb_emit_conv(p, ok, tuple->Tuple.variables[1]->type);
  2503. lbAddr res = lb_add_local_generated(p, tuple, false);
  2504. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  2505. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  2506. lb_emit_store(p, gep0, ptr);
  2507. lb_emit_store(p, gep1, ok);
  2508. return lb_addr_load(p, res);
  2509. } else if (is_type_soa_pointer(tv.type)) {
  2510. ast_node(ie, IndexExpr, ue_expr);
  2511. lbValue addr = lb_build_addr_ptr(p, ie->expr);
  2512. if (is_type_pointer(type_deref(addr.type))) {
  2513. addr = lb_emit_load(p, addr);
  2514. }
  2515. GB_ASSERT(is_type_pointer(addr.type));
  2516. lbValue index = lb_build_expr(p, ie->index);
  2517. if (!build_context.no_bounds_check) {
  2518. // TODO(bill): soa bounds checking
  2519. }
  2520. return lb_make_soa_pointer(p, tv.type, addr, index);
  2521. } else if (ue_expr->kind == Ast_CompoundLit) {
  2522. lbValue v = lb_build_expr(p, ue->expr);
  2523. Type *type = v.type;
  2524. lbAddr addr = {};
  2525. if (p->is_startup) {
  2526. addr = lb_add_global_generated(p->module, type, v);
  2527. } else {
  2528. addr = lb_add_local_generated(p, type, false);
  2529. }
  2530. lb_addr_store(p, addr, v);
  2531. return addr.addr;
  2532. } else if (ue_expr->kind == Ast_TypeAssertion) {
  2533. if (is_type_tuple(tv.type)) {
  2534. Type *tuple = tv.type;
  2535. Type *ptr_type = tuple->Tuple.variables[0]->type;
  2536. Type *ok_type = tuple->Tuple.variables[1]->type;
  2537. ast_node(ta, TypeAssertion, ue_expr);
  2538. TokenPos pos = ast_token(expr).pos;
  2539. Type *type = type_of_expr(ue_expr);
  2540. GB_ASSERT(!is_type_tuple(type));
  2541. lbValue e = lb_build_expr(p, ta->expr);
  2542. Type *t = type_deref(e.type);
  2543. if (is_type_union(t)) {
  2544. lbValue v = e;
  2545. if (!is_type_pointer(v.type)) {
  2546. v = lb_address_from_load_or_generate_local(p, v);
  2547. }
  2548. Type *src_type = type_deref(v.type);
  2549. Type *dst_type = type;
  2550. lbValue src_tag = {};
  2551. lbValue dst_tag = {};
  2552. if (is_type_union_maybe_pointer(src_type)) {
  2553. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  2554. dst_tag = lb_const_bool(p->module, t_bool, true);
  2555. } else {
  2556. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  2557. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  2558. }
  2559. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  2560. lbValue data_ptr = lb_emit_conv(p, v, ptr_type);
  2561. lbAddr res = lb_add_local_generated(p, tuple, true);
  2562. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  2563. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  2564. lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type)));
  2565. lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type));
  2566. return lb_addr_load(p, res);
  2567. } else if (is_type_any(t)) {
  2568. lbValue v = e;
  2569. if (is_type_pointer(v.type)) {
  2570. v = lb_emit_load(p, v);
  2571. }
  2572. lbValue data_ptr = lb_emit_conv(p, lb_emit_struct_ev(p, v, 0), ptr_type);
  2573. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  2574. lbValue id = lb_typeid(p->module, type);
  2575. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  2576. lbAddr res = lb_add_local_generated(p, tuple, false);
  2577. lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0);
  2578. lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1);
  2579. lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type)));
  2580. lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type));
  2581. return lb_addr_load(p, res);
  2582. } else {
  2583. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  2584. }
  2585. } else {
  2586. GB_ASSERT(is_type_pointer(tv.type));
  2587. ast_node(ta, TypeAssertion, ue_expr);
  2588. TokenPos pos = ast_token(expr).pos;
  2589. Type *type = type_of_expr(ue_expr);
  2590. GB_ASSERT(!is_type_tuple(type));
  2591. lbValue e = lb_build_expr(p, ta->expr);
  2592. Type *t = type_deref(e.type);
  2593. if (is_type_union(t)) {
  2594. lbValue v = e;
  2595. if (!is_type_pointer(v.type)) {
  2596. v = lb_address_from_load_or_generate_local(p, v);
  2597. }
  2598. Type *src_type = type_deref(v.type);
  2599. Type *dst_type = type;
  2600. if ((p->state_flags & StateFlag_no_type_assert) == 0) {
  2601. lbValue src_tag = {};
  2602. lbValue dst_tag = {};
  2603. if (is_type_union_maybe_pointer(src_type)) {
  2604. src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v);
  2605. dst_tag = lb_const_bool(p->module, t_bool, true);
  2606. } else {
  2607. src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v));
  2608. dst_tag = lb_const_union_tag(p->module, src_type, dst_type);
  2609. }
  2610. isize arg_count = 6;
  2611. if (build_context.no_rtti) {
  2612. arg_count = 4;
  2613. }
  2614. lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag);
  2615. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  2616. args[0] = ok;
  2617. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  2618. args[2] = lb_const_int(p->module, t_i32, pos.line);
  2619. args[3] = lb_const_int(p->module, t_i32, pos.column);
  2620. if (!build_context.no_rtti) {
  2621. args[4] = lb_typeid(p->module, src_type);
  2622. args[5] = lb_typeid(p->module, dst_type);
  2623. }
  2624. lb_emit_runtime_call(p, "type_assertion_check", args);
  2625. }
  2626. lbValue data_ptr = v;
  2627. return lb_emit_conv(p, data_ptr, tv.type);
  2628. } else if (is_type_any(t)) {
  2629. lbValue v = e;
  2630. if (is_type_pointer(v.type)) {
  2631. v = lb_emit_load(p, v);
  2632. }
  2633. lbValue data_ptr = lb_emit_struct_ev(p, v, 0);
  2634. if ((p->state_flags & StateFlag_no_type_assert) == 0) {
  2635. GB_ASSERT(!build_context.no_rtti);
  2636. lbValue any_id = lb_emit_struct_ev(p, v, 1);
  2637. lbValue id = lb_typeid(p->module, type);
  2638. lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id);
  2639. auto args = array_make<lbValue>(permanent_allocator(), 6);
  2640. args[0] = ok;
  2641. args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id));
  2642. args[2] = lb_const_int(p->module, t_i32, pos.line);
  2643. args[3] = lb_const_int(p->module, t_i32, pos.column);
  2644. args[4] = any_id;
  2645. args[5] = id;
  2646. lb_emit_runtime_call(p, "type_assertion_check", args);
  2647. }
  2648. return lb_emit_conv(p, data_ptr, tv.type);
  2649. } else {
  2650. GB_PANIC("TODO(bill): type assertion %s", type_to_string(type));
  2651. }
  2652. }
  2653. }
  2654. return lb_build_addr_ptr(p, ue->expr);
  2655. }
  2656. gb_internal lbValue lb_build_expr_internal(lbProcedure *p, Ast *expr);
  2657. gb_internal lbValue lb_build_expr(lbProcedure *p, Ast *expr) {
  2658. u16 prev_state_flags = p->state_flags;
  2659. defer (p->state_flags = prev_state_flags);
  2660. if (expr->state_flags != 0) {
  2661. u16 in = expr->state_flags;
  2662. u16 out = p->state_flags;
  2663. if (in & StateFlag_bounds_check) {
  2664. out |= StateFlag_bounds_check;
  2665. out &= ~StateFlag_no_bounds_check;
  2666. } else if (in & StateFlag_no_bounds_check) {
  2667. out |= StateFlag_no_bounds_check;
  2668. out &= ~StateFlag_bounds_check;
  2669. }
  2670. if (in & StateFlag_type_assert) {
  2671. out |= StateFlag_type_assert;
  2672. out &= ~StateFlag_no_type_assert;
  2673. } else if (in & StateFlag_no_type_assert) {
  2674. out |= StateFlag_no_type_assert;
  2675. out &= ~StateFlag_type_assert;
  2676. }
  2677. p->state_flags = out;
  2678. }
  2679. // IMPORTANT NOTE(bill):
  2680. // Selector Call Expressions (foo->bar(...))
  2681. // must only evaluate `foo` once as it gets transformed into
  2682. // `foo.bar(foo, ...)`
  2683. // And if `foo` is a procedure call or something more complex, storing the value
  2684. // once is a very good idea
  2685. // If a stored value is found, it must be removed from the cache
  2686. if (expr->state_flags & StateFlag_SelectorCallExpr) {
  2687. lbValue *pp = map_get(&p->selector_values, expr);
  2688. if (pp != nullptr) {
  2689. lbValue res = *pp;
  2690. map_remove(&p->selector_values, expr);
  2691. return res;
  2692. }
  2693. lbAddr *pa = map_get(&p->selector_addr, expr);
  2694. if (pa != nullptr) {
  2695. lbAddr res = *pa;
  2696. map_remove(&p->selector_addr, expr);
  2697. return lb_addr_load(p, res);
  2698. }
  2699. }
  2700. lbValue res = lb_build_expr_internal(p, expr);
  2701. if (expr->state_flags & StateFlag_SelectorCallExpr) {
  2702. map_set(&p->selector_values, expr, res);
  2703. }
  2704. return res;
  2705. }
  2706. gb_internal lbValue lb_build_expr_internal(lbProcedure *p, Ast *expr) {
  2707. lbModule *m = p->module;
  2708. expr = unparen_expr(expr);
  2709. TokenPos expr_pos = ast_token(expr).pos;
  2710. TypeAndValue tv = type_and_value_of_expr(expr);
  2711. Type *type = type_of_expr(expr);
  2712. 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));
  2713. if (tv.value.kind != ExactValue_Invalid) {
  2714. // NOTE(bill): The commented out code below is just for debug purposes only
  2715. // if (is_type_untyped(type)) {
  2716. // 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);
  2717. // GB_PANIC("%s\n", type_to_string(tv.type));
  2718. // }
  2719. // NOTE(bill): Short on constant values
  2720. return lb_const_value(p->module, type, tv.value);
  2721. } else if (tv.mode == Addressing_Type) {
  2722. // NOTE(bill, 2023-01-16): is this correct? I hope so at least
  2723. return lb_typeid(m, tv.type);
  2724. }
  2725. switch (expr->kind) {
  2726. case_ast_node(bl, BasicLit, expr);
  2727. TokenPos pos = bl->token.pos;
  2728. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind]));
  2729. case_end;
  2730. case_ast_node(bd, BasicDirective, expr);
  2731. TokenPos pos = bd->token.pos;
  2732. GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name.string));
  2733. case_end;
  2734. case_ast_node(i, Implicit, expr);
  2735. return lb_addr_load(p, lb_build_addr(p, expr));
  2736. case_end;
  2737. case_ast_node(u, Uninit, expr)
  2738. lbValue res = {};
  2739. if (is_type_untyped(type)) {
  2740. res.value = nullptr;
  2741. res.type = t_untyped_uninit;
  2742. } else {
  2743. res.value = LLVMGetUndef(lb_type(m, type));
  2744. res.type = type;
  2745. }
  2746. return res;
  2747. case_end;
  2748. case_ast_node(i, Ident, expr);
  2749. Entity *e = entity_from_expr(expr);
  2750. e = strip_entity_wrapping(e);
  2751. GB_ASSERT_MSG(e != nullptr, "%s in %.*s %p", expr_to_string(expr), LIT(p->name), expr);
  2752. if (e->kind == Entity_Builtin) {
  2753. Token token = ast_token(expr);
  2754. GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n"
  2755. "\t at %s", LIT(builtin_procs[e->Builtin.id].name),
  2756. token_pos_to_string(token.pos));
  2757. return {};
  2758. } else if (e->kind == Entity_Nil) {
  2759. lbValue res = {};
  2760. res.value = nullptr;
  2761. res.type = e->type;
  2762. return res;
  2763. }
  2764. GB_ASSERT(e->kind != Entity_ProcGroup);
  2765. return lb_find_ident(p, m, e, expr);
  2766. case_end;
  2767. case_ast_node(de, DerefExpr, expr);
  2768. return lb_addr_load(p, lb_build_addr(p, expr));
  2769. case_end;
  2770. case_ast_node(se, SelectorExpr, expr);
  2771. TypeAndValue tav = type_and_value_of_expr(expr);
  2772. GB_ASSERT(tav.mode != Addressing_Invalid);
  2773. return lb_addr_load(p, lb_build_addr(p, expr));
  2774. case_end;
  2775. case_ast_node(ise, ImplicitSelectorExpr, expr);
  2776. TypeAndValue tav = type_and_value_of_expr(expr);
  2777. GB_ASSERT(tav.mode == Addressing_Constant);
  2778. return lb_const_value(p->module, type, tv.value);
  2779. case_end;
  2780. case_ast_node(se, SelectorCallExpr, expr);
  2781. GB_ASSERT(se->modified_call);
  2782. return lb_build_call_expr(p, se->call);
  2783. case_end;
  2784. case_ast_node(te, TernaryIfExpr, expr);
  2785. LLVMValueRef incoming_values[2] = {};
  2786. LLVMBasicBlockRef incoming_blocks[2] = {};
  2787. GB_ASSERT(te->y != nullptr);
  2788. lbBlock *then = lb_create_block(p, "if.then");
  2789. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  2790. lbBlock *else_ = lb_create_block(p, "if.else");
  2791. lb_build_cond(p, te->cond, then, else_);
  2792. lb_start_block(p, then);
  2793. Type *type = default_type(type_of_expr(expr));
  2794. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2795. incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value;
  2796. if (is_type_internally_pointer_like(type)) {
  2797. incoming_values[0] = LLVMBuildBitCast(p->builder, incoming_values[0], llvm_type, "");
  2798. }
  2799. lb_emit_jump(p, done);
  2800. lb_start_block(p, else_);
  2801. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value;
  2802. if (is_type_internally_pointer_like(type)) {
  2803. incoming_values[1] = LLVMBuildBitCast(p->builder, incoming_values[1], llvm_type, "");
  2804. }
  2805. lb_emit_jump(p, done);
  2806. lb_start_block(p, done);
  2807. lbValue res = {};
  2808. res.value = LLVMBuildPhi(p->builder, llvm_type, "");
  2809. res.type = type;
  2810. GB_ASSERT(p->curr_block->preds.count >= 2);
  2811. incoming_blocks[0] = p->curr_block->preds[0]->block;
  2812. incoming_blocks[1] = p->curr_block->preds[1]->block;
  2813. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  2814. return res;
  2815. case_end;
  2816. case_ast_node(te, TernaryWhenExpr, expr);
  2817. TypeAndValue tav = type_and_value_of_expr(te->cond);
  2818. GB_ASSERT(tav.mode == Addressing_Constant);
  2819. GB_ASSERT(tav.value.kind == ExactValue_Bool);
  2820. if (tav.value.value_bool) {
  2821. return lb_build_expr(p, te->x);
  2822. } else {
  2823. return lb_build_expr(p, te->y);
  2824. }
  2825. case_end;
  2826. case_ast_node(oe, OrElseExpr, expr);
  2827. return lb_emit_or_else(p, oe->x, oe->y, tv);
  2828. case_end;
  2829. case_ast_node(oe, OrReturnExpr, expr);
  2830. return lb_emit_or_return(p, oe->expr, tv);
  2831. case_end;
  2832. case_ast_node(be, OrBranchExpr, expr);
  2833. lbBlock *block = nullptr;
  2834. if (be->label != nullptr) {
  2835. lbBranchBlocks bb = lb_lookup_branch_blocks(p, be->label);
  2836. switch (be->token.kind) {
  2837. case Token_or_break: block = bb.break_; break;
  2838. case Token_or_continue: block = bb.continue_; break;
  2839. }
  2840. } else {
  2841. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  2842. if (t->is_block) {
  2843. continue;
  2844. }
  2845. switch (be->token.kind) {
  2846. case Token_or_break: block = t->break_; break;
  2847. case Token_or_continue: block = t->continue_; break;
  2848. }
  2849. }
  2850. }
  2851. GB_ASSERT(block != nullptr);
  2852. lbValue lhs = {};
  2853. lbValue rhs = {};
  2854. lb_emit_try_lhs_rhs(p, be->expr, tv, &lhs, &rhs);
  2855. Type *type = default_type(tv.type);
  2856. if (lhs.value) {
  2857. lhs = lb_emit_conv(p, lhs, type);
  2858. } else if (type != nullptr && type != t_invalid) {
  2859. lhs = lb_const_nil(p->module, type);
  2860. }
  2861. lbBlock *then = lb_create_block(p, "or_branch.then");
  2862. lbBlock *else_ = lb_create_block(p, "or_branch.else");
  2863. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  2864. lb_start_block(p, else_);
  2865. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  2866. lb_emit_jump(p, block);
  2867. lb_start_block(p, then);
  2868. return lhs;
  2869. case_end;
  2870. case_ast_node(ta, TypeAssertion, expr);
  2871. TokenPos pos = ast_token(expr).pos;
  2872. lbValue e = lb_build_expr(p, ta->expr);
  2873. Type *t = type_deref(e.type);
  2874. if (is_type_union(t)) {
  2875. if (ta->ignores[0]) {
  2876. // NOTE(bill): This is not needed for optimization levels other than 0
  2877. return lb_emit_union_cast_only_ok_check(p, e, type, pos);
  2878. }
  2879. return lb_emit_union_cast(p, e, type, pos);
  2880. } else if (is_type_any(t)) {
  2881. return lb_emit_any_cast(p, e, type, pos);
  2882. } else {
  2883. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  2884. }
  2885. case_end;
  2886. case_ast_node(tc, TypeCast, expr);
  2887. lbValue e = lb_build_expr(p, tc->expr);
  2888. switch (tc->token.kind) {
  2889. case Token_cast:
  2890. return lb_emit_conv(p, e, type);
  2891. case Token_transmute:
  2892. return lb_emit_transmute(p, e, type);
  2893. }
  2894. GB_PANIC("Invalid AST TypeCast");
  2895. case_end;
  2896. case_ast_node(ac, AutoCast, expr);
  2897. lbValue value = lb_build_expr(p, ac->expr);
  2898. return lb_emit_conv(p, value, type);
  2899. case_end;
  2900. case_ast_node(ue, UnaryExpr, expr);
  2901. switch (ue->op.kind) {
  2902. case Token_And:
  2903. return lb_build_unary_and(p, expr);
  2904. default:
  2905. {
  2906. lbValue v = lb_build_expr(p, ue->expr);
  2907. return lb_emit_unary_arith(p, ue->op.kind, v, type);
  2908. }
  2909. }
  2910. case_end;
  2911. case_ast_node(be, BinaryExpr, expr);
  2912. return lb_build_binary_expr(p, expr);
  2913. case_end;
  2914. case_ast_node(pl, ProcLit, expr);
  2915. return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p);
  2916. case_end;
  2917. case_ast_node(cl, CompoundLit, expr);
  2918. return lb_addr_load(p, lb_build_addr(p, expr));
  2919. case_end;
  2920. case_ast_node(ce, CallExpr, expr);
  2921. return lb_build_call_expr(p, expr);
  2922. case_end;
  2923. case_ast_node(se, SliceExpr, expr);
  2924. if (is_type_slice(type_of_expr(se->expr))) {
  2925. // NOTE(bill): Quick optimization
  2926. if (se->high == nullptr &&
  2927. (se->low == nullptr || lb_is_expr_constant_zero(se->low))) {
  2928. return lb_build_expr(p, se->expr);
  2929. }
  2930. }
  2931. return lb_addr_load(p, lb_build_addr(p, expr));
  2932. case_end;
  2933. case_ast_node(ie, IndexExpr, expr);
  2934. return lb_addr_load(p, lb_build_addr(p, expr));
  2935. case_end;
  2936. case_ast_node(ie, MatrixIndexExpr, expr);
  2937. return lb_addr_load(p, lb_build_addr(p, expr));
  2938. case_end;
  2939. case_ast_node(ia, InlineAsmExpr, expr);
  2940. Type *t = type_of_expr(expr);
  2941. GB_ASSERT(is_type_asm_proc(t));
  2942. String asm_string = {};
  2943. String constraints_string = {};
  2944. TypeAndValue tav;
  2945. tav = type_and_value_of_expr(ia->asm_string);
  2946. GB_ASSERT(is_type_string(tav.type));
  2947. GB_ASSERT(tav.value.kind == ExactValue_String);
  2948. asm_string = tav.value.value_string;
  2949. tav = type_and_value_of_expr(ia->constraints_string);
  2950. GB_ASSERT(is_type_string(tav.type));
  2951. GB_ASSERT(tav.value.kind == ExactValue_String);
  2952. constraints_string = tav.value.value_string;
  2953. LLVMInlineAsmDialect dialect = LLVMInlineAsmDialectATT;
  2954. switch (ia->dialect) {
  2955. case InlineAsmDialect_Default: dialect = LLVMInlineAsmDialectATT; break;
  2956. case InlineAsmDialect_ATT: dialect = LLVMInlineAsmDialectATT; break;
  2957. case InlineAsmDialect_Intel: dialect = LLVMInlineAsmDialectIntel; break;
  2958. default: GB_PANIC("Unhandled inline asm dialect"); break;
  2959. }
  2960. LLVMTypeRef func_type = lb_type_internal_for_procedures_raw(p->module, t);
  2961. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, asm_string, constraints_string, ia->has_side_effects, ia->has_side_effects, dialect);
  2962. GB_ASSERT(the_asm != nullptr);
  2963. return {the_asm, t};
  2964. case_end;
  2965. }
  2966. GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind]));
  2967. return {};
  2968. }
  2969. gb_internal lbAddr lb_get_soa_variable_addr(lbProcedure *p, Entity *e) {
  2970. return map_must_get(&p->module->soa_values, e);
  2971. }
  2972. gb_internal lbValue lb_get_using_variable(lbProcedure *p, Entity *e) {
  2973. GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using);
  2974. String name = e->token.string;
  2975. Entity *parent = e->using_parent;
  2976. Selection sel = lookup_field(parent->type, name, false);
  2977. GB_ASSERT(sel.entity != nullptr);
  2978. lbValue *pv = map_get(&p->module->values, parent);
  2979. lbValue v = {};
  2980. if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) {
  2981. // NOTE(bill): using SOA value (probably from for-in statement)
  2982. lbAddr parent_addr = lb_get_soa_variable_addr(p, parent);
  2983. v = lb_addr_get_ptr(p, parent_addr);
  2984. } else if (pv != nullptr) {
  2985. v = *pv;
  2986. } else {
  2987. GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name));
  2988. v = lb_build_addr_ptr(p, e->using_expr);
  2989. }
  2990. GB_ASSERT(v.value != nullptr);
  2991. GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type));
  2992. lbValue ptr = lb_emit_deep_field_gep(p, v, sel);
  2993. if (parent->scope) {
  2994. if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) {
  2995. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  2996. }
  2997. } else {
  2998. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  2999. }
  3000. return ptr;
  3001. }
  3002. gb_internal lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) {
  3003. GB_ASSERT(e != nullptr);
  3004. if (e->kind == Entity_Constant) {
  3005. Type *t = default_type(type_of_expr(expr));
  3006. lbValue v = lb_const_value(p->module, t, e->Constant.value);
  3007. if (LLVMIsConstant(v.value)) {
  3008. lbAddr g = lb_add_global_generated(p->module, t, v);
  3009. return g;
  3010. }
  3011. GB_ASSERT(LLVMIsALoadInst(v.value));
  3012. lbValue ptr = {};
  3013. ptr.value = LLVMGetOperand(v.value, 0);
  3014. ptr.type = alloc_type_pointer(t);
  3015. return lb_addr(ptr);
  3016. }
  3017. lbValue v = {};
  3018. lbValue *found = map_get(&p->module->values, e);
  3019. if (found) {
  3020. v = *found;
  3021. } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) {
  3022. // NOTE(bill): Calculate the using variable every time
  3023. v = lb_get_using_variable(p, e);
  3024. } else if (e->flags & EntityFlag_SoaPtrField) {
  3025. return lb_get_soa_variable_addr(p, e);
  3026. }
  3027. if (v.value == nullptr) {
  3028. return lb_addr(lb_find_value_from_entity(p->module, e));
  3029. // error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s",
  3030. // LIT(p->name),
  3031. // LIT(e->token.string), e, LIT(entity_strings[e->kind]));
  3032. // GB_PANIC("Unknown value");
  3033. }
  3034. return lb_addr(v);
  3035. }
  3036. gb_internal lbAddr lb_build_array_swizzle_addr(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  3037. isize index_count = ce->args.count-1;
  3038. lbAddr addr = lb_build_addr(p, ce->args[0]);
  3039. if (index_count == 0) {
  3040. return addr;
  3041. }
  3042. Type *type = base_type(lb_addr_type(addr));
  3043. GB_ASSERT(type->kind == Type_Array);
  3044. i64 count = type->Array.count;
  3045. if (count <= 4) {
  3046. u8 indices[4] = {};
  3047. u8 index_count = 0;
  3048. for (i32 i = 1; i < ce->args.count; i++) {
  3049. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  3050. GB_ASSERT(is_type_integer(tv.type));
  3051. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  3052. i64 src_index = big_int_to_i64(&tv.value.value_integer);
  3053. indices[index_count++] = cast(u8)src_index;
  3054. }
  3055. return lb_addr_swizzle(lb_addr_get_ptr(p, addr), tv.type, index_count, indices);
  3056. }
  3057. auto indices = slice_make<i32>(permanent_allocator(), ce->args.count-1);
  3058. isize index_index = 0;
  3059. for (i32 i = 1; i < ce->args.count; i++) {
  3060. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  3061. GB_ASSERT(is_type_integer(tv.type));
  3062. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  3063. i64 src_index = big_int_to_i64(&tv.value.value_integer);
  3064. indices[index_index++] = cast(i32)src_index;
  3065. }
  3066. return lb_addr_swizzle_large(lb_addr_get_ptr(p, addr), tv.type, indices);
  3067. }
  3068. gb_internal lbAddr lb_build_addr_internal(lbProcedure *p, Ast *expr);
  3069. gb_internal lbAddr lb_build_addr(lbProcedure *p, Ast *expr) {
  3070. expr = unparen_expr(expr);
  3071. // IMPORTANT NOTE(bill):
  3072. // Selector Call Expressions (foo->bar(...))
  3073. // must only evaluate `foo` once as it gets transformed into
  3074. // `foo.bar(foo, ...)`
  3075. // And if `foo` is a procedure call or something more complex, storing the value
  3076. // once is a very good idea
  3077. // If a stored value is found, it must be removed from the cache
  3078. if (expr->state_flags & StateFlag_SelectorCallExpr) {
  3079. lbAddr *pp = map_get(&p->selector_addr, expr);
  3080. if (pp != nullptr) {
  3081. lbAddr res = *pp;
  3082. map_remove(&p->selector_addr, expr);
  3083. return res;
  3084. }
  3085. }
  3086. lbAddr addr = lb_build_addr_internal(p, expr);
  3087. if (expr->state_flags & StateFlag_SelectorCallExpr) {
  3088. map_set(&p->selector_addr, expr, addr);
  3089. }
  3090. return addr;
  3091. }
  3092. gb_internal void lb_build_addr_compound_lit_populate(lbProcedure *p, Slice<Ast *> const &elems, Array<lbCompoundLitElemTempData> *temp_data, Type *compound_type) {
  3093. Type *bt = base_type(compound_type);
  3094. Type *et = nullptr;
  3095. switch (bt->kind) {
  3096. case Type_Array: et = bt->Array.elem; break;
  3097. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  3098. case Type_Slice: et = bt->Slice.elem; break;
  3099. case Type_BitSet: et = bt->BitSet.elem; break;
  3100. case Type_DynamicArray: et = bt->DynamicArray.elem; break;
  3101. case Type_SimdVector: et = bt->SimdVector.elem; break;
  3102. case Type_Matrix: et = bt->Matrix.elem; break;
  3103. }
  3104. GB_ASSERT(et != nullptr);
  3105. // NOTE(bill): Separate value, gep, store into their own chunks
  3106. for_array(i, elems) {
  3107. Ast *elem = elems[i];
  3108. if (elem->kind == Ast_FieldValue) {
  3109. ast_node(fv, FieldValue, elem);
  3110. if (lb_is_elem_const(fv->value, et)) {
  3111. continue;
  3112. }
  3113. if (is_ast_range(fv->field)) {
  3114. ast_node(ie, BinaryExpr, fv->field);
  3115. TypeAndValue lo_tav = ie->left->tav;
  3116. TypeAndValue hi_tav = ie->right->tav;
  3117. GB_ASSERT(lo_tav.mode == Addressing_Constant);
  3118. GB_ASSERT(hi_tav.mode == Addressing_Constant);
  3119. TokenKind op = ie->op.kind;
  3120. i64 lo = exact_value_to_i64(lo_tav.value);
  3121. i64 hi = exact_value_to_i64(hi_tav.value);
  3122. if (op != Token_RangeHalf) {
  3123. hi += 1;
  3124. }
  3125. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  3126. GB_ASSERT((hi-lo) > 0);
  3127. if (bt->kind == Type_Matrix) {
  3128. for (i64 k = lo; k < hi; k++) {
  3129. lbCompoundLitElemTempData data = {};
  3130. data.value = value;
  3131. data.elem_index = matrix_row_major_index_to_offset(bt, k);
  3132. array_add(temp_data, data);
  3133. }
  3134. } else {
  3135. enum {MAX_ELEMENT_AMOUNT = 32};
  3136. if ((hi-lo) <= MAX_ELEMENT_AMOUNT) {
  3137. for (i64 k = lo; k < hi; k++) {
  3138. lbCompoundLitElemTempData data = {};
  3139. data.value = value;
  3140. data.elem_index = k;
  3141. array_add(temp_data, data);
  3142. }
  3143. } else {
  3144. lbCompoundLitElemTempData data = {};
  3145. data.value = value;
  3146. data.elem_index = lo;
  3147. data.elem_length = hi-lo;
  3148. array_add(temp_data, data);
  3149. }
  3150. }
  3151. } else {
  3152. auto tav = fv->field->tav;
  3153. GB_ASSERT(tav.mode == Addressing_Constant);
  3154. i64 index = exact_value_to_i64(tav.value);
  3155. lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et);
  3156. GB_ASSERT(!is_type_tuple(value.type));
  3157. lbCompoundLitElemTempData data = {};
  3158. data.value = value;
  3159. data.expr = fv->value;
  3160. if (bt->kind == Type_Matrix) {
  3161. data.elem_index = matrix_row_major_index_to_offset(bt, index);
  3162. } else {
  3163. data.elem_index = index;
  3164. }
  3165. array_add(temp_data, data);
  3166. }
  3167. } else {
  3168. if (bt->kind != Type_DynamicArray && lb_is_elem_const(elem, et)) {
  3169. continue;
  3170. }
  3171. lbValue field_expr = lb_build_expr(p, elem);
  3172. GB_ASSERT(!is_type_tuple(field_expr.type));
  3173. lbValue ev = lb_emit_conv(p, field_expr, et);
  3174. lbCompoundLitElemTempData data = {};
  3175. data.value = ev;
  3176. if (bt->kind == Type_Matrix) {
  3177. data.elem_index = matrix_row_major_index_to_offset(bt, i);
  3178. } else {
  3179. data.elem_index = i;
  3180. }
  3181. array_add(temp_data, data);
  3182. }
  3183. }
  3184. }
  3185. gb_internal void lb_build_addr_compound_lit_assign_array(lbProcedure *p, Array<lbCompoundLitElemTempData> const &temp_data) {
  3186. for (auto const &td : temp_data) {
  3187. if (td.value.value != nullptr) {
  3188. if (td.elem_length > 0) {
  3189. auto loop_data = lb_loop_start(p, cast(isize)td.elem_length, t_i32);
  3190. {
  3191. lbValue dst = td.gep;
  3192. dst = lb_emit_ptr_offset(p, dst, loop_data.idx);
  3193. lb_emit_store(p, dst, td.value);
  3194. }
  3195. lb_loop_end(p, loop_data);
  3196. } else {
  3197. lb_emit_store(p, td.gep, td.value);
  3198. }
  3199. }
  3200. }
  3201. }
  3202. gb_internal lbAddr lb_build_addr_index_expr(lbProcedure *p, Ast *expr) {
  3203. ast_node(ie, IndexExpr, expr);
  3204. Type *t = base_type(type_of_expr(ie->expr));
  3205. bool deref = is_type_pointer(t);
  3206. t = base_type(type_deref(t));
  3207. if (is_type_soa_struct(t)) {
  3208. // SOA STRUCTURES!!!!
  3209. lbValue val = lb_build_addr_ptr(p, ie->expr);
  3210. if (deref) {
  3211. val = lb_emit_load(p, val);
  3212. }
  3213. lbValue index = lb_build_expr(p, ie->index);
  3214. return lb_addr_soa_variable(val, index, ie->index);
  3215. }
  3216. if (ie->expr->tav.mode == Addressing_SoaVariable) {
  3217. // SOA Structures for slices/dynamic arrays
  3218. GB_ASSERT(is_type_pointer(type_of_expr(ie->expr)));
  3219. lbValue field = lb_build_expr(p, ie->expr);
  3220. lbValue index = lb_build_expr(p, ie->index);
  3221. if (!build_context.no_bounds_check) {
  3222. // TODO HACK(bill): Clean up this hack to get the length for bounds checking
  3223. // GB_ASSERT(LLVMIsALoadInst(field.value));
  3224. // lbValue a = {};
  3225. // a.value = LLVMGetOperand(field.value, 0);
  3226. // a.type = alloc_type_pointer(field.type);
  3227. // irInstr *b = &a->Instr;
  3228. // GB_ASSERT(b->kind == irInstr_StructElementPtr);
  3229. // lbValue base_struct = b->StructElementPtr.address;
  3230. // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct))));
  3231. // lbValue len = ir_soa_struct_len(p, base_struct);
  3232. // lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3233. }
  3234. lbValue val = lb_emit_ptr_offset(p, field, index);
  3235. return lb_addr(val);
  3236. }
  3237. GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr));
  3238. if (is_type_map(t)) {
  3239. lbAddr map_addr = lb_build_addr(p, ie->expr);
  3240. lbValue key = lb_build_expr(p, ie->index);
  3241. key = lb_emit_conv(p, key, t->Map.key);
  3242. Type *result_type = type_of_expr(expr);
  3243. lbValue map_ptr = lb_addr_get_ptr(p, map_addr);
  3244. if (is_type_pointer(type_deref(map_ptr.type))) {
  3245. map_ptr = lb_emit_load(p, map_ptr);
  3246. }
  3247. return lb_addr_map(map_ptr, key, t, result_type);
  3248. }
  3249. switch (t->kind) {
  3250. case Type_Array: {
  3251. lbValue array = {};
  3252. array = lb_build_addr_ptr(p, ie->expr);
  3253. if (deref) {
  3254. array = lb_emit_load(p, array);
  3255. }
  3256. lbValue index = lb_build_expr(p, ie->index);
  3257. index = lb_emit_conv(p, index, t_int);
  3258. lbValue elem = lb_emit_array_ep(p, array, index);
  3259. auto index_tv = type_and_value_of_expr(ie->index);
  3260. if (index_tv.mode != Addressing_Constant) {
  3261. lbValue len = lb_const_int(p->module, t_int, t->Array.count);
  3262. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3263. }
  3264. return lb_addr(elem);
  3265. }
  3266. case Type_EnumeratedArray: {
  3267. lbValue array = {};
  3268. array = lb_build_addr_ptr(p, ie->expr);
  3269. if (deref) {
  3270. array = lb_emit_load(p, array);
  3271. }
  3272. Type *index_type = t->EnumeratedArray.index;
  3273. auto index_tv = type_and_value_of_expr(ie->index);
  3274. lbValue index = {};
  3275. if (compare_exact_values(Token_NotEq, *t->EnumeratedArray.min_value, exact_value_i64(0))) {
  3276. if (index_tv.mode == Addressing_Constant) {
  3277. ExactValue idx = exact_value_sub(index_tv.value, *t->EnumeratedArray.min_value);
  3278. index = lb_const_value(p->module, index_type, idx);
  3279. } else {
  3280. index = lb_emit_arith(p, Token_Sub,
  3281. lb_build_expr(p, ie->index),
  3282. lb_const_value(p->module, index_type, *t->EnumeratedArray.min_value),
  3283. index_type);
  3284. index = lb_emit_conv(p, index, t_int);
  3285. }
  3286. } else {
  3287. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  3288. }
  3289. lbValue elem = lb_emit_array_ep(p, array, index);
  3290. if (index_tv.mode != Addressing_Constant) {
  3291. lbValue len = lb_const_int(p->module, t_int, t->EnumeratedArray.count);
  3292. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3293. }
  3294. return lb_addr(elem);
  3295. }
  3296. case Type_Slice: {
  3297. lbValue slice = {};
  3298. slice = lb_build_expr(p, ie->expr);
  3299. if (deref) {
  3300. slice = lb_emit_load(p, slice);
  3301. }
  3302. lbValue elem = lb_slice_elem(p, slice);
  3303. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  3304. lbValue len = lb_slice_len(p, slice);
  3305. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3306. lbValue v = lb_emit_ptr_offset(p, elem, index);
  3307. return lb_addr(v);
  3308. }
  3309. case Type_MultiPointer: {
  3310. lbValue multi_ptr = {};
  3311. multi_ptr = lb_build_expr(p, ie->expr);
  3312. if (deref) {
  3313. multi_ptr = lb_emit_load(p, multi_ptr);
  3314. }
  3315. lbValue index = lb_build_expr(p, ie->index);
  3316. index = lb_emit_conv(p, index, t_int);
  3317. lbValue v = {};
  3318. LLVMValueRef indices[1] = {index.value};
  3319. v.value = LLVMBuildGEP2(p->builder, lb_type(p->module, t->MultiPointer.elem), multi_ptr.value, indices, 1, "");
  3320. v.type = alloc_type_pointer(t->MultiPointer.elem);
  3321. return lb_addr(v);
  3322. }
  3323. case Type_RelativeMultiPointer: {
  3324. lbAddr rel_ptr_addr = {};
  3325. if (deref) {
  3326. lbValue rel_ptr_ptr = lb_build_expr(p, ie->expr);
  3327. rel_ptr_addr = lb_addr(rel_ptr_ptr);
  3328. } else {
  3329. rel_ptr_addr = lb_build_addr(p, ie->expr);
  3330. }
  3331. lbValue rel_ptr = lb_relative_pointer_to_pointer(p, rel_ptr_addr);
  3332. lbValue index = lb_build_expr(p, ie->index);
  3333. index = lb_emit_conv(p, index, t_int);
  3334. lbValue v = {};
  3335. Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type);
  3336. GB_ASSERT(pointer_type->kind == Type_MultiPointer);
  3337. Type *elem = pointer_type->MultiPointer.elem;
  3338. LLVMValueRef indices[1] = {index.value};
  3339. v.value = LLVMBuildGEP2(p->builder, lb_type(p->module, elem), rel_ptr.value, indices, 1, "");
  3340. v.type = alloc_type_pointer(elem);
  3341. return lb_addr(v);
  3342. }
  3343. case Type_DynamicArray: {
  3344. lbValue dynamic_array = {};
  3345. dynamic_array = lb_build_expr(p, ie->expr);
  3346. if (deref) {
  3347. dynamic_array = lb_emit_load(p, dynamic_array);
  3348. }
  3349. lbValue elem = lb_dynamic_array_elem(p, dynamic_array);
  3350. lbValue len = lb_dynamic_array_len(p, dynamic_array);
  3351. lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  3352. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3353. lbValue v = lb_emit_ptr_offset(p, elem, index);
  3354. return lb_addr(v);
  3355. }
  3356. case Type_Matrix: {
  3357. lbValue matrix = {};
  3358. matrix = lb_build_addr_ptr(p, ie->expr);
  3359. if (deref) {
  3360. matrix = lb_emit_load(p, matrix);
  3361. }
  3362. lbValue index = lb_build_expr(p, ie->index);
  3363. index = lb_emit_conv(p, index, t_int);
  3364. lbValue elem = lb_emit_matrix_ep(p, matrix, lb_const_int(p->module, t_int, 0), index);
  3365. elem = lb_emit_conv(p, elem, alloc_type_pointer(type_of_expr(expr)));
  3366. auto index_tv = type_and_value_of_expr(ie->index);
  3367. if (index_tv.mode != Addressing_Constant) {
  3368. lbValue len = lb_const_int(p->module, t_int, t->Matrix.column_count);
  3369. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3370. }
  3371. return lb_addr(elem);
  3372. }
  3373. case Type_Basic: { // Basic_string
  3374. lbValue str;
  3375. lbValue elem;
  3376. lbValue len;
  3377. lbValue index;
  3378. str = lb_build_expr(p, ie->expr);
  3379. if (deref) {
  3380. str = lb_emit_load(p, str);
  3381. }
  3382. elem = lb_string_elem(p, str);
  3383. len = lb_string_len(p, str);
  3384. index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int);
  3385. lb_emit_bounds_check(p, ast_token(ie->index), index, len);
  3386. return lb_addr(lb_emit_ptr_offset(p, elem, index));
  3387. }
  3388. }
  3389. return {};
  3390. }
  3391. gb_internal lbAddr lb_build_addr_slice_expr(lbProcedure *p, Ast *expr) {
  3392. ast_node(se, SliceExpr, expr);
  3393. lbValue low = lb_const_int(p->module, t_int, 0);
  3394. lbValue high = {};
  3395. if (se->low != nullptr) {
  3396. low = lb_correct_endianness(p, lb_build_expr(p, se->low));
  3397. }
  3398. if (se->high != nullptr) {
  3399. high = lb_correct_endianness(p, lb_build_expr(p, se->high));
  3400. }
  3401. bool no_indices = se->low == nullptr && se->high == nullptr;
  3402. lbAddr addr = lb_build_addr(p, se->expr);
  3403. lbValue base = lb_addr_load(p, addr);
  3404. Type *type = base_type(base.type);
  3405. if (is_type_pointer(type)) {
  3406. type = base_type(type_deref(type));
  3407. addr = lb_addr(base);
  3408. base = lb_addr_load(p, addr);
  3409. }
  3410. switch (type->kind) {
  3411. case Type_Slice: {
  3412. Type *slice_type = type;
  3413. lbValue len = lb_slice_len(p, base);
  3414. if (high.value == nullptr) high = len;
  3415. if (!no_indices) {
  3416. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3417. }
  3418. lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low);
  3419. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3420. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  3421. lb_fill_slice(p, slice, elem, new_len);
  3422. return slice;
  3423. }
  3424. case Type_RelativePointer:
  3425. GB_PANIC("TODO(bill): Type_RelativePointer should be handled above already on the lb_addr_load");
  3426. break;
  3427. case Type_RelativeMultiPointer:
  3428. GB_PANIC("TODO(bill): Type_RelativeMultiPointer should be handled above already on the lb_addr_load");
  3429. break;
  3430. case Type_DynamicArray: {
  3431. Type *elem_type = type->DynamicArray.elem;
  3432. Type *slice_type = alloc_type_slice(elem_type);
  3433. lbValue len = lb_dynamic_array_len(p, base);
  3434. if (high.value == nullptr) high = len;
  3435. if (!no_indices) {
  3436. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3437. }
  3438. lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low);
  3439. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3440. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  3441. lb_fill_slice(p, slice, elem, new_len);
  3442. return slice;
  3443. }
  3444. case Type_MultiPointer: {
  3445. lbAddr res = lb_add_local_generated(p, type_of_expr(expr), false);
  3446. if (se->high == nullptr) {
  3447. lbValue offset = base;
  3448. LLVMValueRef indices[1] = {low.value};
  3449. offset.value = LLVMBuildGEP2(p->builder, lb_type(p->module, offset.type->MultiPointer.elem), offset.value, indices, 1, "");
  3450. lb_addr_store(p, res, offset);
  3451. } else {
  3452. low = lb_emit_conv(p, low, t_int);
  3453. high = lb_emit_conv(p, high, t_int);
  3454. lb_emit_multi_pointer_slice_bounds_check(p, se->open, low, high);
  3455. LLVMValueRef indices[1] = {low.value};
  3456. LLVMValueRef ptr = LLVMBuildGEP2(p->builder, lb_type(p->module, base.type->MultiPointer.elem), base.value, indices, 1, "");
  3457. LLVMValueRef len = LLVMBuildSub(p->builder, high.value, low.value, "");
  3458. LLVMValueRef gep0 = lb_emit_struct_ep(p, res.addr, 0).value;
  3459. LLVMValueRef gep1 = lb_emit_struct_ep(p, res.addr, 1).value;
  3460. LLVMBuildStore(p->builder, ptr, gep0);
  3461. LLVMBuildStore(p->builder, len, gep1);
  3462. }
  3463. return res;
  3464. }
  3465. case Type_Array: {
  3466. Type *slice_type = alloc_type_slice(type->Array.elem);
  3467. lbValue len = lb_const_int(p->module, t_int, type->Array.count);
  3468. if (high.value == nullptr) high = len;
  3469. bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant;
  3470. bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant;
  3471. if (!low_const || !high_const) {
  3472. if (!no_indices) {
  3473. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3474. }
  3475. }
  3476. lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low);
  3477. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3478. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  3479. lb_fill_slice(p, slice, elem, new_len);
  3480. return slice;
  3481. }
  3482. case Type_Basic: {
  3483. GB_ASSERT_MSG(are_types_identical(type, t_string), "got %s", type_to_string(type));
  3484. lbValue len = lb_string_len(p, base);
  3485. if (high.value == nullptr) high = len;
  3486. if (!no_indices) {
  3487. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3488. }
  3489. lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low);
  3490. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3491. lbAddr str = lb_add_local_generated(p, t_string, false);
  3492. lb_fill_string(p, str, elem, new_len);
  3493. return str;
  3494. }
  3495. case Type_Struct:
  3496. if (is_type_soa_struct(type)) {
  3497. lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr));
  3498. if (high.value == nullptr) high = len;
  3499. if (!no_indices) {
  3500. lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr);
  3501. }
  3502. #if 1
  3503. lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true);
  3504. if (type->Struct.soa_kind == StructSoa_Fixed) {
  3505. i32 field_count = cast(i32)type->Struct.fields.count;
  3506. for (i32 i = 0; i < field_count; i++) {
  3507. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  3508. lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i);
  3509. field_src = lb_emit_array_ep(p, field_src, low);
  3510. lb_emit_store(p, field_dst, field_src);
  3511. }
  3512. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  3513. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3514. lb_emit_store(p, len_dst, new_len);
  3515. } else if (type->Struct.soa_kind == StructSoa_Slice) {
  3516. if (no_indices) {
  3517. lb_addr_store(p, dst, base);
  3518. } else {
  3519. i32 field_count = cast(i32)type->Struct.fields.count - 1;
  3520. for (i32 i = 0; i < field_count; i++) {
  3521. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  3522. lbValue field_src = lb_emit_struct_ev(p, base, i);
  3523. field_src = lb_emit_ptr_offset(p, field_src, low);
  3524. lb_emit_store(p, field_dst, field_src);
  3525. }
  3526. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  3527. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3528. lb_emit_store(p, len_dst, new_len);
  3529. }
  3530. } else if (type->Struct.soa_kind == StructSoa_Dynamic) {
  3531. i32 field_count = cast(i32)type->Struct.fields.count - 3;
  3532. for (i32 i = 0; i < field_count; i++) {
  3533. lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i);
  3534. lbValue field_src = lb_emit_struct_ev(p, base, i);
  3535. field_src = lb_emit_ptr_offset(p, field_src, low);
  3536. lb_emit_store(p, field_dst, field_src);
  3537. }
  3538. lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count);
  3539. lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int);
  3540. lb_emit_store(p, len_dst, new_len);
  3541. }
  3542. return dst;
  3543. #endif
  3544. }
  3545. break;
  3546. }
  3547. GB_PANIC("Unknown slicable type");
  3548. return {};
  3549. }
  3550. gb_internal lbAddr lb_build_addr_compound_lit(lbProcedure *p, Ast *expr) {
  3551. ast_node(cl, CompoundLit, expr);
  3552. Type *type = type_of_expr(expr);
  3553. Type *bt = base_type(type);
  3554. lbAddr v = lb_add_local_generated(p, type, true);
  3555. TEMPORARY_ALLOCATOR_GUARD();
  3556. Type *et = nullptr;
  3557. switch (bt->kind) {
  3558. case Type_Array: et = bt->Array.elem; break;
  3559. case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break;
  3560. case Type_Slice: et = bt->Slice.elem; break;
  3561. case Type_BitSet: et = bt->BitSet.elem; break;
  3562. case Type_SimdVector: et = bt->SimdVector.elem; break;
  3563. case Type_Matrix: et = bt->Matrix.elem; break;
  3564. }
  3565. String proc_name = {};
  3566. if (p->entity) {
  3567. proc_name = p->entity->token.string;
  3568. }
  3569. TokenPos pos = ast_token(expr).pos;
  3570. switch (bt->kind) {
  3571. default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break;
  3572. case Type_Struct: {
  3573. // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment.
  3574. // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR
  3575. bool is_raw_union = is_type_raw_union(bt);
  3576. GB_ASSERT(is_type_struct(bt) || is_raw_union);
  3577. TypeStruct *st = &bt->Struct;
  3578. if (cl->elems.count > 0) {
  3579. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3580. lbValue comp_lit_ptr = lb_addr_get_ptr(p, v);
  3581. for_array(field_index, cl->elems) {
  3582. Ast *elem = cl->elems[field_index];
  3583. lbValue field_expr = {};
  3584. Entity *field = nullptr;
  3585. isize index = field_index;
  3586. if (elem->kind == Ast_FieldValue) {
  3587. ast_node(fv, FieldValue, elem);
  3588. String name = fv->field->Ident.token.string;
  3589. Selection sel = lookup_field(bt, name, false);
  3590. GB_ASSERT(!sel.indirect);
  3591. elem = fv->value;
  3592. if (sel.index.count > 1) {
  3593. if (lb_is_nested_possibly_constant(type, sel, elem)) {
  3594. continue;
  3595. }
  3596. lbValue dst = lb_emit_deep_field_gep(p, comp_lit_ptr, sel);
  3597. field_expr = lb_build_expr(p, elem);
  3598. field_expr = lb_emit_conv(p, field_expr, sel.entity->type);
  3599. lb_emit_store(p, dst, field_expr);
  3600. continue;
  3601. }
  3602. index = sel.index[0];
  3603. } else {
  3604. Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_index);
  3605. GB_ASSERT(sel.index.count == 1);
  3606. GB_ASSERT(!sel.indirect);
  3607. index = sel.index[0];
  3608. }
  3609. field = st->fields[index];
  3610. Type *ft = field->type;
  3611. if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) {
  3612. continue;
  3613. }
  3614. field_expr = lb_build_expr(p, elem);
  3615. lbValue gep = {};
  3616. if (is_raw_union) {
  3617. gep = lb_emit_conv(p, comp_lit_ptr, alloc_type_pointer(ft));
  3618. } else {
  3619. gep = lb_emit_struct_ep(p, comp_lit_ptr, cast(i32)index);
  3620. }
  3621. Type *fet = field_expr.type;
  3622. GB_ASSERT(fet->kind != Type_Tuple);
  3623. // HACK TODO(bill): THIS IS A MASSIVE HACK!!!!
  3624. if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) {
  3625. GB_ASSERT_MSG(union_variant_index(ft, fet) >= 0, "%s", type_to_string(fet));
  3626. lb_emit_store_union_variant(p, gep, field_expr, fet);
  3627. } else {
  3628. lbValue fv = lb_emit_conv(p, field_expr, ft);
  3629. lb_emit_store(p, gep, fv);
  3630. }
  3631. }
  3632. }
  3633. break;
  3634. }
  3635. case Type_Map: {
  3636. if (cl->elems.count == 0) {
  3637. break;
  3638. }
  3639. GB_ASSERT(!build_context.no_dynamic_literals);
  3640. lbValue err = lb_dynamic_map_reserve(p, v.addr, 2*cl->elems.count, pos);
  3641. gb_unused(err);
  3642. for (Ast *elem : cl->elems) {
  3643. ast_node(fv, FieldValue, elem);
  3644. lbValue key = lb_build_expr(p, fv->field);
  3645. lbValue value = lb_build_expr(p, fv->value);
  3646. lb_internal_dynamic_map_set(p, v.addr, type, key, value, elem);
  3647. }
  3648. break;
  3649. }
  3650. case Type_Array: {
  3651. if (cl->elems.count > 0) {
  3652. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3653. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3654. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3655. lbValue dst_ptr = lb_addr_get_ptr(p, v);
  3656. for_array(i, temp_data) {
  3657. i32 index = cast(i32)(temp_data[i].elem_index);
  3658. temp_data[i].gep = lb_emit_array_epi(p, dst_ptr, index);
  3659. }
  3660. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3661. }
  3662. break;
  3663. }
  3664. case Type_EnumeratedArray: {
  3665. if (cl->elems.count > 0) {
  3666. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3667. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3668. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3669. lbValue dst_ptr = lb_addr_get_ptr(p, v);
  3670. i64 index_offset = exact_value_to_i64(*bt->EnumeratedArray.min_value);
  3671. for_array(i, temp_data) {
  3672. i32 index = cast(i32)(temp_data[i].elem_index - index_offset);
  3673. temp_data[i].gep = lb_emit_array_epi(p, dst_ptr, index);
  3674. }
  3675. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3676. }
  3677. break;
  3678. }
  3679. case Type_Slice: {
  3680. if (cl->elems.count > 0) {
  3681. lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr));
  3682. lbValue data = lb_slice_elem(p, slice);
  3683. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3684. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3685. for_array(i, temp_data) {
  3686. temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index));
  3687. }
  3688. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3689. {
  3690. lbValue count = {};
  3691. count.type = t_int;
  3692. unsigned len_index = lb_convert_struct_index(p->module, type, 1);
  3693. if (lb_is_const(slice)) {
  3694. unsigned indices[1] = {len_index};
  3695. count.value = llvm_const_extract_value(p->module, slice.value, indices, gb_count_of(indices));
  3696. } else {
  3697. count.value = LLVMBuildExtractValue(p->builder, slice.value, len_index, "");
  3698. }
  3699. lb_fill_slice(p, v, data, count);
  3700. }
  3701. }
  3702. break;
  3703. }
  3704. case Type_DynamicArray: {
  3705. if (cl->elems.count == 0) {
  3706. break;
  3707. }
  3708. GB_ASSERT(!build_context.no_dynamic_literals);
  3709. Type *et = bt->DynamicArray.elem;
  3710. lbValue size = lb_const_int(p->module, t_int, type_size_of(et));
  3711. lbValue align = lb_const_int(p->module, t_int, type_align_of(et));
  3712. i64 item_count = gb_max(cl->max_count, cl->elems.count);
  3713. {
  3714. auto args = array_make<lbValue>(temporary_allocator(), 5);
  3715. args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr);
  3716. args[1] = size;
  3717. args[2] = align;
  3718. args[3] = lb_const_int(p->module, t_int, item_count);
  3719. args[4] = lb_emit_source_code_location_as_global(p, proc_name, pos);
  3720. lb_emit_runtime_call(p, "__dynamic_array_reserve", args);
  3721. }
  3722. lbValue items = lb_generate_local_array(p, et, item_count);
  3723. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3724. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3725. for_array(i, temp_data) {
  3726. temp_data[i].gep = lb_emit_array_epi(p, items, temp_data[i].elem_index);
  3727. }
  3728. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3729. {
  3730. auto args = array_make<lbValue>(temporary_allocator(), 6);
  3731. args[0] = lb_emit_conv(p, v.addr, t_rawptr);
  3732. args[1] = size;
  3733. args[2] = align;
  3734. args[3] = lb_emit_conv(p, items, t_rawptr);
  3735. args[4] = lb_const_int(p->module, t_int, item_count);
  3736. args[5] = lb_emit_source_code_location_as_global(p, proc_name, pos);
  3737. lb_emit_runtime_call(p, "__dynamic_array_append", args);
  3738. }
  3739. break;
  3740. }
  3741. case Type_Basic: {
  3742. GB_ASSERT(is_type_any(bt));
  3743. if (cl->elems.count > 0) {
  3744. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3745. String field_names[2] = {
  3746. str_lit("data"),
  3747. str_lit("id"),
  3748. };
  3749. Type *field_types[2] = {
  3750. t_rawptr,
  3751. t_typeid,
  3752. };
  3753. for_array(field_index, cl->elems) {
  3754. Ast *elem = cl->elems[field_index];
  3755. lbValue field_expr = {};
  3756. isize index = field_index;
  3757. if (elem->kind == Ast_FieldValue) {
  3758. ast_node(fv, FieldValue, elem);
  3759. Selection sel = lookup_field(bt, fv->field->Ident.token.string, false);
  3760. index = sel.index[0];
  3761. elem = fv->value;
  3762. } else {
  3763. TypeAndValue tav = type_and_value_of_expr(elem);
  3764. Selection sel = lookup_field(bt, field_names[field_index], false);
  3765. index = sel.index[0];
  3766. }
  3767. field_expr = lb_build_expr(p, elem);
  3768. GB_ASSERT(field_expr.type->kind != Type_Tuple);
  3769. Type *ft = field_types[index];
  3770. lbValue fv = lb_emit_conv(p, field_expr, ft);
  3771. lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index);
  3772. lb_emit_store(p, gep, fv);
  3773. }
  3774. }
  3775. break;
  3776. }
  3777. case Type_BitSet: {
  3778. i64 sz = type_size_of(type);
  3779. if (cl->elems.count > 0 && sz > 0) {
  3780. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3781. lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower));
  3782. for (Ast *elem : cl->elems) {
  3783. GB_ASSERT(elem->kind != Ast_FieldValue);
  3784. if (lb_is_elem_const(elem, et)) {
  3785. continue;
  3786. }
  3787. lbValue expr = lb_build_expr(p, elem);
  3788. GB_ASSERT(expr.type->kind != Type_Tuple);
  3789. Type *it = bit_set_to_int(bt);
  3790. lbValue one = lb_const_value(p->module, it, exact_value_i64(1));
  3791. lbValue e = lb_emit_conv(p, expr, it);
  3792. e = lb_emit_arith(p, Token_Sub, e, lower, it);
  3793. e = lb_emit_arith(p, Token_Shl, one, e, it);
  3794. lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it);
  3795. lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it);
  3796. new_value = lb_emit_transmute(p, new_value, type);
  3797. lb_addr_store(p, v, new_value);
  3798. }
  3799. }
  3800. break;
  3801. }
  3802. case Type_Matrix: {
  3803. if (cl->elems.count > 0) {
  3804. lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr)));
  3805. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3806. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3807. lbValue dst_ptr = lb_addr_get_ptr(p, v);
  3808. for_array(i, temp_data) {
  3809. temp_data[i].gep = lb_emit_array_epi(p, dst_ptr, temp_data[i].elem_index);
  3810. }
  3811. lb_build_addr_compound_lit_assign_array(p, temp_data);
  3812. }
  3813. break;
  3814. }
  3815. case Type_SimdVector: {
  3816. if (cl->elems.count > 0) {
  3817. lbValue vector_value = lb_const_value(p->module, type, exact_value_compound(expr));
  3818. defer (lb_addr_store(p, v, vector_value));
  3819. auto temp_data = array_make<lbCompoundLitElemTempData>(temporary_allocator(), 0, cl->elems.count);
  3820. lb_build_addr_compound_lit_populate(p, cl->elems, &temp_data, type);
  3821. // TODO(bill): reduce the need for individual `insertelement` if a `shufflevector`
  3822. // might be a better option
  3823. for (auto const &td : temp_data) {
  3824. if (td.value.value != nullptr) {
  3825. if (td.elem_length > 0) {
  3826. for (i64 k = 0; k < td.elem_length; k++) {
  3827. LLVMValueRef index = lb_const_int(p->module, t_u32, td.elem_index + k).value;
  3828. vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, "");
  3829. }
  3830. } else {
  3831. LLVMValueRef index = lb_const_int(p->module, t_u32, td.elem_index).value;
  3832. vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, "");
  3833. }
  3834. }
  3835. }
  3836. }
  3837. break;
  3838. }
  3839. }
  3840. return v;
  3841. }
  3842. gb_internal lbAddr lb_build_addr_internal(lbProcedure *p, Ast *expr) {
  3843. switch (expr->kind) {
  3844. case_ast_node(i, Implicit, expr);
  3845. lbAddr v = {};
  3846. switch (i->kind) {
  3847. case Token_context:
  3848. v = lb_find_or_generate_context_ptr(p);
  3849. break;
  3850. }
  3851. GB_ASSERT(v.addr.value != nullptr);
  3852. return v;
  3853. case_end;
  3854. case_ast_node(i, Ident, expr);
  3855. if (is_blank_ident(expr)) {
  3856. lbAddr val = {};
  3857. return val;
  3858. }
  3859. String name = i->token.string;
  3860. Entity *e = entity_of_node(expr);
  3861. return lb_build_addr_from_entity(p, e, expr);
  3862. case_end;
  3863. case_ast_node(se, SelectorExpr, expr);
  3864. Ast *sel_node = unparen_expr(se->selector);
  3865. if (sel_node->kind == Ast_Ident) {
  3866. String selector = sel_node->Ident.token.string;
  3867. TypeAndValue tav = type_and_value_of_expr(se->expr);
  3868. if (tav.mode == Addressing_Invalid) {
  3869. // NOTE(bill): Imports
  3870. Entity *imp = entity_of_node(se->expr);
  3871. if (imp != nullptr) {
  3872. GB_ASSERT(imp->kind == Entity_ImportName);
  3873. }
  3874. return lb_build_addr(p, unparen_expr(se->selector));
  3875. }
  3876. Type *type = base_type(tav.type);
  3877. if (tav.mode == Addressing_Type) { // Addressing_Type
  3878. Selection sel = lookup_field(tav.type, selector, true);
  3879. if (sel.pseudo_field) {
  3880. GB_ASSERT(sel.entity->kind == Entity_Procedure);
  3881. return lb_addr(lb_find_value_from_entity(p->module, sel.entity));
  3882. }
  3883. GB_PANIC("Unreachable %.*s", LIT(selector));
  3884. }
  3885. if (se->swizzle_count > 0) {
  3886. Type *array_type = base_type(type_deref(tav.type));
  3887. GB_ASSERT(array_type->kind == Type_Array);
  3888. u8 swizzle_count = se->swizzle_count;
  3889. u8 swizzle_indices_raw = se->swizzle_indices;
  3890. u8 swizzle_indices[4] = {};
  3891. for (u8 i = 0; i < swizzle_count; i++) {
  3892. u8 index = swizzle_indices_raw>>(i*2) & 3;
  3893. swizzle_indices[i] = index;
  3894. }
  3895. lbValue a = {};
  3896. if (is_type_pointer(tav.type)) {
  3897. a = lb_build_expr(p, se->expr);
  3898. } else {
  3899. lbAddr addr = lb_build_addr(p, se->expr);
  3900. a = lb_addr_get_ptr(p, addr);
  3901. }
  3902. GB_ASSERT(is_type_array(expr->tav.type));
  3903. return lb_addr_swizzle(a, expr->tav.type, swizzle_count, swizzle_indices);
  3904. }
  3905. Selection sel = lookup_field(type, selector, false);
  3906. GB_ASSERT(sel.entity != nullptr);
  3907. if (sel.pseudo_field) {
  3908. GB_ASSERT(sel.entity->kind == Entity_Procedure || sel.entity->kind == Entity_ProcGroup);
  3909. Entity *e = entity_of_node(sel_node);
  3910. GB_ASSERT(e->kind == Entity_Procedure);
  3911. return lb_addr(lb_find_value_from_entity(p->module, e));
  3912. }
  3913. {
  3914. lbAddr addr = lb_build_addr(p, se->expr);
  3915. if (addr.kind == lbAddr_Map) {
  3916. lbValue v = lb_addr_load(p, addr);
  3917. lbValue a = lb_address_from_load_or_generate_local(p, v);
  3918. a = lb_emit_deep_field_gep(p, a, sel);
  3919. return lb_addr(a);
  3920. } else if (addr.kind == lbAddr_Context) {
  3921. GB_ASSERT(sel.index.count > 0);
  3922. if (addr.ctx.sel.index.count >= 0) {
  3923. sel = selection_combine(addr.ctx.sel, sel);
  3924. }
  3925. addr.ctx.sel = sel;
  3926. addr.kind = lbAddr_Context;
  3927. return addr;
  3928. } else if (addr.kind == lbAddr_SoaVariable) {
  3929. lbValue index = addr.soa.index;
  3930. i32 first_index = sel.index[0];
  3931. Selection sub_sel = sel;
  3932. sub_sel.index.data += 1;
  3933. sub_sel.index.count -= 1;
  3934. lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index);
  3935. Type *t = base_type(type_deref(addr.addr.type));
  3936. GB_ASSERT(is_type_soa_struct(t));
  3937. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  3938. lbValue len = lb_soa_struct_len(p, addr.addr);
  3939. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  3940. }
  3941. lbValue item = {};
  3942. if (t->Struct.soa_kind == StructSoa_Fixed) {
  3943. item = lb_emit_array_ep(p, arr, index);
  3944. } else {
  3945. item = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  3946. }
  3947. if (sub_sel.index.count > 0) {
  3948. item = lb_emit_deep_field_gep(p, item, sub_sel);
  3949. }
  3950. return lb_addr(item);
  3951. } else if (addr.kind == lbAddr_Swizzle) {
  3952. GB_ASSERT(sel.index.count > 0);
  3953. // NOTE(bill): just patch the index in place
  3954. sel.index[0] = addr.swizzle.indices[sel.index[0]];
  3955. } else if (addr.kind == lbAddr_SwizzleLarge) {
  3956. GB_ASSERT(sel.index.count > 0);
  3957. // NOTE(bill): just patch the index in place
  3958. sel.index[0] = addr.swizzle.indices[sel.index[0]];
  3959. }
  3960. lbValue a = lb_addr_get_ptr(p, addr);
  3961. a = lb_emit_deep_field_gep(p, a, sel);
  3962. return lb_addr(a);
  3963. }
  3964. } else {
  3965. GB_PANIC("Unsupported selector expression");
  3966. }
  3967. case_end;
  3968. case_ast_node(se, SelectorCallExpr, expr);
  3969. lbValue e = lb_build_expr(p, expr);
  3970. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  3971. case_end;
  3972. case_ast_node(ta, TypeAssertion, expr);
  3973. TokenPos pos = ast_token(expr).pos;
  3974. lbValue e = lb_build_expr(p, ta->expr);
  3975. Type *t = type_deref(e.type);
  3976. if (is_type_union(t)) {
  3977. Type *type = type_of_expr(expr);
  3978. lbAddr v = lb_add_local_generated(p, type, false);
  3979. lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos));
  3980. return v;
  3981. } else if (is_type_any(t)) {
  3982. Type *type = type_of_expr(expr);
  3983. return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos);
  3984. } else {
  3985. GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type));
  3986. }
  3987. case_end;
  3988. case_ast_node(ue, UnaryExpr, expr);
  3989. switch (ue->op.kind) {
  3990. case Token_And: {
  3991. lbValue ptr = lb_build_expr(p, expr);
  3992. return lb_addr(lb_address_from_load_or_generate_local(p, ptr));
  3993. }
  3994. default:
  3995. GB_PANIC("Invalid unary expression for lb_build_addr");
  3996. }
  3997. case_end;
  3998. case_ast_node(be, BinaryExpr, expr);
  3999. lbValue v = lb_build_expr(p, expr);
  4000. Type *t = v.type;
  4001. if (is_type_pointer(t)) {
  4002. return lb_addr(v);
  4003. }
  4004. return lb_addr(lb_address_from_load_or_generate_local(p, v));
  4005. case_end;
  4006. case_ast_node(ie, IndexExpr, expr);
  4007. return lb_build_addr_index_expr(p, expr);
  4008. case_end;
  4009. case_ast_node(ie, MatrixIndexExpr, expr);
  4010. Type *t = base_type(type_of_expr(ie->expr));
  4011. bool deref = is_type_pointer(t);
  4012. t = base_type(type_deref(t));
  4013. lbValue m = {};
  4014. m = lb_build_addr_ptr(p, ie->expr);
  4015. if (deref) {
  4016. m = lb_emit_load(p, m);
  4017. }
  4018. lbValue row_index = lb_build_expr(p, ie->row_index);
  4019. lbValue column_index = lb_build_expr(p, ie->column_index);
  4020. row_index = lb_emit_conv(p, row_index, t_int);
  4021. column_index = lb_emit_conv(p, column_index, t_int);
  4022. lbValue elem = lb_emit_matrix_ep(p, m, row_index, column_index);
  4023. auto row_index_tv = type_and_value_of_expr(ie->row_index);
  4024. auto column_index_tv = type_and_value_of_expr(ie->column_index);
  4025. if (row_index_tv.mode != Addressing_Constant || column_index_tv.mode != Addressing_Constant) {
  4026. lbValue row_count = lb_const_int(p->module, t_int, t->Matrix.row_count);
  4027. lbValue column_count = lb_const_int(p->module, t_int, t->Matrix.column_count);
  4028. lb_emit_matrix_bounds_check(p, ast_token(ie->row_index), row_index, column_index, row_count, column_count);
  4029. }
  4030. return lb_addr(elem);
  4031. case_end;
  4032. case_ast_node(se, SliceExpr, expr);
  4033. return lb_build_addr_slice_expr(p, expr);
  4034. case_end;
  4035. case_ast_node(de, DerefExpr, expr);
  4036. Type *t = type_of_expr(de->expr);
  4037. if (is_type_relative_pointer(t)) {
  4038. lbAddr addr = lb_build_addr(p, de->expr);
  4039. addr.relative.deref = true;
  4040. return addr;
  4041. } else if (is_type_soa_pointer(t)) {
  4042. lbValue value = lb_build_expr(p, de->expr);
  4043. lbValue ptr = lb_emit_struct_ev(p, value, 0);
  4044. lbValue idx = lb_emit_struct_ev(p, value, 1);
  4045. return lb_addr_soa_variable(ptr, idx, nullptr);
  4046. }
  4047. lbValue addr = lb_build_expr(p, de->expr);
  4048. return lb_addr(addr);
  4049. case_end;
  4050. case_ast_node(ce, CallExpr, expr);
  4051. BuiltinProcId builtin_id = BuiltinProc_Invalid;
  4052. if (ce->proc->tav.mode == Addressing_Builtin) {
  4053. Entity *e = entity_of_node(ce->proc);
  4054. if (e != nullptr) {
  4055. builtin_id = cast(BuiltinProcId)e->Builtin.id;
  4056. } else {
  4057. builtin_id = BuiltinProc_DIRECTIVE;
  4058. }
  4059. }
  4060. auto const &tv = expr->tav;
  4061. if (builtin_id == BuiltinProc_swizzle &&
  4062. is_type_array(tv.type)) {
  4063. // NOTE(bill, 2021-08-09): `swizzle` has some bizarre semantics so it needs to be
  4064. // specialized here for to be addressable
  4065. return lb_build_array_swizzle_addr(p, ce, tv);
  4066. }
  4067. // NOTE(bill): This is make sure you never need to have an 'array_ev'
  4068. lbValue e = lb_build_expr(p, expr);
  4069. #if 1
  4070. return lb_addr(lb_address_from_load_or_generate_local(p, e));
  4071. #else
  4072. lbAddr v = lb_add_local_generated(p, e.type, false);
  4073. lb_addr_store(p, v, e);
  4074. return v;
  4075. #endif
  4076. case_end;
  4077. case_ast_node(cl, CompoundLit, expr);
  4078. return lb_build_addr_compound_lit(p, expr);
  4079. case_end;
  4080. case_ast_node(tc, TypeCast, expr);
  4081. Type *type = type_of_expr(expr);
  4082. lbValue x = lb_build_expr(p, tc->expr);
  4083. lbValue e = {};
  4084. switch (tc->token.kind) {
  4085. case Token_cast:
  4086. e = lb_emit_conv(p, x, type);
  4087. break;
  4088. case Token_transmute:
  4089. e = lb_emit_transmute(p, x, type);
  4090. break;
  4091. default:
  4092. GB_PANIC("Invalid AST TypeCast");
  4093. }
  4094. lbAddr v = lb_add_local_generated(p, type, false);
  4095. lb_addr_store(p, v, e);
  4096. return v;
  4097. case_end;
  4098. case_ast_node(ac, AutoCast, expr);
  4099. return lb_build_addr(p, ac->expr);
  4100. case_end;
  4101. case_ast_node(te, TernaryIfExpr, expr);
  4102. LLVMValueRef incoming_values[2] = {};
  4103. LLVMBasicBlockRef incoming_blocks[2] = {};
  4104. GB_ASSERT(te->y != nullptr);
  4105. lbBlock *then = lb_create_block(p, "if.then");
  4106. lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later
  4107. lbBlock *else_ = lb_create_block(p, "if.else");
  4108. lb_build_cond(p, te->cond, then, else_);
  4109. lb_start_block(p, then);
  4110. Type *ptr_type = alloc_type_pointer(default_type(type_of_expr(expr)));
  4111. incoming_values[0] = lb_emit_conv(p, lb_build_addr_ptr(p, te->x), ptr_type).value;
  4112. lb_emit_jump(p, done);
  4113. lb_start_block(p, else_);
  4114. incoming_values[1] = lb_emit_conv(p, lb_build_addr_ptr(p, te->y), ptr_type).value;
  4115. lb_emit_jump(p, done);
  4116. lb_start_block(p, done);
  4117. lbValue res = {};
  4118. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, ptr_type), "");
  4119. res.type = ptr_type;
  4120. GB_ASSERT(p->curr_block->preds.count >= 2);
  4121. incoming_blocks[0] = p->curr_block->preds[0]->block;
  4122. incoming_blocks[1] = p->curr_block->preds[1]->block;
  4123. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  4124. return lb_addr(res);
  4125. case_end;
  4126. case_ast_node(oe, OrElseExpr, expr);
  4127. lbValue ptr = lb_address_from_load_or_generate_local(p, lb_build_expr(p, expr));
  4128. return lb_addr(ptr);
  4129. case_end;
  4130. case_ast_node(oe, OrReturnExpr, expr);
  4131. lbValue ptr = lb_address_from_load_or_generate_local(p, lb_build_expr(p, expr));
  4132. return lb_addr(ptr);
  4133. case_end;
  4134. }
  4135. TokenPos token_pos = ast_token(expr).pos;
  4136. GB_PANIC("Unexpected address expression\n"
  4137. "\tAst: %.*s @ "
  4138. "%s\n",
  4139. LIT(ast_strings[expr->kind]),
  4140. token_pos_to_string(token_pos));
  4141. return {};
  4142. }