llvm_backend_proc.cpp 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837
  1. gb_internal LLVMValueRef lb_call_intrinsic(lbProcedure *p, const char *name, LLVMValueRef* args, unsigned arg_count, LLVMTypeRef* types, unsigned type_count) {
  2. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  3. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  4. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, type_count);
  5. LLVMTypeRef call_type = LLVMIntrinsicGetType(p->module->ctx, id, types, type_count);
  6. return LLVMBuildCall2(p->builder, call_type, ip, args, arg_count, "");
  7. }
  8. gb_internal void lb_mem_copy_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  9. dst = lb_emit_conv(p, dst, t_rawptr);
  10. src = lb_emit_conv(p, src, t_rawptr);
  11. len = lb_emit_conv(p, len, t_int);
  12. char const *name = "llvm.memmove";
  13. if (LLVMIsConstant(len.value)) {
  14. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  15. if (const_len <= 4*build_context.int_size) {
  16. name = "llvm.memmove.inline";
  17. }
  18. }
  19. LLVMTypeRef types[3] = {
  20. lb_type(p->module, t_rawptr),
  21. lb_type(p->module, t_rawptr),
  22. lb_type(p->module, t_int)
  23. };
  24. LLVMValueRef args[4] = {
  25. dst.value,
  26. src.value,
  27. len.value,
  28. LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile)
  29. };
  30. lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  31. }
  32. gb_internal void lb_mem_copy_non_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  33. dst = lb_emit_conv(p, dst, t_rawptr);
  34. src = lb_emit_conv(p, src, t_rawptr);
  35. len = lb_emit_conv(p, len, t_int);
  36. char const *name = "llvm.memcpy";
  37. if (LLVMIsConstant(len.value)) {
  38. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  39. if (const_len <= 4*build_context.int_size) {
  40. name = "llvm.memcpy.inline";
  41. }
  42. }
  43. LLVMTypeRef types[3] = {
  44. lb_type(p->module, t_rawptr),
  45. lb_type(p->module, t_rawptr),
  46. lb_type(p->module, t_int)
  47. };
  48. LLVMValueRef args[4] = {
  49. dst.value,
  50. src.value,
  51. len.value,
  52. LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile) };
  53. lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  54. }
  55. gb_internal lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  56. GB_ASSERT(entity != nullptr);
  57. GB_ASSERT(entity->kind == Entity_Procedure);
  58. if (!entity->Procedure.is_foreign) {
  59. if ((entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  60. GB_PANIC("%.*s :: %s (was parapoly: %d %d)", LIT(entity->token.string), type_to_string(entity->type), is_type_polymorphic(entity->type, true), is_type_polymorphic(entity->type, false));
  61. }
  62. }
  63. String link_name = {};
  64. if (ignore_body) {
  65. lbModule *other_module = lb_module_of_entity(m->gen, entity);
  66. link_name = lb_get_entity_name(other_module, entity);
  67. } else {
  68. link_name = lb_get_entity_name(m, entity);
  69. }
  70. {
  71. StringHashKey key = string_hash_string(link_name);
  72. lbValue *found = string_map_get(&m->members, key);
  73. if (found) {
  74. lb_add_entity(m, entity, *found);
  75. return string_map_must_get(&m->procedures, key);
  76. }
  77. }
  78. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  79. p->module = m;
  80. entity->code_gen_module = m;
  81. entity->code_gen_procedure = p;
  82. p->entity = entity;
  83. p->name = link_name;
  84. DeclInfo *decl = entity->decl_info;
  85. ast_node(pl, ProcLit, decl->proc_lit);
  86. Type *pt = base_type(entity->type);
  87. GB_ASSERT(pt->kind == Type_Proc);
  88. p->type = entity->type;
  89. p->type_expr = decl->type_expr;
  90. p->body = pl->body;
  91. p->inlining = pl->inlining;
  92. p->is_foreign = entity->Procedure.is_foreign;
  93. p->is_export = entity->Procedure.is_export;
  94. p->is_entry_point = false;
  95. gbAllocator a = heap_allocator();
  96. p->children.allocator = a;
  97. p->defer_stmts.allocator = a;
  98. p->blocks.allocator = a;
  99. p->branch_blocks.allocator = a;
  100. p->context_stack.allocator = a;
  101. p->scope_stack.allocator = a;
  102. // map_init(&p->selector_values, 0);
  103. // map_init(&p->selector_addr, 0);
  104. // map_init(&p->tuple_fix_map, 0);
  105. if (p->is_foreign) {
  106. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  107. }
  108. LLVMTypeRef func_type = lb_get_procedure_raw_type(m, p->type);
  109. {
  110. TEMPORARY_ALLOCATOR_GUARD();
  111. char *c_link_name = alloc_cstring(temporary_allocator(), p->name);
  112. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  113. }
  114. lb_ensure_abi_function_type(m, p);
  115. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  116. if (pt->Proc.diverging) {
  117. lb_add_attribute_to_proc(m, p->value, "noreturn");
  118. }
  119. if (pt->Proc.calling_convention == ProcCC_Naked) {
  120. lb_add_attribute_to_proc(m, p->value, "naked");
  121. }
  122. if (!entity->Procedure.is_foreign && build_context.disable_red_zone) {
  123. lb_add_attribute_to_proc(m, p->value, "noredzone");
  124. }
  125. switch (p->inlining) {
  126. case ProcInlining_inline:
  127. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  128. break;
  129. case ProcInlining_no_inline:
  130. lb_add_attribute_to_proc(m, p->value, "noinline");
  131. break;
  132. default:
  133. if (build_context.internal_no_inline) {
  134. lb_add_attribute_to_proc(m, p->value, "noinline");
  135. break;
  136. }
  137. }
  138. switch (entity->Procedure.optimization_mode) {
  139. case ProcedureOptimizationMode_None:
  140. lb_add_attribute_to_proc(m, p->value, "optnone");
  141. lb_add_attribute_to_proc(m, p->value, "noinline");
  142. break;
  143. case ProcedureOptimizationMode_FavorSize:
  144. lb_add_attribute_to_proc(m, p->value, "optsize");
  145. break;
  146. }
  147. if (pt->Proc.enable_target_feature.len != 0) {
  148. gbString feature_str = gb_string_make(temporary_allocator(), "");
  149. String_Iterator it = {pt->Proc.enable_target_feature, 0};
  150. bool first = true;
  151. for (;;) {
  152. String str = string_split_iterator(&it, ',');
  153. if (str == "") break;
  154. if (!first) {
  155. feature_str = gb_string_appendc(feature_str, ",");
  156. }
  157. first = false;
  158. feature_str = gb_string_appendc(feature_str, "+");
  159. feature_str = gb_string_append_length(feature_str, str.text, str.len);
  160. }
  161. lb_add_attribute_to_proc_with_string(m, p->value, make_string_c("target-features"), make_string_c(feature_str));
  162. }
  163. if (entity->flags & EntityFlag_Cold) {
  164. lb_add_attribute_to_proc(m, p->value, "cold");
  165. }
  166. if (p->is_export) {
  167. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  168. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  169. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  170. lb_set_wasm_export_attributes(p->value, p->name);
  171. } else if (!p->is_foreign) {
  172. if (USE_SEPARATE_MODULES) {
  173. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  174. } else {
  175. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  176. // NOTE(bill): if a procedure is defined in package runtime and uses a custom link name,
  177. // then it is very likely it is required by LLVM and thus cannot have internal linkage
  178. if (entity->pkg != nullptr && entity->pkg->kind == Package_Runtime && p->body != nullptr) {
  179. GB_ASSERT(entity->kind == Entity_Procedure);
  180. String link_name = entity->Procedure.link_name;
  181. if (entity->flags & EntityFlag_CustomLinkName &&
  182. link_name != "") {
  183. if (string_starts_with(link_name, str_lit("__"))) {
  184. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  185. } else {
  186. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  187. }
  188. }
  189. }
  190. }
  191. }
  192. lb_set_linkage_from_entity_flags(p->module, p->value, entity->flags);
  193. if (p->is_foreign) {
  194. lb_set_wasm_procedure_import_attributes(p->value, entity, p->name);
  195. }
  196. // NOTE(bill): offset==0 is the return value
  197. isize offset = 1;
  198. if (pt->Proc.return_by_pointer) {
  199. offset = 2;
  200. }
  201. isize parameter_index = 0;
  202. if (pt->Proc.param_count) {
  203. TypeTuple *params = &pt->Proc.params->Tuple;
  204. for (isize i = 0; i < pt->Proc.param_count; i++) {
  205. Entity *e = params->variables[i];
  206. if (e->kind != Entity_Variable) {
  207. continue;
  208. }
  209. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  210. continue;
  211. }
  212. if (e->flags&EntityFlag_NoAlias) {
  213. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  214. }
  215. if (e->flags&EntityFlag_NoCapture) {
  216. if (is_type_internally_pointer_like(e->type)) {
  217. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  218. }
  219. }
  220. parameter_index += 1;
  221. }
  222. }
  223. if (ignore_body) {
  224. p->body = nullptr;
  225. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  226. }
  227. if (m->debug_builder) { // Debug Information
  228. Type *bt = base_type(p->type);
  229. unsigned line = cast(unsigned)entity->token.pos.line;
  230. LLVMMetadataRef scope = nullptr;
  231. LLVMMetadataRef file = nullptr;
  232. LLVMMetadataRef type = nullptr;
  233. scope = p->module->debug_compile_unit;
  234. type = lb_debug_type_internal_proc(m, bt);
  235. Ast *ident = entity->identifier.load();
  236. if (entity->file != nullptr) {
  237. file = lb_get_llvm_metadata(m, entity->file);
  238. scope = file;
  239. } else if (ident != nullptr && ident->file_id != 0) {
  240. file = lb_get_llvm_metadata(m, ident->file());
  241. scope = file;
  242. } else if (entity->scope != nullptr) {
  243. file = lb_get_llvm_metadata(m, entity->scope->file);
  244. scope = file;
  245. }
  246. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  247. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  248. LLVMBool is_local_to_unit = false;
  249. LLVMBool is_definition = p->body != nullptr;
  250. unsigned scope_line = line;
  251. u32 flags = LLVMDIFlagStaticMember;
  252. LLVMBool is_optimized = false;
  253. if (bt->Proc.diverging) {
  254. flags |= LLVMDIFlagNoReturn;
  255. }
  256. if (p->body == nullptr) {
  257. flags |= LLVMDIFlagPrototyped;
  258. is_optimized = false;
  259. }
  260. if (p->body != nullptr) {
  261. // String debug_name = entity->token.string.text;
  262. String debug_name = p->name;
  263. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  264. cast(char const *)debug_name.text, debug_name.len,
  265. cast(char const *)p->name.text, p->name.len,
  266. file, line, type,
  267. is_local_to_unit, is_definition,
  268. scope_line, cast(LLVMDIFlags)flags, is_optimized
  269. );
  270. GB_ASSERT(p->debug_info != nullptr);
  271. LLVMSetSubprogram(p->value, p->debug_info);
  272. lb_set_llvm_metadata(m, p, p->debug_info);
  273. }
  274. }
  275. if (p->body && entity->pkg && ((entity->pkg->kind == Package_Normal) || (entity->pkg->kind == Package_Init))) {
  276. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  277. lb_add_attribute_to_proc(m, p->value, "sanitize_address");
  278. }
  279. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  280. lb_add_attribute_to_proc(m, p->value, "sanitize_memory");
  281. }
  282. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  283. lb_add_attribute_to_proc(m, p->value, "sanitize_thread");
  284. }
  285. }
  286. if (p->body && entity->Procedure.has_instrumentation) {
  287. Entity *instrumentation_enter = m->info->instrumentation_enter_entity;
  288. Entity *instrumentation_exit = m->info->instrumentation_exit_entity;
  289. if (instrumentation_enter && instrumentation_exit) {
  290. String enter = lb_get_entity_name(m, instrumentation_enter);
  291. String exit = lb_get_entity_name(m, instrumentation_exit);
  292. lb_add_attribute_to_proc_with_string(m, p->value, make_string_c("instrument-function-entry"), enter);
  293. lb_add_attribute_to_proc_with_string(m, p->value, make_string_c("instrument-function-exit"), exit);
  294. }
  295. }
  296. lbValue proc_value = {p->value, p->type};
  297. lb_add_entity(m, entity, proc_value);
  298. lb_add_member(m, p->name, proc_value);
  299. lb_add_procedure_value(m, p);
  300. return p;
  301. }
  302. gb_internal lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  303. {
  304. lbValue *found = string_map_get(&m->members, link_name);
  305. GB_ASSERT_MSG(found == nullptr, "failed to create dummy procedure for: %.*s", LIT(link_name));
  306. }
  307. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  308. p->module = m;
  309. p->name = link_name;
  310. p->type = type;
  311. p->type_expr = nullptr;
  312. p->body = nullptr;
  313. p->tags = 0;
  314. p->inlining = ProcInlining_none;
  315. p->is_foreign = false;
  316. p->is_export = false;
  317. p->is_entry_point = false;
  318. gbAllocator a = permanent_allocator();
  319. p->children.allocator = a;
  320. p->defer_stmts.allocator = a;
  321. p->blocks.allocator = a;
  322. p->branch_blocks.allocator = a;
  323. p->context_stack.allocator = a;
  324. map_init(&p->tuple_fix_map, 0);
  325. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  326. LLVMTypeRef func_type = lb_get_procedure_raw_type(m, p->type);
  327. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  328. Type *pt = p->type;
  329. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  330. if (!is_arch_wasm()) {
  331. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  332. }
  333. LLVMSetFunctionCallConv(p->value, cc_kind);
  334. lbValue proc_value = {p->value, p->type};
  335. lb_add_member(m, p->name, proc_value);
  336. lb_add_procedure_value(m, p);
  337. // NOTE(bill): offset==0 is the return value
  338. isize offset = 1;
  339. if (pt->Proc.return_by_pointer) {
  340. lb_add_proc_attribute_at_index(p, 1, "sret");
  341. lb_add_proc_attribute_at_index(p, 1, "noalias");
  342. offset = 2;
  343. }
  344. isize parameter_index = 0;
  345. if (pt->Proc.calling_convention == ProcCC_Odin) {
  346. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  347. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  348. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  349. }
  350. return p;
  351. }
  352. // gb_internal lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  353. // lbParamPasskind kind = lbParamPass_Value;
  354. // if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  355. // if (is_type_pointer(abi_type)) {
  356. // GB_ASSERT(e->kind == Entity_Variable);
  357. // Type *av = core_type(type_deref(abi_type));
  358. // if (are_types_identical(av, core_type(e->type))) {
  359. // kind = lbParamPass_Pointer;
  360. // if (e->flags&EntityFlag_Value) {
  361. // kind = lbParamPass_ConstRef;
  362. // }
  363. // } else {
  364. // kind = lbParamPass_BitCast;
  365. // }
  366. // } else if (is_type_integer(abi_type)) {
  367. // kind = lbParamPass_Integer;
  368. // } else if (abi_type == t_llvm_bool) {
  369. // kind = lbParamPass_Value;
  370. // } else if (is_type_boolean(abi_type)) {
  371. // kind = lbParamPass_Integer;
  372. // } else if (is_type_simd_vector(abi_type)) {
  373. // kind = lbParamPass_BitCast;
  374. // } else if (is_type_float(abi_type)) {
  375. // kind = lbParamPass_BitCast;
  376. // } else if (is_type_tuple(abi_type)) {
  377. // kind = lbParamPass_Tuple;
  378. // } else if (is_type_proc(abi_type)) {
  379. // kind = lbParamPass_Value;
  380. // } else {
  381. // GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  382. // }
  383. // }
  384. // if (kind_) *kind_ = kind;
  385. // lbValue res = {};
  386. // res.value = LLVMGetParam(p->value, cast(unsigned)index);
  387. // res.type = abi_type;
  388. // return res;
  389. // }
  390. gb_internal void lb_start_block(lbProcedure *p, lbBlock *b) {
  391. GB_ASSERT(b != nullptr);
  392. if (!b->appended) {
  393. b->appended = true;
  394. LLVMAppendExistingBasicBlock(p->value, b->block);
  395. }
  396. LLVMPositionBuilderAtEnd(p->builder, b->block);
  397. p->curr_block = b;
  398. }
  399. gb_internal void lb_set_debug_position_to_procedure_begin(lbProcedure *p) {
  400. if (p->debug_info == nullptr) {
  401. return;
  402. }
  403. TokenPos pos = {};
  404. if (p->body != nullptr) {
  405. pos = ast_token(p->body).pos;
  406. } else if (p->type_expr != nullptr) {
  407. pos = ast_token(p->type_expr).pos;
  408. } else if (p->entity != nullptr) {
  409. pos = p->entity->token.pos;
  410. }
  411. if (pos.file_id != 0) {
  412. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  413. }
  414. }
  415. gb_internal void lb_set_debug_position_to_procedure_end(lbProcedure *p) {
  416. if (p->debug_info == nullptr) {
  417. return;
  418. }
  419. TokenPos pos = {};
  420. if (p->body != nullptr) {
  421. pos = ast_end_token(p->body).pos;
  422. } else if (p->type_expr != nullptr) {
  423. pos = ast_end_token(p->type_expr).pos;
  424. } else if (p->entity != nullptr) {
  425. pos = p->entity->token.pos;
  426. }
  427. if (pos.file_id != 0) {
  428. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  429. }
  430. }
  431. gb_internal void lb_begin_procedure_body(lbProcedure *p) {
  432. DeclInfo *decl = decl_info_of_entity(p->entity);
  433. if (decl != nullptr) {
  434. for_array(i, decl->labels) {
  435. BlockLabel bl = decl->labels[i];
  436. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  437. array_add(&p->branch_blocks, bb);
  438. }
  439. }
  440. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  441. p->decl_block = lb_create_block(p, "decls", true);
  442. p->entry_block = lb_create_block(p, "entry", true);
  443. lb_start_block(p, p->entry_block);
  444. map_init(&p->direct_parameters);
  445. p->variadic_reuses.allocator = heap_allocator();
  446. GB_ASSERT(p->type != nullptr);
  447. lb_ensure_abi_function_type(p->module, p);
  448. {
  449. lbFunctionType *ft = p->abi_function_type;
  450. unsigned param_offset = 0;
  451. lbValue return_ptr_value = {};
  452. if (ft->ret.kind == lbArg_Indirect) {
  453. // NOTE(bill): this must be parameter 0
  454. String name = str_lit("agg.result");
  455. if (ft->multiple_return_original_type &&
  456. p->type->Proc.has_named_results) {
  457. auto const &variables = p->type->Proc.results->Tuple.variables;
  458. Entity *e = variables[variables.count-1];
  459. if (!is_blank_ident(e->token)) {
  460. name = e->token.string;
  461. }
  462. }
  463. Type *return_ptr_type = reduce_tuple_to_single_type(p->type->Proc.results);
  464. bool split_returns = ft->multiple_return_original_type != nullptr;
  465. if (split_returns) {
  466. GB_ASSERT(is_type_tuple(return_ptr_type));
  467. auto const &variables = return_ptr_type->Tuple.variables;
  468. return_ptr_type = variables[variables.count-1]->type;
  469. }
  470. Type *ptr_type = alloc_type_pointer(return_ptr_type);
  471. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  472. e->flags |= EntityFlag_NoAlias;
  473. return_ptr_value.value = LLVMGetParam(p->value, 0);
  474. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  475. return_ptr_value.type = ptr_type;
  476. p->return_ptr = lb_addr(return_ptr_value);
  477. lb_add_entity(p->module, e, return_ptr_value);
  478. param_offset += 1;
  479. }
  480. if (p->type->Proc.params != nullptr) {
  481. TypeTuple *params = &p->type->Proc.params->Tuple;
  482. unsigned raw_input_parameters_count = LLVMCountParams(p->value);
  483. p->raw_input_parameters = array_make<LLVMValueRef>(permanent_allocator(), raw_input_parameters_count);
  484. LLVMGetParams(p->value, p->raw_input_parameters.data);
  485. unsigned param_index = 0;
  486. for_array(i, params->variables) {
  487. Entity *e = params->variables[i];
  488. if (e->kind != Entity_Variable) {
  489. continue;
  490. }
  491. lbArgType *arg_type = &ft->args[param_index];
  492. defer (param_index += 1);
  493. if (arg_type->kind == lbArg_Ignore) {
  494. // Even though it is an ignored argument, it might still be referenced in the
  495. // body.
  496. lbValue dummy = lb_add_local_generated(p, e->type, false).addr;
  497. lb_add_entity(p->module, e, dummy);
  498. } else if (arg_type->kind == lbArg_Direct) {
  499. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  500. LLVMTypeRef param_type = lb_type(p->module, e->type);
  501. LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index);
  502. LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type);
  503. lbValue param = {};
  504. param.value = value;
  505. param.type = e->type;
  506. map_set(&p->direct_parameters, e, param);
  507. lbValue ptr = lb_address_from_load_or_generate_local(p, param);
  508. GB_ASSERT(LLVMIsAAllocaInst(ptr.value));
  509. lb_add_entity(p->module, e, ptr);
  510. lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->curr_block);
  511. }
  512. } else if (arg_type->kind == lbArg_Indirect) {
  513. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  514. lbValue ptr = {};
  515. ptr.value = LLVMGetParam(p->value, param_offset+param_index);
  516. ptr.type = alloc_type_pointer(e->type);
  517. lb_add_entity(p->module, e, ptr);
  518. lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block);
  519. }
  520. }
  521. }
  522. }
  523. if (p->type->Proc.has_named_results) {
  524. GB_ASSERT(p->type->Proc.result_count > 0);
  525. TypeTuple *results = &p->type->Proc.results->Tuple;
  526. for_array(i, results->variables) {
  527. Entity *e = results->variables[i];
  528. GB_ASSERT(e->kind == Entity_Variable);
  529. if (e->token.string != "") {
  530. GB_ASSERT(!is_blank_ident(e->token));
  531. lbAddr res = {};
  532. if (p->entity && p->entity->decl_info &&
  533. p->entity->decl_info->defer_use_checked &&
  534. p->entity->decl_info->defer_used == 0) {
  535. // NOTE(bill): this is a bodge to get around the issue of the problem BELOW
  536. // We check to see if we ever use a defer statement ever within a procedure and if it
  537. // if it never happens, see if you can possibly do take the return value pointer
  538. //
  539. // NOTE(bill): this could be buggy in that I have missed a case where `defer` was used
  540. //
  541. // TODO(bill): This could be optimized to check to see where a `defer` only uses
  542. // the variable in question
  543. bool has_return_ptr = p->return_ptr.addr.value != nullptr;
  544. lbValue ptr = {};
  545. if (ft->multiple_return_original_type != nullptr) {
  546. isize the_offset = -1;
  547. if (i+1 < results->variables.count) {
  548. the_offset = cast(isize)param_offset + ft->original_arg_count + i;
  549. } else if (has_return_ptr) {
  550. GB_ASSERT(i+1 == results->variables.count);
  551. the_offset = 0;
  552. }
  553. if (the_offset >= 0) {
  554. lbValue ptr = {};
  555. ptr.value = LLVMGetParam(p->value, cast(unsigned)the_offset);
  556. ptr.type = alloc_type_pointer(e->type);
  557. }
  558. } else if (has_return_ptr) {
  559. lbValue ptr = p->return_ptr.addr;
  560. if (results->variables.count > 1) {
  561. ptr = lb_emit_tuple_ep(p, ptr, cast(i32)i);
  562. }
  563. GB_ASSERT(is_type_pointer(ptr.type));
  564. GB_ASSERT(are_types_identical(type_deref(ptr.type), e->type));
  565. }
  566. if (ptr.value != nullptr) {
  567. lb_add_entity(p->module, e, ptr);
  568. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  569. // NOTE(bill): no need to zero on the callee side as it is zeroed on the caller side
  570. res = lb_addr(ptr);
  571. }
  572. }
  573. if (res.addr.type == nullptr) {
  574. // NOTE(bill): Don't even bother trying to optimize this with the return ptr value
  575. // This will violate the defer rules if you do:
  576. // foo :: proc() -> (x, y: T) {
  577. // defer x = ... // defer is executed after the `defer`
  578. // return // the values returned should be zeroed
  579. // }
  580. // NOTE(bill): REALLY, don't even bother.
  581. //
  582. // IMPORTANT NOTE(bill): REALLY, don't even bother!!!!!!
  583. res = lb_add_local(p, e->type, e);
  584. }
  585. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  586. GB_ASSERT(e->Variable.param_value.kind != ParameterValue_Location);
  587. GB_ASSERT(e->Variable.param_value.kind != ParameterValue_Expression);
  588. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, nullptr, nullptr);
  589. lb_addr_store(p, res, c);
  590. }
  591. }
  592. }
  593. }
  594. }
  595. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  596. lb_push_context_onto_stack_from_implicit_parameter(p);
  597. }
  598. lb_set_debug_position_to_procedure_begin(p);
  599. if (p->debug_info != nullptr) {
  600. if (p->context_stack.count != 0) {
  601. lbBlock *prev_block = p->curr_block;
  602. p->curr_block = p->decl_block;
  603. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  604. p->curr_block = prev_block;
  605. }
  606. }
  607. }
  608. gb_internal void lb_end_procedure_body(lbProcedure *p) {
  609. lb_set_debug_position_to_procedure_begin(p);
  610. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  611. LLVMBuildBr(p->builder, p->entry_block->block);
  612. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  613. LLVMValueRef instr = nullptr;
  614. // Make sure there is a "ret void" at the end of a procedure with no return type
  615. if (p->type->Proc.result_count == 0) {
  616. instr = LLVMGetLastInstruction(p->curr_block->block);
  617. if (!lb_is_instr_terminating(instr)) {
  618. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  619. lb_set_debug_position_to_procedure_end(p);
  620. LLVMBuildRetVoid(p->builder);
  621. }
  622. }
  623. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  624. LLVMBasicBlockRef block = nullptr;
  625. // Make sure every block terminates, and if not, make it unreachable
  626. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  627. instr = LLVMGetLastInstruction(block);
  628. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  629. LLVMPositionBuilderAtEnd(p->builder, block);
  630. LLVMBuildUnreachable(p->builder);
  631. }
  632. }
  633. p->curr_block = nullptr;
  634. p->state_flags = 0;
  635. }
  636. gb_internal void lb_end_procedure(lbProcedure *p) {
  637. LLVMDisposeBuilder(p->builder);
  638. }
  639. gb_internal void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  640. GB_ASSERT(pd->body != nullptr);
  641. lbModule *m = p->module;
  642. auto *min_dep_set = &m->info->minimum_dependency_set;
  643. if (ptr_set_exists(min_dep_set, e) == false) {
  644. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  645. return;
  646. }
  647. // NOTE(bill): Generate a new name
  648. // parent.name-guid
  649. String original_name = e->token.string;
  650. String pd_name = original_name;
  651. if (e->Procedure.link_name.len > 0) {
  652. pd_name = e->Procedure.link_name;
  653. }
  654. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  655. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  656. i32 guid = cast(i32)p->children.count;
  657. name_len = gb_snprintf(name_text, name_len, "%.*s" ABI_PKG_NAME_SEPARATOR "%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  658. String name = make_string(cast(u8 *)name_text, name_len-1);
  659. e->Procedure.link_name = name;
  660. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  661. e->code_gen_procedure = nested_proc;
  662. lbValue value = {};
  663. value.value = nested_proc->value;
  664. value.type = nested_proc->type;
  665. lb_add_entity(m, e, value);
  666. array_add(&p->children, nested_proc);
  667. array_add(&m->procedures_to_generate, nested_proc);
  668. }
  669. gb_internal Array<lbValue> lb_value_to_array(lbProcedure *p, gbAllocator const &allocator, lbValue value) {
  670. Array<lbValue> array = {};
  671. Type *t = base_type(value.type);
  672. if (t == nullptr) {
  673. // Do nothing
  674. } else if (is_type_tuple(t)) {
  675. array = array_make<lbValue>(allocator, 0, t->Tuple.variables.count);
  676. lb_append_tuple_values(p, &array, value);
  677. } else {
  678. array = array_make<lbValue>(allocator, 1);
  679. array[0] = value;
  680. }
  681. return array;
  682. }
  683. gb_internal lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array<lbValue> const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) {
  684. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  685. unsigned arg_count = cast(unsigned)processed_args.count;
  686. if (return_ptr.value != nullptr) {
  687. arg_count += 1;
  688. }
  689. if (context_ptr.addr.value != nullptr) {
  690. arg_count += 1;
  691. }
  692. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  693. isize arg_index = 0;
  694. if (return_ptr.value != nullptr) {
  695. args[arg_index++] = return_ptr.value;
  696. }
  697. for_array(i, processed_args) {
  698. lbValue arg = processed_args[i];
  699. if (is_type_proc(arg.type)) {
  700. arg.value = LLVMBuildPointerCast(p->builder, arg.value, lb_type(p->module, arg.type), "");
  701. }
  702. args[arg_index++] = arg.value;
  703. }
  704. if (context_ptr.addr.value != nullptr) {
  705. LLVMValueRef cp = context_ptr.addr.value;
  706. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  707. args[arg_index++] = cp;
  708. }
  709. GB_ASSERT(arg_index == arg_count);
  710. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  711. GB_ASSERT(curr_block != p->decl_block->block);
  712. {
  713. Type *proc_type = base_type(value.type);
  714. GB_ASSERT(proc_type->kind == Type_Proc);
  715. LLVMTypeRef fnp = lb_type_internal_for_procedures_raw(p->module, proc_type);
  716. LLVMTypeRef ftp = LLVMPointerType(fnp, 0);
  717. LLVMValueRef fn = value.value;
  718. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  719. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  720. }
  721. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  722. lbFunctionType *ft = map_must_get(&p->module->function_type_map, base_type(value.type));
  723. {
  724. unsigned param_count = LLVMCountParamTypes(fnp);
  725. GB_ASSERT(arg_count >= param_count);
  726. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  727. LLVMGetParamTypes(fnp, param_types);
  728. for (unsigned i = 0; i < param_count; i++) {
  729. LLVMTypeRef param_type = param_types[i];
  730. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  731. if (LB_USE_NEW_PASS_SYSTEM &&
  732. arg_type != param_type) {
  733. LLVMTypeKind arg_kind = LLVMGetTypeKind(arg_type);
  734. LLVMTypeKind param_kind = LLVMGetTypeKind(param_type);
  735. if (arg_kind == param_kind &&
  736. arg_kind == LLVMPointerTypeKind) {
  737. // NOTE(bill): LLVM's newer `ptr` only type system seems to fail at times
  738. // I don't know why...
  739. args[i] = LLVMBuildPointerCast(p->builder, args[i], param_type, "");
  740. arg_type = param_type;
  741. continue;
  742. }
  743. }
  744. GB_ASSERT_MSG(
  745. arg_type == param_type,
  746. "Parameter types do not match: %s != %s, argument: %s\n\t%s",
  747. LLVMPrintTypeToString(arg_type),
  748. LLVMPrintTypeToString(param_type),
  749. LLVMPrintValueToString(args[i]),
  750. LLVMPrintTypeToString(fnp)
  751. );
  752. }
  753. }
  754. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  755. auto llvm_cc = lb_calling_convention_map[proc_type->Proc.calling_convention];
  756. LLVMSetInstructionCallConv(ret, llvm_cc);
  757. LLVMAttributeIndex param_offset = LLVMAttributeIndex_FirstArgIndex;
  758. if (return_ptr.value != nullptr) {
  759. param_offset += 1;
  760. LLVMAddCallSiteAttribute(ret, 1, lb_create_enum_attribute_with_type(p->module->ctx, "sret", LLVMTypeOf(args[0])));
  761. }
  762. for_array(i, ft->args) {
  763. LLVMAttributeRef attribute = ft->args[i].attribute;
  764. if (attribute != nullptr) {
  765. LLVMAddCallSiteAttribute(ret, param_offset + cast(LLVMAttributeIndex)i, attribute);
  766. }
  767. }
  768. switch (inlining) {
  769. case ProcInlining_none:
  770. break;
  771. case ProcInlining_inline:
  772. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  773. break;
  774. case ProcInlining_no_inline:
  775. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  776. break;
  777. }
  778. lbValue res = {};
  779. res.value = ret;
  780. res.type = abi_rt;
  781. return res;
  782. }
  783. }
  784. gb_internal lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  785. AstPackage *pkg = m->info->runtime_package;
  786. Entity *e = scope_lookup_current(pkg->scope, name);
  787. return lb_find_procedure_value_from_entity(m, e);
  788. }
  789. gb_internal lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  790. String name = make_string_c(c_name);
  791. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  792. return lb_emit_call(p, proc, args);
  793. }
  794. gb_internal lbValue lb_emit_conjugate(lbProcedure *p, lbValue val, Type *type) {
  795. lbValue res = {};
  796. Type *t = val.type;
  797. if (is_type_complex(t)) {
  798. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  799. lbValue real = lb_emit_struct_ev(p, val, 0);
  800. lbValue imag = lb_emit_struct_ev(p, val, 1);
  801. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  802. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  803. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  804. } else if (is_type_quaternion(t)) {
  805. // @QuaternionLayout
  806. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  807. lbValue real = lb_emit_struct_ev(p, val, 3);
  808. lbValue imag = lb_emit_struct_ev(p, val, 0);
  809. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  810. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  811. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  812. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  813. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  814. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  815. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  816. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  817. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  818. } else if (is_type_array_like(t)) {
  819. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  820. Type *elem_type = base_array_type(t);
  821. i64 count = get_array_type_count(t);
  822. for (i64 i = 0; i < count; i++) {
  823. lbValue dst = lb_emit_array_epi(p, res, i);
  824. lbValue elem = lb_emit_struct_ev(p, val, cast(i32)i);
  825. elem = lb_emit_conjugate(p, elem, elem_type);
  826. lb_emit_store(p, dst, elem);
  827. }
  828. } else if (is_type_matrix(t)) {
  829. Type *mt = base_type(t);
  830. GB_ASSERT(mt->kind == Type_Matrix);
  831. Type *elem_type = mt->Matrix.elem;
  832. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  833. for (i64 j = 0; j < mt->Matrix.column_count; j++) {
  834. for (i64 i = 0; i < mt->Matrix.row_count; i++) {
  835. lbValue dst = lb_emit_matrix_epi(p, res, i, j);
  836. lbValue elem = lb_emit_matrix_ev(p, val, i, j);
  837. elem = lb_emit_conjugate(p, elem, elem_type);
  838. lb_emit_store(p, dst, elem);
  839. }
  840. }
  841. }
  842. return lb_emit_load(p, res);
  843. }
  844. gb_internal lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining) {
  845. lbModule *m = p->module;
  846. Type *pt = base_type(value.type);
  847. GB_ASSERT(pt->kind == Type_Proc);
  848. Type *results = pt->Proc.results;
  849. lbAddr context_ptr = {};
  850. if (pt->Proc.calling_convention == ProcCC_Odin) {
  851. context_ptr = lb_find_or_generate_context_ptr(p);
  852. }
  853. defer (if (pt->Proc.diverging) {
  854. LLVMBuildUnreachable(p->builder);
  855. });
  856. bool is_c_vararg = pt->Proc.c_vararg;
  857. isize param_count = pt->Proc.param_count;
  858. if (is_c_vararg) {
  859. GB_ASSERT(param_count-1 <= args.count);
  860. param_count -= 1;
  861. } else {
  862. GB_ASSERT_MSG(param_count == args.count, "%td == %td (%s)", param_count, args.count, LLVMPrintValueToString(value.value));
  863. }
  864. lbValue result = {};
  865. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  866. {
  867. bool is_odin_cc = is_calling_convention_odin(pt->Proc.calling_convention);
  868. lbFunctionType *ft = lb_get_function_type(m, pt);
  869. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  870. bool split_returns = ft->multiple_return_original_type != nullptr;
  871. unsigned param_index = 0;
  872. for (isize i = 0; i < param_count; i++) {
  873. Entity *e = pt->Proc.params->Tuple.variables[i];
  874. if (e->kind != Entity_Variable) {
  875. continue;
  876. }
  877. GB_ASSERT(e->flags & EntityFlag_Param);
  878. Type *original_type = e->type;
  879. lbArgType *arg = &ft->args[param_index];
  880. if (arg->kind == lbArg_Ignore) {
  881. param_index += 1;
  882. continue;
  883. }
  884. lbValue x = lb_emit_conv(p, args[i], original_type);
  885. LLVMTypeRef xt = lb_type(p->module, x.type);
  886. if (arg->kind == lbArg_Direct) {
  887. LLVMTypeRef abi_type = arg->cast_type;
  888. if (!abi_type) {
  889. abi_type = arg->type;
  890. }
  891. if (xt == abi_type) {
  892. array_add(&processed_args, x);
  893. } else {
  894. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  895. array_add(&processed_args, x);
  896. }
  897. } else if (arg->kind == lbArg_Indirect) {
  898. lbValue ptr = {};
  899. if (arg->is_byval) {
  900. if (is_odin_cc) {
  901. if (are_types_identical(original_type, t_source_code_location)) {
  902. ptr = lb_address_from_load_or_generate_local(p, x);
  903. // } else {
  904. // ptr = lb_address_from_load_if_readonly_parameter(p, x);
  905. }
  906. }
  907. if (ptr.value == nullptr) {
  908. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  909. }
  910. } else if (is_odin_cc) {
  911. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  912. // i.e. `T const &` in C++
  913. if (LLVMIsConstant(x.value)) {
  914. // NOTE(bill): if the value is already constant, then just it as a global variable
  915. // and pass it by pointer
  916. lbAddr addr = lb_add_global_generated(p->module, original_type, x);
  917. lb_make_global_private_const(addr);
  918. ptr = addr.addr;
  919. } else {
  920. ptr = lb_address_from_load_or_generate_local(p, x);
  921. }
  922. } else {
  923. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  924. }
  925. array_add(&processed_args, ptr);
  926. }
  927. param_index += 1;
  928. }
  929. if (is_c_vararg) {
  930. for (isize i = processed_args.count; i < args.count; i++) {
  931. array_add(&processed_args, args[i]);
  932. }
  933. }
  934. if (inlining == ProcInlining_none) {
  935. inlining = p->inlining;
  936. }
  937. Type *rt = reduce_tuple_to_single_type(results);
  938. Type *original_rt = rt;
  939. if (split_returns) {
  940. GB_ASSERT(rt->kind == Type_Tuple);
  941. for (isize j = 0; j < rt->Tuple.variables.count-1; j++) {
  942. Type *partial_return_type = rt->Tuple.variables[j]->type;
  943. lbValue partial_return_ptr = lb_add_local(p, partial_return_type, nullptr, true, false).addr;
  944. array_add(&processed_args, partial_return_ptr);
  945. }
  946. rt = reduce_tuple_to_single_type(rt->Tuple.variables[rt->Tuple.variables.count-1]->type);
  947. }
  948. if (return_by_pointer) {
  949. lbValue return_ptr = lb_add_local_generated(p, rt, true).addr;
  950. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  951. result = lb_emit_load(p, return_ptr);
  952. } else if (rt != nullptr) {
  953. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  954. if (ft->ret.cast_type) {
  955. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  956. }
  957. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  958. result.type = rt;
  959. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  960. result.type = t_llvm_bool;
  961. }
  962. if (!is_type_tuple(rt)) {
  963. result = lb_emit_conv(p, result, rt);
  964. }
  965. } else {
  966. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  967. }
  968. if (original_rt != rt) {
  969. GB_ASSERT(split_returns);
  970. GB_ASSERT(is_type_tuple(original_rt));
  971. // IMPORTANT NOTE(bill, 2022-11-24)
  972. // result_ptr is a dummy value which is only used to reference a tuple
  973. // value for the "tuple-fix"
  974. //
  975. // The reason for the fake stack allocation is to have a unique pointer
  976. // for the value to be used as a key within the procedure itself
  977. lbValue result_ptr = lb_add_local_generated(p, original_rt, false).addr;
  978. isize ret_count = original_rt->Tuple.variables.count;
  979. auto tuple_fix_values = slice_make<lbValue>(permanent_allocator(), ret_count);
  980. auto tuple_geps = slice_make<lbValue>(permanent_allocator(), ret_count);
  981. isize offset = ft->original_arg_count;
  982. for (isize j = 0; j < ret_count-1; j++) {
  983. lbValue ret_arg_ptr = processed_args[offset + j];
  984. lbValue ret_arg = lb_emit_load(p, ret_arg_ptr);
  985. tuple_fix_values[j] = ret_arg;
  986. }
  987. tuple_fix_values[ret_count-1] = result;
  988. #if 0
  989. for (isize j = 0; j < ret_count; j++) {
  990. tuple_geps[j] = lb_emit_struct_ep(p, result_ptr, cast(i32)j);
  991. }
  992. for (isize j = 0; j < ret_count; j++) {
  993. lb_emit_store(p, tuple_geps[j], tuple_fix_values[j]);
  994. }
  995. #endif
  996. result = lb_emit_load(p, result_ptr);
  997. lbTupleFix tf = {tuple_fix_values};
  998. map_set(&p->tuple_fix_map, result_ptr.value, tf);
  999. map_set(&p->tuple_fix_map, result.value, tf);
  1000. }
  1001. }
  1002. LLVMValueRef the_proc_value = value.value;
  1003. if (LLVMIsAConstantExpr(the_proc_value)) {
  1004. // NOTE(bill): it's a bit cast
  1005. the_proc_value = LLVMGetOperand(the_proc_value, 0);
  1006. }
  1007. Entity **found = map_get(&p->module->procedure_values, the_proc_value);
  1008. if (found != nullptr) {
  1009. Entity *e = *found;
  1010. if (e != nullptr && entity_has_deferred_procedure(e)) {
  1011. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  1012. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  1013. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  1014. bool by_ptr = false;
  1015. auto in_args = args;
  1016. Array<lbValue> result_as_args = {};
  1017. switch (kind) {
  1018. case DeferredProcedure_none:
  1019. break;
  1020. case DeferredProcedure_in_by_ptr:
  1021. by_ptr = true;
  1022. /*fallthrough*/
  1023. case DeferredProcedure_in:
  1024. result_as_args = array_clone(heap_allocator(), in_args);
  1025. break;
  1026. case DeferredProcedure_out_by_ptr:
  1027. by_ptr = true;
  1028. /*fallthrough*/
  1029. case DeferredProcedure_out:
  1030. result_as_args = lb_value_to_array(p, heap_allocator(), result);
  1031. break;
  1032. case DeferredProcedure_in_out_by_ptr:
  1033. by_ptr = true;
  1034. /*fallthrough*/
  1035. case DeferredProcedure_in_out:
  1036. {
  1037. auto out_args = lb_value_to_array(p, heap_allocator(), result);
  1038. array_init(&result_as_args, heap_allocator(), in_args.count + out_args.count);
  1039. array_copy(&result_as_args, in_args, 0);
  1040. array_copy(&result_as_args, out_args, in_args.count);
  1041. }
  1042. break;
  1043. }
  1044. if (by_ptr) {
  1045. for_array(i, result_as_args) {
  1046. lbValue arg_ptr = lb_address_from_load_or_generate_local(p, result_as_args[i]);
  1047. result_as_args[i] = arg_ptr;
  1048. }
  1049. }
  1050. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  1051. }
  1052. }
  1053. return result;
  1054. }
  1055. gb_internal LLVMValueRef llvm_splat_int(i64 count, LLVMTypeRef type, i64 value, bool is_signed=false) {
  1056. LLVMValueRef v = LLVMConstInt(type, value, is_signed);
  1057. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1058. for (i64 i = 0; i < count; i++) {
  1059. values[i] = v;
  1060. }
  1061. return LLVMConstVector(values, cast(unsigned)count);
  1062. }
  1063. gb_internal lbValue lb_build_builtin_simd_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId builtin_id) {
  1064. ast_node(ce, CallExpr, expr);
  1065. lbModule *m = p->module;
  1066. lbValue res = {};
  1067. res.type = tv.type;
  1068. lbValue arg0 = {}; if (ce->args.count > 0) arg0 = lb_build_expr(p, ce->args[0]);
  1069. lbValue arg1 = {}; if (ce->args.count > 1) arg1 = lb_build_expr(p, ce->args[1]);
  1070. lbValue arg2 = {}; if (ce->args.count > 2) arg2 = lb_build_expr(p, ce->args[2]);
  1071. Type *elem = base_array_type(arg0.type);
  1072. bool is_float = is_type_float(elem);
  1073. bool is_signed = !is_type_unsigned(elem);
  1074. LLVMOpcode op_code = cast(LLVMOpcode)0;
  1075. switch (builtin_id) {
  1076. case BuiltinProc_simd_add:
  1077. case BuiltinProc_simd_sub:
  1078. case BuiltinProc_simd_mul:
  1079. case BuiltinProc_simd_div:
  1080. case BuiltinProc_simd_rem:
  1081. if (is_float) {
  1082. switch (builtin_id) {
  1083. case BuiltinProc_simd_add: op_code = LLVMFAdd; break;
  1084. case BuiltinProc_simd_sub: op_code = LLVMFSub; break;
  1085. case BuiltinProc_simd_mul: op_code = LLVMFMul; break;
  1086. case BuiltinProc_simd_div: op_code = LLVMFDiv; break;
  1087. }
  1088. } else {
  1089. switch (builtin_id) {
  1090. case BuiltinProc_simd_add: op_code = LLVMAdd; break;
  1091. case BuiltinProc_simd_sub: op_code = LLVMSub; break;
  1092. case BuiltinProc_simd_mul: op_code = LLVMMul; break;
  1093. case BuiltinProc_simd_div:
  1094. if (is_signed) {
  1095. op_code = LLVMSDiv;
  1096. } else {
  1097. op_code = LLVMUDiv;
  1098. }
  1099. break;
  1100. case BuiltinProc_simd_rem:
  1101. if (is_signed) {
  1102. op_code = LLVMSRem;
  1103. } else {
  1104. op_code = LLVMURem;
  1105. }
  1106. break;
  1107. }
  1108. }
  1109. if (op_code) {
  1110. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1111. return res;
  1112. }
  1113. break;
  1114. case BuiltinProc_simd_shl: // Odin logic
  1115. case BuiltinProc_simd_shr: // Odin logic
  1116. case BuiltinProc_simd_shl_masked: // C logic
  1117. case BuiltinProc_simd_shr_masked: // C logic
  1118. {
  1119. i64 sz = type_size_of(elem);
  1120. GB_ASSERT(arg0.type->kind == Type_SimdVector);
  1121. i64 count = arg0.type->SimdVector.count;
  1122. Type *elem1 = base_array_type(arg1.type);
  1123. bool is_masked = false;
  1124. switch (builtin_id) {
  1125. case BuiltinProc_simd_shl: op_code = LLVMShl; is_masked = false; break;
  1126. case BuiltinProc_simd_shr: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = false; break;
  1127. case BuiltinProc_simd_shl_masked: op_code = LLVMShl; is_masked = true; break;
  1128. case BuiltinProc_simd_shr_masked: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = true; break;
  1129. }
  1130. if (op_code) {
  1131. LLVMValueRef bits = llvm_splat_int(count, lb_type(m, elem1), sz*8 - 1);
  1132. if (is_masked) {
  1133. // C logic
  1134. LLVMValueRef shift = LLVMBuildAnd(p->builder, arg1.value, bits, "");
  1135. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, shift, "");
  1136. } else {
  1137. // Odin logic
  1138. LLVMValueRef zero = lb_const_nil(m, arg1.type).value;
  1139. LLVMValueRef mask = LLVMBuildICmp(p->builder, LLVMIntULE, arg1.value, bits, "");
  1140. LLVMValueRef shift = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1141. res.value = LLVMBuildSelect(p->builder, mask, shift, zero, "");
  1142. }
  1143. return res;
  1144. }
  1145. }
  1146. break;
  1147. case BuiltinProc_simd_bit_and:
  1148. case BuiltinProc_simd_bit_or:
  1149. case BuiltinProc_simd_bit_xor:
  1150. case BuiltinProc_simd_bit_and_not:
  1151. switch (builtin_id) {
  1152. case BuiltinProc_simd_bit_and: op_code = LLVMAnd; break;
  1153. case BuiltinProc_simd_bit_or: op_code = LLVMOr; break;
  1154. case BuiltinProc_simd_bit_xor: op_code = LLVMXor; break;
  1155. case BuiltinProc_simd_bit_and_not:
  1156. op_code = LLVMAnd;
  1157. arg1.value = LLVMBuildNot(p->builder, arg1.value, "");
  1158. break;
  1159. }
  1160. if (op_code) {
  1161. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1162. return res;
  1163. }
  1164. break;
  1165. case BuiltinProc_simd_neg:
  1166. if (is_float) {
  1167. res.value = LLVMBuildFNeg(p->builder, arg0.value, "");
  1168. } else {
  1169. res.value = LLVMBuildNeg(p->builder, arg0.value, "");
  1170. }
  1171. return res;
  1172. case BuiltinProc_simd_abs:
  1173. if (is_float) {
  1174. LLVMValueRef pos = arg0.value;
  1175. LLVMValueRef neg = LLVMBuildFNeg(p->builder, pos, "");
  1176. LLVMValueRef cond = LLVMBuildFCmp(p->builder, LLVMRealOGT, pos, neg, "");
  1177. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1178. } else {
  1179. LLVMValueRef pos = arg0.value;
  1180. LLVMValueRef neg = LLVMBuildNeg(p->builder, pos, "");
  1181. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, pos, neg, "");
  1182. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1183. }
  1184. return res;
  1185. case BuiltinProc_simd_min:
  1186. if (is_float) {
  1187. return lb_emit_min(p, res.type, arg0, arg1);
  1188. } else {
  1189. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSLT : LLVMIntULT, arg0.value, arg1.value, "");
  1190. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1191. }
  1192. return res;
  1193. case BuiltinProc_simd_max:
  1194. if (is_float) {
  1195. return lb_emit_max(p, res.type, arg0, arg1);
  1196. } else {
  1197. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, arg0.value, arg1.value, "");
  1198. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1199. }
  1200. return res;
  1201. case BuiltinProc_simd_lanes_eq:
  1202. case BuiltinProc_simd_lanes_ne:
  1203. case BuiltinProc_simd_lanes_lt:
  1204. case BuiltinProc_simd_lanes_le:
  1205. case BuiltinProc_simd_lanes_gt:
  1206. case BuiltinProc_simd_lanes_ge:
  1207. if (is_float) {
  1208. LLVMRealPredicate pred = cast(LLVMRealPredicate)0;
  1209. switch (builtin_id) {
  1210. case BuiltinProc_simd_lanes_eq: pred = LLVMRealOEQ; break;
  1211. case BuiltinProc_simd_lanes_ne: pred = LLVMRealONE; break;
  1212. case BuiltinProc_simd_lanes_lt: pred = LLVMRealOLT; break;
  1213. case BuiltinProc_simd_lanes_le: pred = LLVMRealOLE; break;
  1214. case BuiltinProc_simd_lanes_gt: pred = LLVMRealOGT; break;
  1215. case BuiltinProc_simd_lanes_ge: pred = LLVMRealOGE; break;
  1216. }
  1217. if (pred) {
  1218. res.value = LLVMBuildFCmp(p->builder, pred, arg0.value, arg1.value, "");
  1219. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1220. return res;
  1221. }
  1222. } else {
  1223. LLVMIntPredicate pred = cast(LLVMIntPredicate)0;
  1224. switch (builtin_id) {
  1225. case BuiltinProc_simd_lanes_eq: pred = LLVMIntEQ; break;
  1226. case BuiltinProc_simd_lanes_ne: pred = LLVMIntNE; break;
  1227. case BuiltinProc_simd_lanes_lt: pred = is_signed ? LLVMIntSLT :LLVMIntULT; break;
  1228. case BuiltinProc_simd_lanes_le: pred = is_signed ? LLVMIntSLE :LLVMIntULE; break;
  1229. case BuiltinProc_simd_lanes_gt: pred = is_signed ? LLVMIntSGT :LLVMIntUGT; break;
  1230. case BuiltinProc_simd_lanes_ge: pred = is_signed ? LLVMIntSGE :LLVMIntUGE; break;
  1231. }
  1232. if (pred) {
  1233. res.value = LLVMBuildICmp(p->builder, pred, arg0.value, arg1.value, "");
  1234. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1235. return res;
  1236. }
  1237. }
  1238. break;
  1239. case BuiltinProc_simd_extract:
  1240. res.value = LLVMBuildExtractElement(p->builder, arg0.value, arg1.value, "");
  1241. return res;
  1242. case BuiltinProc_simd_replace:
  1243. res.value = LLVMBuildInsertElement(p->builder, arg0.value, arg2.value, arg1.value, "");
  1244. return res;
  1245. case BuiltinProc_simd_reduce_add_ordered:
  1246. case BuiltinProc_simd_reduce_mul_ordered:
  1247. {
  1248. LLVMTypeRef llvm_elem = lb_type(m, elem);
  1249. LLVMValueRef args[2] = {};
  1250. isize args_count = 0;
  1251. char const *name = nullptr;
  1252. switch (builtin_id) {
  1253. case BuiltinProc_simd_reduce_add_ordered:
  1254. if (is_float) {
  1255. name = "llvm.vector.reduce.fadd";
  1256. args[args_count++] = LLVMConstReal(llvm_elem, 0.0);
  1257. } else {
  1258. name = "llvm.vector.reduce.add";
  1259. }
  1260. break;
  1261. case BuiltinProc_simd_reduce_mul_ordered:
  1262. if (is_float) {
  1263. name = "llvm.vector.reduce.fmul";
  1264. args[args_count++] = LLVMConstReal(llvm_elem, 1.0);
  1265. } else {
  1266. name = "llvm.vector.reduce.mul";
  1267. }
  1268. break;
  1269. }
  1270. args[args_count++] = arg0.value;
  1271. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1272. res.value = lb_call_intrinsic(p, name, args, cast(unsigned)args_count, types, gb_count_of(types));
  1273. return res;
  1274. }
  1275. case BuiltinProc_simd_reduce_min:
  1276. case BuiltinProc_simd_reduce_max:
  1277. case BuiltinProc_simd_reduce_and:
  1278. case BuiltinProc_simd_reduce_or:
  1279. case BuiltinProc_simd_reduce_xor:
  1280. {
  1281. char const *name = nullptr;
  1282. switch (builtin_id) {
  1283. case BuiltinProc_simd_reduce_min:
  1284. if (is_float) {
  1285. name = "llvm.vector.reduce.fmin";
  1286. } else if (is_signed) {
  1287. name = "llvm.vector.reduce.smin";
  1288. } else {
  1289. name = "llvm.vector.reduce.umin";
  1290. }
  1291. break;
  1292. case BuiltinProc_simd_reduce_max:
  1293. if (is_float) {
  1294. name = "llvm.vector.reduce.fmax";
  1295. } else if (is_signed) {
  1296. name = "llvm.vector.reduce.smax";
  1297. } else {
  1298. name = "llvm.vector.reduce.umax";
  1299. }
  1300. break;
  1301. case BuiltinProc_simd_reduce_and: name = "llvm.vector.reduce.and"; break;
  1302. case BuiltinProc_simd_reduce_or: name = "llvm.vector.reduce.or"; break;
  1303. case BuiltinProc_simd_reduce_xor: name = "llvm.vector.reduce.xor"; break;
  1304. }
  1305. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1306. LLVMValueRef args[1] = { arg0.value };
  1307. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1308. return res;
  1309. }
  1310. case BuiltinProc_simd_reduce_any:
  1311. case BuiltinProc_simd_reduce_all:
  1312. {
  1313. char const *name = nullptr;
  1314. switch (builtin_id) {
  1315. case BuiltinProc_simd_reduce_any: name = "llvm.vector.reduce.or"; break;
  1316. case BuiltinProc_simd_reduce_all: name = "llvm.vector.reduce.and"; break;
  1317. }
  1318. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1319. LLVMValueRef args[1] = { arg0.value };
  1320. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1321. return res;
  1322. }
  1323. case BuiltinProc_simd_shuffle:
  1324. {
  1325. Type *vt = arg0.type;
  1326. GB_ASSERT(vt->kind == Type_SimdVector);
  1327. i64 indices_count = ce->args.count-2;
  1328. i64 max_count = vt->SimdVector.count*2;
  1329. GB_ASSERT(indices_count <= max_count);
  1330. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, indices_count);
  1331. for (isize i = 0; i < indices_count; i++) {
  1332. lbValue idx = lb_build_expr(p, ce->args[i+2]);
  1333. GB_ASSERT(LLVMIsConstant(idx.value));
  1334. values[i] = idx.value;
  1335. }
  1336. LLVMValueRef indices = LLVMConstVector(values, cast(unsigned)indices_count);
  1337. res.value = LLVMBuildShuffleVector(p->builder, arg0.value, arg1.value, indices, "");
  1338. return res;
  1339. }
  1340. case BuiltinProc_simd_select:
  1341. {
  1342. LLVMValueRef cond = arg0.value;
  1343. LLVMValueRef x = lb_build_expr(p, ce->args[1]).value;
  1344. LLVMValueRef y = lb_build_expr(p, ce->args[2]).value;
  1345. cond = LLVMBuildICmp(p->builder, LLVMIntNE, cond, LLVMConstNull(LLVMTypeOf(cond)), "");
  1346. res.value = LLVMBuildSelect(p->builder, cond, x, y, "");
  1347. return res;
  1348. }
  1349. case BuiltinProc_simd_ceil:
  1350. case BuiltinProc_simd_floor:
  1351. case BuiltinProc_simd_trunc:
  1352. case BuiltinProc_simd_nearest:
  1353. {
  1354. char const *name = nullptr;
  1355. switch (builtin_id) {
  1356. case BuiltinProc_simd_ceil: name = "llvm.ceil"; break;
  1357. case BuiltinProc_simd_floor: name = "llvm.floor"; break;
  1358. case BuiltinProc_simd_trunc: name = "llvm.trunc"; break;
  1359. case BuiltinProc_simd_nearest: name = "llvm.nearbyint"; break;
  1360. }
  1361. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1362. LLVMValueRef args[1] = { arg0.value };
  1363. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1364. return res;
  1365. }
  1366. case BuiltinProc_simd_lanes_reverse:
  1367. {
  1368. i64 count = get_array_type_count(arg0.type);
  1369. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1370. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1371. for (i64 i = 0; i < count; i++) {
  1372. values[i] = LLVMConstInt(llvm_u32, count-1-i, false);
  1373. }
  1374. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1375. LLVMValueRef v = arg0.value;
  1376. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1377. return res;
  1378. }
  1379. case BuiltinProc_simd_lanes_rotate_left:
  1380. case BuiltinProc_simd_lanes_rotate_right:
  1381. {
  1382. i64 count = get_array_type_count(arg0.type);
  1383. GB_ASSERT(is_power_of_two(count));
  1384. BigInt bi_count = {};
  1385. big_int_from_i64(&bi_count, count);
  1386. TypeAndValue const &tv = ce->args[1]->tav;
  1387. ExactValue val = exact_value_to_integer(tv.value);
  1388. GB_ASSERT(val.kind == ExactValue_Integer);
  1389. BigInt *bi = &val.value_integer;
  1390. if (builtin_id == BuiltinProc_simd_lanes_rotate_right) {
  1391. big_int_neg(bi, bi);
  1392. }
  1393. big_int_rem(bi, bi, &bi_count);
  1394. big_int_dealloc(&bi_count);
  1395. i64 left = big_int_to_i64(bi);
  1396. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1397. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1398. for (i64 i = 0; i < count; i++) {
  1399. u64 idx = cast(u64)(i+left) & cast(u64)(count-1);
  1400. values[i] = LLVMConstInt(llvm_u32, idx, false);
  1401. }
  1402. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1403. LLVMValueRef v = arg0.value;
  1404. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1405. return res;
  1406. }
  1407. case BuiltinProc_simd_saturating_add:
  1408. case BuiltinProc_simd_saturating_sub:
  1409. {
  1410. char const *name = nullptr;
  1411. switch (builtin_id) {
  1412. case BuiltinProc_simd_saturating_add: name = is_signed ? "llvm.sadd.sat" : "llvm.uadd.sat"; break;
  1413. case BuiltinProc_simd_saturating_sub: name = is_signed ? "llvm.ssub.sat" : "llvm.usub.sat"; break;
  1414. }
  1415. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1416. LLVMValueRef args[2] = { arg0.value, arg1.value };
  1417. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1418. return res;
  1419. }
  1420. case BuiltinProc_simd_clamp:
  1421. {
  1422. LLVMValueRef v = arg0.value;
  1423. LLVMValueRef min = arg1.value;
  1424. LLVMValueRef max = arg2.value;
  1425. if (is_float) {
  1426. v = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOLT, v, min, ""), min, v, "");
  1427. res.value = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOGT, v, max, ""), max, v, "");
  1428. } else if (is_signed) {
  1429. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSLT, v, min, ""), min, v, "");
  1430. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSGT, v, max, ""), max, v, "");
  1431. } else {
  1432. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntULT, v, min, ""), min, v, "");
  1433. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntUGT, v, max, ""), max, v, "");
  1434. }
  1435. return res;
  1436. }
  1437. case BuiltinProc_simd_to_bits:
  1438. {
  1439. res.value = LLVMBuildBitCast(p->builder, arg0.value, lb_type(m, tv.type), "");
  1440. return res;
  1441. }
  1442. case BuiltinProc_simd_gather:
  1443. case BuiltinProc_simd_scatter:
  1444. case BuiltinProc_simd_masked_load:
  1445. case BuiltinProc_simd_masked_store:
  1446. case BuiltinProc_simd_masked_expand_load:
  1447. case BuiltinProc_simd_masked_compress_store:
  1448. {
  1449. LLVMValueRef ptr = arg0.value;
  1450. LLVMValueRef val = arg1.value;
  1451. LLVMValueRef mask = arg2.value;
  1452. unsigned count = cast(unsigned)get_array_type_count(arg1.type);
  1453. LLVMTypeRef mask_type = LLVMVectorType(LLVMInt1TypeInContext(p->module->ctx), count);
  1454. mask = LLVMBuildTrunc(p->builder, mask, mask_type, "");
  1455. char const *name = nullptr;
  1456. switch (builtin_id) {
  1457. case BuiltinProc_simd_gather: name = "llvm.masked.gather"; break;
  1458. case BuiltinProc_simd_scatter: name = "llvm.masked.scatter"; break;
  1459. case BuiltinProc_simd_masked_load: name = "llvm.masked.load"; break;
  1460. case BuiltinProc_simd_masked_store: name = "llvm.masked.store"; break;
  1461. case BuiltinProc_simd_masked_expand_load: name = "llvm.masked.expandload"; break;
  1462. case BuiltinProc_simd_masked_compress_store: name = "llvm.masked.compressstore"; break;
  1463. }
  1464. unsigned type_count = 2;
  1465. LLVMTypeRef types[2] = {
  1466. lb_type(p->module, arg1.type),
  1467. lb_type(p->module, arg0.type)
  1468. };
  1469. auto alignment = cast(unsigned long long)type_align_of(base_array_type(arg1.type));
  1470. LLVMValueRef align = LLVMConstInt(LLVMInt32TypeInContext(p->module->ctx), alignment, false);
  1471. unsigned arg_count = 4;
  1472. LLVMValueRef args[4] = {};
  1473. switch (builtin_id) {
  1474. case BuiltinProc_simd_masked_load:
  1475. types[1] = lb_type(p->module, t_rawptr);
  1476. /*fallthrough*/
  1477. case BuiltinProc_simd_gather:
  1478. args[0] = ptr;
  1479. args[1] = align;
  1480. args[2] = mask;
  1481. args[3] = val;
  1482. break;
  1483. case BuiltinProc_simd_masked_store:
  1484. types[1] = lb_type(p->module, t_rawptr);
  1485. /*fallthrough*/
  1486. case BuiltinProc_simd_scatter:
  1487. args[0] = val;
  1488. args[1] = ptr;
  1489. args[2] = align;
  1490. args[3] = mask;
  1491. break;
  1492. case BuiltinProc_simd_masked_expand_load:
  1493. arg_count = 3;
  1494. type_count = 1;
  1495. args[0] = ptr;
  1496. args[1] = mask;
  1497. args[2] = val;
  1498. break;
  1499. case BuiltinProc_simd_masked_compress_store:
  1500. arg_count = 3;
  1501. type_count = 1;
  1502. args[0] = val;
  1503. args[1] = ptr;
  1504. args[2] = mask;
  1505. break;
  1506. }
  1507. res.value = lb_call_intrinsic(p, name, args, arg_count, types, type_count);
  1508. return res;
  1509. }
  1510. }
  1511. GB_PANIC("Unhandled simd intrinsic: '%.*s'", LIT(builtin_procs[builtin_id].name));
  1512. return {};
  1513. }
  1514. gb_internal lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  1515. ast_node(ce, CallExpr, expr);
  1516. if (BuiltinProc__simd_begin < id && id < BuiltinProc__simd_end) {
  1517. return lb_build_builtin_simd_proc(p, expr, tv, id);
  1518. }
  1519. switch (id) {
  1520. case BuiltinProc_DIRECTIVE: {
  1521. ast_node(bd, BasicDirective, ce->proc);
  1522. String name = bd->name.string;
  1523. if (name == "location") {
  1524. String procedure = p->entity->token.string;
  1525. TokenPos pos = ast_token(ce->proc).pos;
  1526. if (ce->args.count > 0) {
  1527. Ast *ident = unselector_expr(ce->args[0]);
  1528. GB_ASSERT(ident->kind == Ast_Ident);
  1529. Entity *e = entity_of_node(ident);
  1530. GB_ASSERT(e != nullptr);
  1531. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  1532. procedure = e->parent_proc_decl->entity->token.string;
  1533. } else {
  1534. procedure = str_lit("");
  1535. }
  1536. pos = e->token.pos;
  1537. }
  1538. return lb_emit_source_code_location_as_global(p, procedure, pos);
  1539. } else if (name == "load_directory") {
  1540. lbModule *m = p->module;
  1541. TEMPORARY_ALLOCATOR_GUARD();
  1542. LoadDirectoryCache *cache = map_must_get(&m->info->load_directory_map, expr);
  1543. isize count = cache->files.count;
  1544. LLVMValueRef *elements = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1545. for_array(i, cache->files) {
  1546. LoadFileCache *file = cache->files[i];
  1547. String file_name = filename_without_directory(file->path);
  1548. LLVMValueRef values[2] = {};
  1549. values[0] = lb_const_string(m, file_name).value;
  1550. values[1] = lb_const_string(m, file->data).value;
  1551. LLVMValueRef element = llvm_const_named_struct(m, t_load_directory_file, values, gb_count_of(values));
  1552. elements[i] = element;
  1553. }
  1554. LLVMValueRef backing_array = llvm_const_array(lb_type(m, t_load_directory_file), elements, count);
  1555. Type *array_type = alloc_type_array(t_load_directory_file, count);
  1556. lbAddr backing_array_addr = lb_add_global_generated(m, array_type, {backing_array, array_type}, nullptr);
  1557. lb_make_global_private_const(backing_array_addr);
  1558. LLVMValueRef backing_array_ptr = backing_array_addr.addr.value;
  1559. backing_array_ptr = LLVMConstPointerCast(backing_array_ptr, lb_type(m, t_load_directory_file_ptr));
  1560. LLVMValueRef const_slice = llvm_const_slice_internal(m, backing_array_ptr, LLVMConstInt(lb_type(m, t_int), count, false));
  1561. lbAddr addr = lb_add_global_generated(p->module, tv.type, {const_slice, t_load_directory_file_slice}, nullptr);
  1562. lb_make_global_private_const(addr);
  1563. return lb_addr_load(p, addr);
  1564. } else {
  1565. GB_PANIC("UNKNOWN DIRECTIVE: %.*s", LIT(name));
  1566. }
  1567. }
  1568. case BuiltinProc_type_info_of: {
  1569. Ast *arg = ce->args[0];
  1570. TypeAndValue tav = type_and_value_of_expr(arg);
  1571. if (tav.mode == Addressing_Type) {
  1572. Type *t = default_type(type_of_expr(arg));
  1573. return lb_type_info(p, t);
  1574. }
  1575. GB_ASSERT(is_type_typeid(tav.type));
  1576. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1577. args[0] = lb_build_expr(p, arg);
  1578. return lb_emit_runtime_call(p, "__type_info_of", args);
  1579. }
  1580. case BuiltinProc_typeid_of: {
  1581. Ast *arg = ce->args[0];
  1582. TypeAndValue tav = type_and_value_of_expr(arg);
  1583. GB_ASSERT(tav.mode == Addressing_Type);
  1584. Type *t = default_type(type_of_expr(arg));
  1585. return lb_typeid(p->module, t);
  1586. }
  1587. case BuiltinProc_len: {
  1588. lbValue v = lb_build_expr(p, ce->args[0]);
  1589. Type *t = base_type(v.type);
  1590. if (is_type_pointer(t)) {
  1591. v = lb_emit_load(p, v);
  1592. t = type_deref(t);
  1593. }
  1594. if (is_type_cstring(t)) {
  1595. return lb_cstring_len(p, v);
  1596. } else if (is_type_string(t)) {
  1597. return lb_string_len(p, v);
  1598. } else if (is_type_array(t)) {
  1599. GB_PANIC("Array lengths are constant");
  1600. } else if (is_type_slice(t)) {
  1601. return lb_slice_len(p, v);
  1602. } else if (is_type_dynamic_array(t)) {
  1603. return lb_dynamic_array_len(p, v);
  1604. } else if (is_type_map(t)) {
  1605. return lb_map_len(p, v);
  1606. } else if (is_type_soa_struct(t)) {
  1607. return lb_soa_struct_len(p, v);
  1608. }
  1609. GB_PANIC("Unreachable");
  1610. break;
  1611. }
  1612. case BuiltinProc_cap: {
  1613. lbValue v = lb_build_expr(p, ce->args[0]);
  1614. Type *t = base_type(v.type);
  1615. if (is_type_pointer(t)) {
  1616. v = lb_emit_load(p, v);
  1617. t = type_deref(t);
  1618. }
  1619. if (is_type_string(t)) {
  1620. GB_PANIC("Unreachable");
  1621. } else if (is_type_array(t)) {
  1622. GB_PANIC("Array lengths are constant");
  1623. } else if (is_type_slice(t)) {
  1624. return lb_slice_len(p, v);
  1625. } else if (is_type_dynamic_array(t)) {
  1626. return lb_dynamic_array_cap(p, v);
  1627. } else if (is_type_map(t)) {
  1628. return lb_map_cap(p, v);
  1629. } else if (is_type_soa_struct(t)) {
  1630. return lb_soa_struct_cap(p, v);
  1631. }
  1632. GB_PANIC("Unreachable");
  1633. break;
  1634. }
  1635. case BuiltinProc_swizzle: {
  1636. isize index_count = ce->args.count-1;
  1637. if (is_type_simd_vector(tv.type)) {
  1638. lbValue vec = lb_build_expr(p, ce->args[0]);
  1639. if (index_count == 0) {
  1640. return vec;
  1641. }
  1642. unsigned mask_len = cast(unsigned)index_count;
  1643. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  1644. for (isize i = 1; i < ce->args.count; i++) {
  1645. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  1646. GB_ASSERT(is_type_integer(tv.type));
  1647. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  1648. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  1649. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  1650. }
  1651. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  1652. LLVMValueRef v1 = vec.value;
  1653. LLVMValueRef v2 = vec.value;
  1654. lbValue res = {};
  1655. res.type = tv.type;
  1656. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  1657. return res;
  1658. }
  1659. lbAddr addr = lb_build_array_swizzle_addr(p, ce, tv);
  1660. return lb_addr_load(p, addr);
  1661. }
  1662. case BuiltinProc_complex: {
  1663. lbValue real = lb_build_expr(p, ce->args[0]);
  1664. lbValue imag = lb_build_expr(p, ce->args[1]);
  1665. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1666. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1667. Type *ft = base_complex_elem_type(tv.type);
  1668. real = lb_emit_conv(p, real, ft);
  1669. imag = lb_emit_conv(p, imag, ft);
  1670. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  1671. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  1672. return lb_emit_load(p, dst);
  1673. }
  1674. case BuiltinProc_quaternion: {
  1675. lbValue xyzw[4] = {};
  1676. for (i32 i = 0; i < 4; i++) {
  1677. ast_node(f, FieldValue, ce->args[i]);
  1678. GB_ASSERT(f->field->kind == Ast_Ident);
  1679. String name = f->field->Ident.token.string;
  1680. i32 index = -1;
  1681. // @QuaternionLayout
  1682. if (name == "x" || name == "imag") {
  1683. index = 0;
  1684. } else if (name == "y" || name == "jmag") {
  1685. index = 1;
  1686. } else if (name == "z" || name == "kmag") {
  1687. index = 2;
  1688. } else if (name == "w" || name == "real") {
  1689. index = 3;
  1690. }
  1691. GB_ASSERT(index >= 0);
  1692. xyzw[index] = lb_build_expr(p, f->value);
  1693. }
  1694. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1695. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1696. Type *ft = base_complex_elem_type(tv.type);
  1697. xyzw[0] = lb_emit_conv(p, xyzw[0], ft);
  1698. xyzw[1] = lb_emit_conv(p, xyzw[1], ft);
  1699. xyzw[2] = lb_emit_conv(p, xyzw[2], ft);
  1700. xyzw[3] = lb_emit_conv(p, xyzw[3], ft);
  1701. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), xyzw[0]);
  1702. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), xyzw[1]);
  1703. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), xyzw[2]);
  1704. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), xyzw[3]);
  1705. return lb_emit_load(p, dst);
  1706. }
  1707. case BuiltinProc_real: {
  1708. lbValue val = lb_build_expr(p, ce->args[0]);
  1709. if (is_type_complex(val.type)) {
  1710. lbValue real = lb_emit_struct_ev(p, val, 0);
  1711. return lb_emit_conv(p, real, tv.type);
  1712. } else if (is_type_quaternion(val.type)) {
  1713. // @QuaternionLayout
  1714. lbValue real = lb_emit_struct_ev(p, val, 3);
  1715. return lb_emit_conv(p, real, tv.type);
  1716. }
  1717. GB_PANIC("invalid type for real");
  1718. return {};
  1719. }
  1720. case BuiltinProc_imag: {
  1721. lbValue val = lb_build_expr(p, ce->args[0]);
  1722. if (is_type_complex(val.type)) {
  1723. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1724. return lb_emit_conv(p, imag, tv.type);
  1725. } else if (is_type_quaternion(val.type)) {
  1726. // @QuaternionLayout
  1727. lbValue imag = lb_emit_struct_ev(p, val, 0);
  1728. return lb_emit_conv(p, imag, tv.type);
  1729. }
  1730. GB_PANIC("invalid type for imag");
  1731. return {};
  1732. }
  1733. case BuiltinProc_jmag: {
  1734. lbValue val = lb_build_expr(p, ce->args[0]);
  1735. if (is_type_quaternion(val.type)) {
  1736. // @QuaternionLayout
  1737. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1738. return lb_emit_conv(p, imag, tv.type);
  1739. }
  1740. GB_PANIC("invalid type for jmag");
  1741. return {};
  1742. }
  1743. case BuiltinProc_kmag: {
  1744. lbValue val = lb_build_expr(p, ce->args[0]);
  1745. if (is_type_quaternion(val.type)) {
  1746. // @QuaternionLayout
  1747. lbValue imag = lb_emit_struct_ev(p, val, 2);
  1748. return lb_emit_conv(p, imag, tv.type);
  1749. }
  1750. GB_PANIC("invalid type for kmag");
  1751. return {};
  1752. }
  1753. case BuiltinProc_conj: {
  1754. lbValue val = lb_build_expr(p, ce->args[0]);
  1755. return lb_emit_conjugate(p, val, tv.type);
  1756. }
  1757. case BuiltinProc_expand_values: {
  1758. lbValue val = lb_build_expr(p, ce->args[0]);
  1759. Type *t = base_type(val.type);
  1760. if (!is_type_tuple(tv.type)) {
  1761. if (t->kind == Type_Struct) {
  1762. GB_ASSERT(t->Struct.fields.count == 1);
  1763. return lb_emit_struct_ev(p, val, 0);
  1764. } else if (t->kind == Type_Array) {
  1765. GB_ASSERT(t->Array.count == 1);
  1766. return lb_emit_struct_ev(p, val, 0);
  1767. } else {
  1768. GB_PANIC("Unknown type of expand_values");
  1769. }
  1770. }
  1771. GB_ASSERT(is_type_tuple(tv.type));
  1772. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1773. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  1774. if (t->kind == Type_Struct) {
  1775. for_array(src_index, t->Struct.fields) {
  1776. Entity *field = t->Struct.fields[src_index];
  1777. i32 field_index = field->Variable.field_index;
  1778. lbValue f = lb_emit_struct_ev(p, val, field_index);
  1779. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  1780. lb_emit_store(p, ep, f);
  1781. }
  1782. } else if (is_type_array_like(t)) {
  1783. // TODO(bill): Clean-up this code
  1784. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  1785. i32 n = cast(i32)get_array_type_count(t);
  1786. for (i32 i = 0; i < n; i++) {
  1787. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  1788. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  1789. lb_emit_store(p, ep, f);
  1790. }
  1791. } else {
  1792. GB_PANIC("Unknown type of expand_values");
  1793. }
  1794. return lb_emit_load(p, tuple);
  1795. }
  1796. case BuiltinProc_min: {
  1797. Type *t = type_of_expr(expr);
  1798. if (ce->args.count == 2) {
  1799. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1800. } else {
  1801. lbValue x = lb_build_expr(p, ce->args[0]);
  1802. for (isize i = 1; i < ce->args.count; i++) {
  1803. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  1804. }
  1805. return x;
  1806. }
  1807. }
  1808. case BuiltinProc_max: {
  1809. Type *t = type_of_expr(expr);
  1810. if (ce->args.count == 2) {
  1811. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1812. } else {
  1813. lbValue x = lb_build_expr(p, ce->args[0]);
  1814. for (isize i = 1; i < ce->args.count; i++) {
  1815. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  1816. }
  1817. return x;
  1818. }
  1819. }
  1820. case BuiltinProc_abs: {
  1821. lbValue x = lb_build_expr(p, ce->args[0]);
  1822. Type *t = x.type;
  1823. if (is_type_unsigned(t)) {
  1824. return x;
  1825. }
  1826. if (is_type_quaternion(t)) {
  1827. i64 sz = 8*type_size_of(t);
  1828. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1829. args[0] = x;
  1830. switch (sz) {
  1831. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  1832. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  1833. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  1834. }
  1835. GB_PANIC("Unknown complex type");
  1836. } else if (is_type_complex(t)) {
  1837. i64 sz = 8*type_size_of(t);
  1838. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1839. args[0] = x;
  1840. switch (sz) {
  1841. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  1842. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  1843. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  1844. }
  1845. GB_PANIC("Unknown complex type");
  1846. }
  1847. lbValue zero = lb_const_nil(p->module, t);
  1848. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  1849. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  1850. return lb_emit_select(p, cond, neg, x);
  1851. }
  1852. case BuiltinProc_clamp:
  1853. return lb_emit_clamp(p, type_of_expr(expr),
  1854. lb_build_expr(p, ce->args[0]),
  1855. lb_build_expr(p, ce->args[1]),
  1856. lb_build_expr(p, ce->args[2]));
  1857. case BuiltinProc_soa_zip:
  1858. return lb_soa_zip(p, ce, tv);
  1859. case BuiltinProc_soa_unzip:
  1860. return lb_soa_unzip(p, ce, tv);
  1861. case BuiltinProc_transpose:
  1862. {
  1863. lbValue m = lb_build_expr(p, ce->args[0]);
  1864. return lb_emit_matrix_tranpose(p, m, tv.type);
  1865. }
  1866. case BuiltinProc_outer_product:
  1867. {
  1868. lbValue a = lb_build_expr(p, ce->args[0]);
  1869. lbValue b = lb_build_expr(p, ce->args[1]);
  1870. return lb_emit_outer_product(p, a, b, tv.type);
  1871. }
  1872. case BuiltinProc_hadamard_product:
  1873. {
  1874. lbValue a = lb_build_expr(p, ce->args[0]);
  1875. lbValue b = lb_build_expr(p, ce->args[1]);
  1876. if (is_type_array(tv.type)) {
  1877. return lb_emit_arith(p, Token_Mul, a, b, tv.type);
  1878. }
  1879. GB_ASSERT(is_type_matrix(tv.type));
  1880. return lb_emit_arith_matrix(p, Token_Mul, a, b, tv.type, true);
  1881. }
  1882. case BuiltinProc_matrix_flatten:
  1883. {
  1884. lbValue m = lb_build_expr(p, ce->args[0]);
  1885. return lb_emit_matrix_flatten(p, m, tv.type);
  1886. }
  1887. case BuiltinProc_unreachable:
  1888. lb_emit_unreachable(p);
  1889. return {};
  1890. case BuiltinProc_raw_data:
  1891. {
  1892. lbValue x = lb_build_expr(p, ce->args[0]);
  1893. Type *t = base_type(x.type);
  1894. lbValue res = {};
  1895. switch (t->kind) {
  1896. case Type_Slice:
  1897. res = lb_slice_elem(p, x);
  1898. res = lb_emit_conv(p, res, tv.type);
  1899. break;
  1900. case Type_DynamicArray:
  1901. res = lb_dynamic_array_elem(p, x);
  1902. res = lb_emit_conv(p, res, tv.type);
  1903. break;
  1904. case Type_Basic:
  1905. if (t->Basic.kind == Basic_string) {
  1906. res = lb_string_elem(p, x);
  1907. res = lb_emit_conv(p, res, tv.type);
  1908. } else if (t->Basic.kind == Basic_cstring) {
  1909. res = lb_emit_conv(p, x, tv.type);
  1910. }
  1911. break;
  1912. case Type_Pointer:
  1913. case Type_MultiPointer:
  1914. res = lb_emit_conv(p, x, tv.type);
  1915. break;
  1916. }
  1917. GB_ASSERT(res.value != nullptr);
  1918. return res;
  1919. }
  1920. // "Intrinsics"
  1921. case BuiltinProc_alloca:
  1922. {
  1923. lbValue sz = lb_build_expr(p, ce->args[0]);
  1924. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  1925. lbValue res = {};
  1926. res.type = alloc_type_multi_pointer(t_u8);
  1927. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  1928. LLVMSetAlignment(res.value, cast(unsigned)al);
  1929. return res;
  1930. }
  1931. case BuiltinProc_cpu_relax:
  1932. if (build_context.metrics.arch == TargetArch_i386 ||
  1933. build_context.metrics.arch == TargetArch_amd64) {
  1934. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1935. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("pause"), {}, true);
  1936. GB_ASSERT(the_asm != nullptr);
  1937. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1938. } else if (build_context.metrics.arch == TargetArch_arm64) {
  1939. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1940. // NOTE(bill, 2022-03-30): `isb` appears to a better option that `yield`
  1941. // See: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8258604
  1942. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("isb"), {}, true);
  1943. GB_ASSERT(the_asm != nullptr);
  1944. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1945. } else {
  1946. // NOTE: default to something to prevent optimization
  1947. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1948. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit(""), {}, true);
  1949. GB_ASSERT(the_asm != nullptr);
  1950. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1951. }
  1952. return {};
  1953. case BuiltinProc_debug_trap:
  1954. case BuiltinProc_trap:
  1955. {
  1956. char const *name = nullptr;
  1957. switch (id) {
  1958. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  1959. case BuiltinProc_trap: name = "llvm.trap"; break;
  1960. }
  1961. lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1962. if (id == BuiltinProc_trap) {
  1963. LLVMBuildUnreachable(p->builder);
  1964. }
  1965. return {};
  1966. }
  1967. case BuiltinProc_read_cycle_counter:
  1968. {
  1969. lbValue res = {};
  1970. res.type = tv.type;
  1971. if (build_context.metrics.arch == TargetArch_arm64) {
  1972. LLVMTypeRef func_type = LLVMFunctionType(LLVMInt64TypeInContext(p->module->ctx), nullptr, 0, false);
  1973. bool has_side_effects = false;
  1974. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("mrs $0, cntvct_el0"), str_lit("=r"), has_side_effects);
  1975. GB_ASSERT(the_asm != nullptr);
  1976. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1977. } else {
  1978. char const *name = "llvm.readcyclecounter";
  1979. res.value = lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1980. }
  1981. return res;
  1982. }
  1983. case BuiltinProc_count_trailing_zeros:
  1984. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1985. case BuiltinProc_count_leading_zeros:
  1986. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1987. case BuiltinProc_count_ones:
  1988. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  1989. case BuiltinProc_count_zeros:
  1990. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1991. case BuiltinProc_reverse_bits:
  1992. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  1993. case BuiltinProc_byte_swap:
  1994. {
  1995. lbValue x = lb_build_expr(p, ce->args[0]);
  1996. x = lb_emit_conv(p, x, tv.type);
  1997. return lb_emit_byte_swap(p, x, tv.type);
  1998. }
  1999. case BuiltinProc_overflow_add:
  2000. case BuiltinProc_overflow_sub:
  2001. case BuiltinProc_overflow_mul:
  2002. {
  2003. Type *main_type = tv.type;
  2004. Type *type = main_type;
  2005. if (is_type_tuple(main_type)) {
  2006. type = main_type->Tuple.variables[0]->type;
  2007. }
  2008. lbValue x = lb_build_expr(p, ce->args[0]);
  2009. lbValue y = lb_build_expr(p, ce->args[1]);
  2010. x = lb_emit_conv(p, x, type);
  2011. y = lb_emit_conv(p, y, type);
  2012. char const *name = nullptr;
  2013. if (is_type_unsigned(type)) {
  2014. switch (id) {
  2015. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  2016. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  2017. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  2018. }
  2019. } else {
  2020. switch (id) {
  2021. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  2022. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  2023. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  2024. }
  2025. }
  2026. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  2027. LLVMValueRef args[2] = { x.value, y.value };
  2028. lbValue res = {};
  2029. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2030. if (is_type_tuple(main_type)) {
  2031. Type *res_type = nullptr;
  2032. gbAllocator a = permanent_allocator();
  2033. res_type = alloc_type_tuple();
  2034. slice_init(&res_type->Tuple.variables, a, 2);
  2035. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  2036. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  2037. res.type = res_type;
  2038. } else {
  2039. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  2040. res.type = type;
  2041. }
  2042. return res;
  2043. }
  2044. case BuiltinProc_saturating_add:
  2045. case BuiltinProc_saturating_sub:
  2046. {
  2047. Type *main_type = tv.type;
  2048. Type *type = main_type;
  2049. lbValue x = lb_build_expr(p, ce->args[0]);
  2050. lbValue y = lb_build_expr(p, ce->args[1]);
  2051. x = lb_emit_conv(p, x, type);
  2052. y = lb_emit_conv(p, y, type);
  2053. char const *name = nullptr;
  2054. if (is_type_unsigned(type)) {
  2055. switch (id) {
  2056. case BuiltinProc_saturating_add: name = "llvm.uadd.sat"; break;
  2057. case BuiltinProc_saturating_sub: name = "llvm.usub.sat"; break;
  2058. }
  2059. } else {
  2060. switch (id) {
  2061. case BuiltinProc_saturating_add: name = "llvm.sadd.sat"; break;
  2062. case BuiltinProc_saturating_sub: name = "llvm.ssub.sat"; break;
  2063. }
  2064. }
  2065. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  2066. LLVMValueRef args[2] = { x.value, y.value };
  2067. lbValue res = {};
  2068. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2069. res.type = type;
  2070. return res;
  2071. }
  2072. case BuiltinProc_sqrt:
  2073. {
  2074. Type *type = tv.type;
  2075. lbValue x = lb_build_expr(p, ce->args[0]);
  2076. x = lb_emit_conv(p, x, type);
  2077. char const *name = "llvm.sqrt";
  2078. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  2079. LLVMValueRef args[1] = { x.value };
  2080. lbValue res = {};
  2081. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2082. res.type = type;
  2083. return res;
  2084. }
  2085. case BuiltinProc_fused_mul_add:
  2086. {
  2087. Type *type = tv.type;
  2088. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), type);
  2089. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), type);
  2090. lbValue z = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), type);
  2091. char const *name = "llvm.fma";
  2092. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  2093. LLVMValueRef args[3] = { x.value, y.value, z.value };
  2094. lbValue res = {};
  2095. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2096. res.type = type;
  2097. return res;
  2098. }
  2099. case BuiltinProc_mem_copy:
  2100. {
  2101. lbValue dst = lb_build_expr(p, ce->args[0]);
  2102. lbValue src = lb_build_expr(p, ce->args[1]);
  2103. lbValue len = lb_build_expr(p, ce->args[2]);
  2104. lb_mem_copy_overlapping(p, dst, src, len, false);
  2105. return {};
  2106. }
  2107. case BuiltinProc_mem_copy_non_overlapping:
  2108. {
  2109. lbValue dst = lb_build_expr(p, ce->args[0]);
  2110. lbValue src = lb_build_expr(p, ce->args[1]);
  2111. lbValue len = lb_build_expr(p, ce->args[2]);
  2112. lb_mem_copy_non_overlapping(p, dst, src, len, false);
  2113. return {};
  2114. }
  2115. case BuiltinProc_mem_zero:
  2116. {
  2117. lbValue ptr = lb_build_expr(p, ce->args[0]);
  2118. lbValue len = lb_build_expr(p, ce->args[1]);
  2119. ptr = lb_emit_conv(p, ptr, t_rawptr);
  2120. len = lb_emit_conv(p, len, t_int);
  2121. unsigned alignment = 1;
  2122. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, false);
  2123. return {};
  2124. }
  2125. case BuiltinProc_mem_zero_volatile:
  2126. {
  2127. lbValue ptr = lb_build_expr(p, ce->args[0]);
  2128. lbValue len = lb_build_expr(p, ce->args[1]);
  2129. ptr = lb_emit_conv(p, ptr, t_rawptr);
  2130. len = lb_emit_conv(p, len, t_int);
  2131. unsigned alignment = 1;
  2132. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, true);
  2133. return {};
  2134. }
  2135. case BuiltinProc_ptr_offset:
  2136. {
  2137. lbValue ptr = lb_build_expr(p, ce->args[0]);
  2138. lbValue len = lb_build_expr(p, ce->args[1]);
  2139. len = lb_emit_conv(p, len, t_int);
  2140. return lb_emit_ptr_offset(p, ptr, len);
  2141. }
  2142. case BuiltinProc_ptr_sub:
  2143. {
  2144. Type *elem0 = type_deref(type_of_expr(ce->args[0]));
  2145. Type *elem1 = type_deref(type_of_expr(ce->args[1]));
  2146. GB_ASSERT(are_types_identical(elem0, elem1));
  2147. Type *elem = elem0;
  2148. lbValue ptr0 = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr);
  2149. lbValue ptr1 = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr);
  2150. ptr0 = lb_emit_conv(p, ptr0, t_int);
  2151. ptr1 = lb_emit_conv(p, ptr1, t_int);
  2152. lbValue diff = lb_emit_arith(p, Token_Sub, ptr0, ptr1, t_int);
  2153. return lb_emit_arith(p, Token_Quo, diff, lb_const_int(p->module, t_int, type_size_of(elem)), t_int);
  2154. }
  2155. // TODO(bill): Which is correct?
  2156. case BuiltinProc_atomic_thread_fence:
  2157. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), false, "");
  2158. return {};
  2159. case BuiltinProc_atomic_signal_fence:
  2160. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), true, "");
  2161. return {};
  2162. case BuiltinProc_volatile_store:
  2163. case BuiltinProc_non_temporal_store:
  2164. case BuiltinProc_atomic_store:
  2165. case BuiltinProc_atomic_store_explicit: {
  2166. lbValue dst = lb_build_expr(p, ce->args[0]);
  2167. lbValue val = lb_build_expr(p, ce->args[1]);
  2168. val = lb_emit_conv(p, val, type_deref(dst.type));
  2169. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  2170. switch (id) {
  2171. case BuiltinProc_non_temporal_store:
  2172. {
  2173. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  2174. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  2175. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  2176. }
  2177. break;
  2178. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  2179. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  2180. case BuiltinProc_atomic_store_explicit:
  2181. {
  2182. auto ordering = llvm_atomic_ordering_from_odin(ce->args[2]);
  2183. LLVMSetOrdering(instr, ordering);
  2184. if (ordering == LLVMAtomicOrderingUnordered) {
  2185. LLVMSetVolatile(instr, true);
  2186. }
  2187. }
  2188. break;
  2189. }
  2190. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2191. return {};
  2192. }
  2193. case BuiltinProc_volatile_load:
  2194. case BuiltinProc_non_temporal_load:
  2195. case BuiltinProc_atomic_load:
  2196. case BuiltinProc_atomic_load_explicit: {
  2197. lbValue dst = lb_build_expr(p, ce->args[0]);
  2198. LLVMValueRef instr = OdinLLVMBuildLoad(p, lb_type(p->module, type_deref(dst.type)), dst.value);
  2199. switch (id) {
  2200. case BuiltinProc_non_temporal_load:
  2201. {
  2202. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  2203. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  2204. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  2205. }
  2206. break;
  2207. break;
  2208. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  2209. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  2210. case BuiltinProc_atomic_load_explicit:
  2211. {
  2212. auto ordering = llvm_atomic_ordering_from_odin(ce->args[1]);
  2213. LLVMSetOrdering(instr, ordering);
  2214. if (ordering == LLVMAtomicOrderingUnordered) {
  2215. LLVMSetVolatile(instr, true);
  2216. }
  2217. }
  2218. break;
  2219. }
  2220. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2221. lbValue res = {};
  2222. res.value = instr;
  2223. res.type = type_deref(dst.type);
  2224. return res;
  2225. }
  2226. case BuiltinProc_unaligned_store:
  2227. {
  2228. lbValue dst = lb_build_expr(p, ce->args[0]);
  2229. lbValue src = lb_build_expr(p, ce->args[1]);
  2230. Type *t = type_deref(dst.type);
  2231. if (is_type_simd_vector(t)) {
  2232. LLVMValueRef store = LLVMBuildStore(p->builder, src.value, dst.value);
  2233. LLVMSetAlignment(store, 1);
  2234. } else {
  2235. src = lb_address_from_load_or_generate_local(p, src);
  2236. lb_mem_copy_non_overlapping(p, dst, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2237. }
  2238. return {};
  2239. }
  2240. case BuiltinProc_unaligned_load:
  2241. {
  2242. lbValue src = lb_build_expr(p, ce->args[0]);
  2243. Type *t = type_deref(src.type);
  2244. if (is_type_simd_vector(t)) {
  2245. lbValue res = {};
  2246. res.type = t;
  2247. res.value = OdinLLVMBuildLoadAligned(p, lb_type(p->module, t), src.value, 1);
  2248. return res;
  2249. } else {
  2250. lbAddr dst = lb_add_local_generated(p, t, false);
  2251. lb_mem_copy_non_overlapping(p, dst.addr, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2252. return lb_addr_load(p, dst);
  2253. }
  2254. }
  2255. case BuiltinProc_atomic_add:
  2256. case BuiltinProc_atomic_sub:
  2257. case BuiltinProc_atomic_and:
  2258. case BuiltinProc_atomic_nand:
  2259. case BuiltinProc_atomic_or:
  2260. case BuiltinProc_atomic_xor:
  2261. case BuiltinProc_atomic_exchange:
  2262. case BuiltinProc_atomic_add_explicit:
  2263. case BuiltinProc_atomic_sub_explicit:
  2264. case BuiltinProc_atomic_and_explicit:
  2265. case BuiltinProc_atomic_nand_explicit:
  2266. case BuiltinProc_atomic_or_explicit:
  2267. case BuiltinProc_atomic_xor_explicit:
  2268. case BuiltinProc_atomic_exchange_explicit: {
  2269. lbValue dst = lb_build_expr(p, ce->args[0]);
  2270. lbValue val = lb_build_expr(p, ce->args[1]);
  2271. val = lb_emit_conv(p, val, type_deref(dst.type));
  2272. LLVMAtomicRMWBinOp op = {};
  2273. LLVMAtomicOrdering ordering = {};
  2274. switch (id) {
  2275. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2276. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2277. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2278. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2279. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2280. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2281. case BuiltinProc_atomic_exchange: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2282. case BuiltinProc_atomic_add_explicit: op = LLVMAtomicRMWBinOpAdd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2283. case BuiltinProc_atomic_sub_explicit: op = LLVMAtomicRMWBinOpSub; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2284. case BuiltinProc_atomic_and_explicit: op = LLVMAtomicRMWBinOpAnd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2285. case BuiltinProc_atomic_nand_explicit: op = LLVMAtomicRMWBinOpNand; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2286. case BuiltinProc_atomic_or_explicit: op = LLVMAtomicRMWBinOpOr; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2287. case BuiltinProc_atomic_xor_explicit: op = LLVMAtomicRMWBinOpXor; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2288. case BuiltinProc_atomic_exchange_explicit: op = LLVMAtomicRMWBinOpXchg; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2289. }
  2290. lbValue res = {};
  2291. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  2292. res.type = tv.type;
  2293. if (ordering == LLVMAtomicOrderingUnordered) {
  2294. LLVMSetVolatile(res.value, true);
  2295. }
  2296. return res;
  2297. }
  2298. case BuiltinProc_atomic_compare_exchange_strong:
  2299. case BuiltinProc_atomic_compare_exchange_weak:
  2300. case BuiltinProc_atomic_compare_exchange_strong_explicit:
  2301. case BuiltinProc_atomic_compare_exchange_weak_explicit: {
  2302. lbValue address = lb_build_expr(p, ce->args[0]);
  2303. Type *elem = type_deref(address.type);
  2304. lbValue old_value = lb_build_expr(p, ce->args[1]);
  2305. lbValue new_value = lb_build_expr(p, ce->args[2]);
  2306. old_value = lb_emit_conv(p, old_value, elem);
  2307. new_value = lb_emit_conv(p, new_value, elem);
  2308. LLVMAtomicOrdering success_ordering = {};
  2309. LLVMAtomicOrdering failure_ordering = {};
  2310. LLVMBool weak = false;
  2311. switch (id) {
  2312. case BuiltinProc_atomic_compare_exchange_strong: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  2313. case BuiltinProc_atomic_compare_exchange_weak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  2314. case BuiltinProc_atomic_compare_exchange_strong_explicit: success_ordering = llvm_atomic_ordering_from_odin(ce->args[3]); failure_ordering = llvm_atomic_ordering_from_odin(ce->args[4]); weak = false; break;
  2315. case BuiltinProc_atomic_compare_exchange_weak_explicit: success_ordering = llvm_atomic_ordering_from_odin(ce->args[3]); failure_ordering = llvm_atomic_ordering_from_odin(ce->args[4]); weak = true; break;
  2316. }
  2317. LLVMBool single_threaded = false;
  2318. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  2319. p->builder, address.value,
  2320. old_value.value, new_value.value,
  2321. success_ordering,
  2322. failure_ordering,
  2323. single_threaded
  2324. );
  2325. LLVMSetWeak(value, weak);
  2326. if (success_ordering == LLVMAtomicOrderingUnordered || failure_ordering == LLVMAtomicOrderingUnordered) {
  2327. LLVMSetVolatile(value, true);
  2328. }
  2329. if (is_type_tuple(tv.type)) {
  2330. Type *fix_typed = alloc_type_tuple();
  2331. slice_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  2332. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  2333. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  2334. lbValue res = {};
  2335. res.value = value;
  2336. res.type = fix_typed;
  2337. return res;
  2338. } else {
  2339. lbValue res = {};
  2340. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  2341. res.type = tv.type;
  2342. return res;
  2343. }
  2344. }
  2345. case BuiltinProc_type_equal_proc:
  2346. return lb_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  2347. case BuiltinProc_type_hasher_proc:
  2348. return lb_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  2349. case BuiltinProc_type_map_info:
  2350. return lb_gen_map_info_ptr(p->module, ce->args[0]->tav.type);
  2351. case BuiltinProc_type_map_cell_info:
  2352. return lb_gen_map_cell_info_ptr(p->module, ce->args[0]->tav.type);
  2353. case BuiltinProc_fixed_point_mul:
  2354. case BuiltinProc_fixed_point_div:
  2355. case BuiltinProc_fixed_point_mul_sat:
  2356. case BuiltinProc_fixed_point_div_sat:
  2357. {
  2358. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  2359. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  2360. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  2361. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  2362. char const *name = nullptr;
  2363. if (is_type_unsigned(tv.type)) {
  2364. switch (id) {
  2365. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  2366. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  2367. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  2368. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  2369. }
  2370. } else {
  2371. switch (id) {
  2372. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  2373. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  2374. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  2375. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  2376. }
  2377. }
  2378. GB_ASSERT(name != nullptr);
  2379. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  2380. lbValue res = {};
  2381. LLVMValueRef args[3] = {
  2382. x.value,
  2383. y.value,
  2384. scale.value };
  2385. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2386. res.type = platform_type;
  2387. return lb_emit_conv(p, res, tv.type);
  2388. }
  2389. case BuiltinProc_expect:
  2390. {
  2391. Type *t = default_type(tv.type);
  2392. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  2393. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  2394. char const *name = "llvm.expect";
  2395. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  2396. lbValue res = {};
  2397. LLVMValueRef args[2] = { x.value, y.value };
  2398. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2399. res.type = t;
  2400. return lb_emit_conv(p, res, t);
  2401. }
  2402. case BuiltinProc_prefetch_read_instruction:
  2403. case BuiltinProc_prefetch_read_data:
  2404. case BuiltinProc_prefetch_write_instruction:
  2405. case BuiltinProc_prefetch_write_data:
  2406. {
  2407. lbValue ptr = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_rawptr);
  2408. unsigned long long locality = cast(unsigned long long)exact_value_to_i64(ce->args[1]->tav.value);
  2409. unsigned long long rw = 0;
  2410. unsigned long long cache = 0;
  2411. switch (id) {
  2412. case BuiltinProc_prefetch_read_instruction:
  2413. rw = 0;
  2414. cache = 0;
  2415. break;
  2416. case BuiltinProc_prefetch_read_data:
  2417. rw = 0;
  2418. cache = 1;
  2419. break;
  2420. case BuiltinProc_prefetch_write_instruction:
  2421. rw = 1;
  2422. cache = 0;
  2423. break;
  2424. case BuiltinProc_prefetch_write_data:
  2425. rw = 1;
  2426. cache = 1;
  2427. break;
  2428. }
  2429. char const *name = "llvm.prefetch";
  2430. LLVMTypeRef types[1] = {lb_type(p->module, t_rawptr)};
  2431. LLVMTypeRef llvm_i32 = lb_type(p->module, t_i32);
  2432. LLVMValueRef args[4] = {};
  2433. args[0] = ptr.value;
  2434. args[1] = LLVMConstInt(llvm_i32, rw, false);
  2435. args[2] = LLVMConstInt(llvm_i32, locality, false);
  2436. args[3] = LLVMConstInt(llvm_i32, cache, false);
  2437. lbValue res = {};
  2438. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2439. res.type = nullptr;
  2440. return res;
  2441. }
  2442. case BuiltinProc___entry_point:
  2443. if (p->module->info->entry_point) {
  2444. lbValue entry_point = lb_find_procedure_value_from_entity(p->module, p->module->info->entry_point);
  2445. GB_ASSERT(entry_point.value != nullptr);
  2446. lb_emit_call(p, entry_point, {});
  2447. }
  2448. return {};
  2449. case BuiltinProc_syscall:
  2450. {
  2451. unsigned arg_count = cast(unsigned)ce->args.count;
  2452. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  2453. for_array(i, ce->args) {
  2454. lbValue arg = lb_build_expr(p, ce->args[i]);
  2455. arg = lb_emit_conv(p, arg, t_uintptr);
  2456. args[i] = arg.value;
  2457. }
  2458. LLVMTypeRef llvm_uintptr = lb_type(p->module, t_uintptr);
  2459. LLVMTypeRef *llvm_arg_types = gb_alloc_array(permanent_allocator(), LLVMTypeRef, arg_count);
  2460. for (unsigned i = 0; i < arg_count; i++) {
  2461. llvm_arg_types[i] = llvm_uintptr;
  2462. }
  2463. LLVMTypeRef func_type = LLVMFunctionType(llvm_uintptr, llvm_arg_types, arg_count, false);
  2464. LLVMValueRef inline_asm = nullptr;
  2465. switch (build_context.metrics.arch) {
  2466. case TargetArch_riscv64:
  2467. {
  2468. GB_ASSERT(arg_count <= 7);
  2469. char asm_string[] = "ecall";
  2470. gbString constraints = gb_string_make(heap_allocator(), "={a0}");
  2471. for (unsigned i = 0; i < arg_count; i++) {
  2472. constraints = gb_string_appendc(constraints, ",{");
  2473. static char const *regs[] = {
  2474. "a7",
  2475. "a0",
  2476. "a1",
  2477. "a2",
  2478. "a3",
  2479. "a4",
  2480. "a5",
  2481. "a6"
  2482. };
  2483. constraints = gb_string_appendc(constraints, regs[i]);
  2484. constraints = gb_string_appendc(constraints, "}");
  2485. }
  2486. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2487. }
  2488. break;
  2489. case TargetArch_amd64:
  2490. {
  2491. GB_ASSERT(arg_count <= 7);
  2492. char asm_string[] = "syscall";
  2493. gbString constraints = gb_string_make(heap_allocator(), "={rax}");
  2494. for (unsigned i = 0; i < arg_count; i++) {
  2495. constraints = gb_string_appendc(constraints, ",{");
  2496. static char const *regs[] = {
  2497. "rax",
  2498. "rdi",
  2499. "rsi",
  2500. "rdx",
  2501. "r10",
  2502. "r8",
  2503. "r9"
  2504. };
  2505. constraints = gb_string_appendc(constraints, regs[i]);
  2506. constraints = gb_string_appendc(constraints, "}");
  2507. }
  2508. // The SYSCALL instruction stores the address of the
  2509. // following instruction into RCX, and RFLAGS in R11.
  2510. //
  2511. // RSP is not saved, but at least on Linux it appears
  2512. // that the kernel system-call handler does the right
  2513. // thing.
  2514. //
  2515. // Some but not all system calls will additionally
  2516. // clobber memory.
  2517. //
  2518. // TODO:
  2519. // * Figure out what Darwin does.
  2520. constraints = gb_string_appendc(constraints, ",~{rcx},~{r11},~{memory}");
  2521. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2522. }
  2523. break;
  2524. case TargetArch_i386:
  2525. {
  2526. GB_ASSERT(arg_count <= 7);
  2527. char asm_string[] = "int $$0x80";
  2528. gbString constraints = gb_string_make(heap_allocator(), "={eax}");
  2529. for (unsigned i = 0; i < gb_min(arg_count, 6); i++) {
  2530. constraints = gb_string_appendc(constraints, ",{");
  2531. static char const *regs[] = {
  2532. "eax",
  2533. "ebx",
  2534. "ecx",
  2535. "edx",
  2536. "esi",
  2537. "edi",
  2538. "ebp",
  2539. };
  2540. constraints = gb_string_appendc(constraints, regs[i]);
  2541. constraints = gb_string_appendc(constraints, "}");
  2542. }
  2543. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2544. }
  2545. break;
  2546. case TargetArch_arm64:
  2547. {
  2548. GB_ASSERT(arg_count <= 7);
  2549. if(build_context.metrics.os == TargetOs_darwin) {
  2550. char asm_string[] = "svc #0x80";
  2551. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2552. for (unsigned i = 0; i < arg_count; i++) {
  2553. constraints = gb_string_appendc(constraints, ",{");
  2554. static char const *regs[] = {
  2555. "x16",
  2556. "x0",
  2557. "x1",
  2558. "x2",
  2559. "x3",
  2560. "x4",
  2561. "x5",
  2562. };
  2563. constraints = gb_string_appendc(constraints, regs[i]);
  2564. constraints = gb_string_appendc(constraints, "}");
  2565. }
  2566. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2567. } else {
  2568. char asm_string[] = "svc #0";
  2569. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2570. for (unsigned i = 0; i < arg_count; i++) {
  2571. constraints = gb_string_appendc(constraints, ",{");
  2572. static char const *regs[] = {
  2573. "x8",
  2574. "x0",
  2575. "x1",
  2576. "x2",
  2577. "x3",
  2578. "x4",
  2579. "x5",
  2580. };
  2581. constraints = gb_string_appendc(constraints, regs[i]);
  2582. constraints = gb_string_appendc(constraints, "}");
  2583. }
  2584. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2585. }
  2586. }
  2587. break;
  2588. case TargetArch_arm32:
  2589. {
  2590. GB_ASSERT(arg_count <= 7);
  2591. char asm_string[] = "svc #0";
  2592. gbString constraints = gb_string_make(heap_allocator(), "={r0}");
  2593. for (unsigned i = 0; i < arg_count; i++) {
  2594. constraints = gb_string_appendc(constraints, ",{");
  2595. static char const *regs[] = {
  2596. "r7",
  2597. "r0",
  2598. "r1",
  2599. "r2",
  2600. "r3",
  2601. "r4",
  2602. "r5",
  2603. "r6",
  2604. };
  2605. constraints = gb_string_appendc(constraints, regs[i]);
  2606. constraints = gb_string_appendc(constraints, "}");
  2607. }
  2608. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2609. }
  2610. break;
  2611. default:
  2612. GB_PANIC("Unsupported platform");
  2613. }
  2614. lbValue res = {};
  2615. res.value = LLVMBuildCall2(p->builder, func_type, inline_asm, args, arg_count, "");
  2616. res.type = t_uintptr;
  2617. return res;
  2618. }
  2619. case BuiltinProc_syscall_bsd:
  2620. {
  2621. // This is a BSD-style syscall where errors are indicated by a high
  2622. // Carry Flag and a positive return value, allowing the kernel to
  2623. // return any value that fits into a machine word.
  2624. //
  2625. // This is unlike Linux, where errors are indicated by a negative
  2626. // return value, limiting what can be expressed in one result.
  2627. unsigned arg_count = cast(unsigned)ce->args.count;
  2628. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  2629. for_array(i, ce->args) {
  2630. lbValue arg = lb_build_expr(p, ce->args[i]);
  2631. arg = lb_emit_conv(p, arg, t_uintptr);
  2632. args[i] = arg.value;
  2633. }
  2634. LLVMTypeRef llvm_uintptr = lb_type(p->module, t_uintptr);
  2635. LLVMTypeRef *llvm_arg_types = gb_alloc_array(permanent_allocator(), LLVMTypeRef, arg_count);
  2636. for (unsigned i = 0; i < arg_count; i++) {
  2637. llvm_arg_types[i] = llvm_uintptr;
  2638. }
  2639. LLVMTypeRef *results = gb_alloc_array(permanent_allocator(), LLVMTypeRef, 2);
  2640. results[0] = lb_type(p->module, t_uintptr);
  2641. results[1] = lb_type(p->module, t_bool);
  2642. LLVMTypeRef llvm_results = LLVMStructTypeInContext(p->module->ctx, results, 2, false);
  2643. LLVMTypeRef func_type = LLVMFunctionType(llvm_results, llvm_arg_types, arg_count, false);
  2644. LLVMValueRef inline_asm = nullptr;
  2645. switch (build_context.metrics.arch) {
  2646. case TargetArch_amd64:
  2647. {
  2648. GB_ASSERT(arg_count <= 7);
  2649. char asm_string[] = "syscall; setnb %cl";
  2650. // Using CL as an output; RCX doesn't need to get clobbered later.
  2651. gbString constraints = gb_string_make(heap_allocator(), "={rax},={cl}");
  2652. for (unsigned i = 0; i < arg_count; i++) {
  2653. constraints = gb_string_appendc(constraints, ",{");
  2654. static char const *regs[] = {
  2655. "rax",
  2656. "rdi",
  2657. "rsi",
  2658. "rdx",
  2659. "r10",
  2660. "r8",
  2661. "r9",
  2662. };
  2663. constraints = gb_string_appendc(constraints, regs[i]);
  2664. constraints = gb_string_appendc(constraints, "}");
  2665. }
  2666. // NOTE(Feoramund): If you're experiencing instability
  2667. // regarding syscalls during optimized builds, it is
  2668. // possible that the ABI has changed for your platform,
  2669. // or I've missed a register clobber.
  2670. //
  2671. // Documentation on this topic is sparse, but I was able to
  2672. // determine what registers were being clobbered by adding
  2673. // dummy values to them, setting a breakpoint after the
  2674. // syscall, and checking the state of the registers afterwards.
  2675. //
  2676. // Be advised that manually stepping through a debugger may
  2677. // cause the kernel to not return via sysret, which will
  2678. // preserve register state that normally would've been
  2679. // otherwise clobbered.
  2680. //
  2681. // It is also possible that some syscalls clobber different registers.
  2682. if (build_context.metrics.os == TargetOs_freebsd) {
  2683. // As a fix for CVE-2019-5595, FreeBSD started
  2684. // clobbering R8, R9, and R10, instead of restoring
  2685. // them.
  2686. //
  2687. // More info here:
  2688. //
  2689. // https://www.freebsd.org/security/advisories/FreeBSD-SA-19:01.syscall.asc
  2690. // https://github.com/freebsd/freebsd-src/blob/098dbd7ff7f3da9dda03802cdb2d8755f816eada/sys/amd64/amd64/exception.S#L605
  2691. // https://stackoverflow.com/q/66878250
  2692. constraints = gb_string_appendc(constraints, ",~{r8},~{r9},~{r10}");
  2693. }
  2694. // Both FreeBSD and NetBSD might clobber RDX.
  2695. //
  2696. // For NetBSD, it was clobbered during a call to sysctl.
  2697. //
  2698. // For FreeBSD, it's listed as "return value 2" in their
  2699. // AMD64 assembly, so there's no guarantee that it will persist.
  2700. constraints = gb_string_appendc(constraints, ",~{rdx},~{r11},~{cc},~{memory}");
  2701. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2702. }
  2703. break;
  2704. case TargetArch_arm64:
  2705. {
  2706. GB_ASSERT(arg_count <= 7);
  2707. char asm_string[] = "svc #0; cset x8, cc";
  2708. gbString constraints = gb_string_make(heap_allocator(), "={x0},={x8}");
  2709. for (unsigned i = 0; i < arg_count; i++) {
  2710. constraints = gb_string_appendc(constraints, ",{");
  2711. static char const *regs[] = {
  2712. "x8",
  2713. "x0",
  2714. "x1",
  2715. "x2",
  2716. "x3",
  2717. "x4",
  2718. "x5",
  2719. };
  2720. constraints = gb_string_appendc(constraints, regs[i]);
  2721. constraints = gb_string_appendc(constraints, "}");
  2722. }
  2723. // FreeBSD clobbered x1 on a call to sysctl.
  2724. constraints = gb_string_appendc(constraints, ",~{x1},~{cc},~{memory}");
  2725. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2726. }
  2727. break;
  2728. default:
  2729. GB_PANIC("Unsupported platform");
  2730. }
  2731. lbValue res = {};
  2732. res.value = LLVMBuildCall2(p->builder, func_type, inline_asm, args, arg_count, "");
  2733. res.type = make_optional_ok_type(t_uintptr, true);
  2734. return res;
  2735. }
  2736. case BuiltinProc_objc_send:
  2737. return lb_handle_objc_send(p, expr);
  2738. case BuiltinProc_objc_find_selector: return lb_handle_objc_find_selector(p, expr);
  2739. case BuiltinProc_objc_find_class: return lb_handle_objc_find_class(p, expr);
  2740. case BuiltinProc_objc_register_selector: return lb_handle_objc_register_selector(p, expr);
  2741. case BuiltinProc_objc_register_class: return lb_handle_objc_register_class(p, expr);
  2742. case BuiltinProc_constant_utf16_cstring:
  2743. {
  2744. auto const encode_surrogate_pair = [](Rune r, u16 *r1, u16 *r2) {
  2745. if (r < 0x10000 || r > 0x10ffff) {
  2746. *r1 = 0xfffd;
  2747. *r2 = 0xfffd;
  2748. } else {
  2749. r -= 0x10000;
  2750. *r1 = 0xd800 + ((r>>10)&0x3ff);
  2751. *r2 = 0xdc00 + (r&0x3ff);
  2752. }
  2753. };
  2754. lbModule *m = p->module;
  2755. auto tav = type_and_value_of_expr(ce->args[0]);
  2756. GB_ASSERT(tav.value.kind == ExactValue_String);
  2757. String value = tav.value.value_string;
  2758. LLVMTypeRef llvm_u16 = lb_type(m, t_u16);
  2759. isize max_len = value.len*2 + 1;
  2760. LLVMValueRef *buffer = gb_alloc_array(temporary_allocator(), LLVMValueRef, max_len);
  2761. isize n = 0;
  2762. while (value.len > 0) {
  2763. Rune r = 0;
  2764. isize w = gb_utf8_decode(value.text, value.len, &r);
  2765. value.text += w;
  2766. value.len -= w;
  2767. if ((0 <= r && r < 0xd800) || (0xe000 <= r && r < 0x10000)) {
  2768. buffer[n++] = LLVMConstInt(llvm_u16, cast(u16)r, false);
  2769. } else if (0x10000 <= r && r <= 0x10ffff) {
  2770. u16 r1, r2;
  2771. encode_surrogate_pair(r, &r1, &r2);
  2772. buffer[n++] = LLVMConstInt(llvm_u16, r1, false);
  2773. buffer[n++] = LLVMConstInt(llvm_u16, r2, false);
  2774. } else {
  2775. buffer[n++] = LLVMConstInt(llvm_u16, 0xfffd, false);
  2776. }
  2777. }
  2778. buffer[n++] = LLVMConstInt(llvm_u16, 0, false);
  2779. LLVMValueRef array = LLVMConstArray(llvm_u16, buffer, cast(unsigned int)n);
  2780. char *name = nullptr;
  2781. {
  2782. isize max_len = 7+8+1;
  2783. name = gb_alloc_array(permanent_allocator(), char, max_len);
  2784. u32 id = m->gen->global_array_index.fetch_add(1);
  2785. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  2786. len -= 1;
  2787. }
  2788. LLVMTypeRef type = LLVMTypeOf(array);
  2789. LLVMValueRef global_data = LLVMAddGlobal(m->mod, type, name);
  2790. LLVMSetInitializer(global_data, array);
  2791. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  2792. LLVMValueRef indices[] = {
  2793. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2794. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2795. };
  2796. lbValue res = {};
  2797. res.type = tv.type;
  2798. res.value = LLVMBuildInBoundsGEP2(p->builder, type, global_data, indices, gb_count_of(indices), "");
  2799. return res;
  2800. }
  2801. case BuiltinProc_wasm_memory_grow:
  2802. {
  2803. char const *name = "llvm.wasm.memory.grow";
  2804. LLVMTypeRef types[1] = {
  2805. lb_type(p->module, t_i32),
  2806. };
  2807. LLVMValueRef args[2] = {};
  2808. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2809. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr).value;
  2810. lbValue res = {};
  2811. res.type = t_i32;
  2812. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2813. return lb_emit_conv(p, res, tv.type);
  2814. }
  2815. case BuiltinProc_wasm_memory_size:
  2816. {
  2817. char const *name = "llvm.wasm.memory.size";
  2818. LLVMTypeRef types[1] = {
  2819. lb_type(p->module, t_i32),
  2820. };
  2821. LLVMValueRef args[1] = {};
  2822. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2823. lbValue res = {};
  2824. res.type = t_i32;
  2825. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2826. return lb_emit_conv(p, res, tv.type);
  2827. }
  2828. case BuiltinProc_wasm_memory_atomic_wait32:
  2829. {
  2830. char const *name = "llvm.wasm.memory.atomic.wait32";
  2831. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2832. LLVMValueRef args[3] = {};
  2833. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value;
  2834. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2835. args[2] = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i64).value;
  2836. lbValue res = {};
  2837. res.type = tv.type;
  2838. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), nullptr, 0);
  2839. return res;
  2840. }
  2841. case BuiltinProc_wasm_memory_atomic_notify32:
  2842. {
  2843. char const *name = "llvm.wasm.memory.atomic.notify";
  2844. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2845. LLVMValueRef args[2] = {
  2846. lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value,
  2847. lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value
  2848. };
  2849. lbValue res = {};
  2850. res.type = tv.type;
  2851. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), nullptr, 0);
  2852. return res;
  2853. }
  2854. case BuiltinProc_x86_cpuid:
  2855. {
  2856. Type *param_types[2] = {t_u32, t_u32};
  2857. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), tv.type, false, ProcCC_None);
  2858. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2859. LLVMValueRef the_asm = llvm_get_inline_asm(
  2860. func_type,
  2861. str_lit("cpuid"),
  2862. str_lit("={ax},={bx},={cx},={dx},{ax},{cx}"),
  2863. true
  2864. );
  2865. GB_ASSERT(the_asm != nullptr);
  2866. LLVMValueRef args[2] = {};
  2867. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2868. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2869. lbValue res = {};
  2870. res.type = tv.type;
  2871. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2872. return res;
  2873. }
  2874. case BuiltinProc_x86_xgetbv:
  2875. {
  2876. Type *type = alloc_type_proc_from_types(&t_u32, 1, tv.type, false, ProcCC_None);
  2877. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2878. LLVMValueRef the_asm = llvm_get_inline_asm(
  2879. func_type,
  2880. str_lit("xgetbv"),
  2881. str_lit("={ax},={dx},{cx}"),
  2882. true
  2883. );
  2884. GB_ASSERT(the_asm != nullptr);
  2885. LLVMValueRef args[1] = {};
  2886. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2887. lbValue res = {};
  2888. res.type = tv.type;
  2889. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2890. return res;
  2891. }
  2892. case BuiltinProc_valgrind_client_request:
  2893. {
  2894. lbValue args[7] = {};
  2895. for (isize i = 0; i < 7; i++) {
  2896. args[i] = lb_emit_conv(p, lb_build_expr(p, ce->args[i]), t_uintptr);
  2897. }
  2898. if (!build_context.ODIN_VALGRIND_SUPPORT) {
  2899. return args[0];
  2900. }
  2901. lbValue array = lb_generate_local_array(p, t_uintptr, 6, false);
  2902. for (isize i = 0; i < 6; i++) {
  2903. lbValue gep = lb_emit_array_epi(p, array, i);
  2904. lb_emit_store(p, gep, args[i+1]);
  2905. }
  2906. switch (build_context.metrics.arch) {
  2907. case TargetArch_amd64:
  2908. {
  2909. Type *param_types[2] = {};
  2910. param_types[0] = t_uintptr;
  2911. param_types[1] = array.type;
  2912. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), t_uintptr, false, ProcCC_None);
  2913. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2914. LLVMValueRef the_asm = llvm_get_inline_asm(
  2915. func_type,
  2916. str_lit("rolq $$3, %rdi; rolq $$13, %rdi\n rolq $$61, %rdi; rolq $$51, %rdi\n xchgq %rbx, %rbx"),
  2917. str_lit("={rdx},{rdx},{rax},~{cc},~{memory}"),
  2918. true
  2919. );
  2920. LLVMValueRef asm_args[2] = {};
  2921. asm_args[0] = args[0].value;
  2922. asm_args[1] = array.value;
  2923. lbValue res = {};
  2924. res.type = t_uintptr;
  2925. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, asm_args, gb_count_of(asm_args), "");
  2926. return res;
  2927. }
  2928. break;
  2929. default:
  2930. GB_PANIC("Unsupported architecture: %.*s", LIT(target_arch_names[build_context.metrics.arch]));
  2931. break;
  2932. }
  2933. }
  2934. }
  2935. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  2936. return {};
  2937. }
  2938. gb_internal lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TypeProc *procedure_type, Ast* call_expression) {
  2939. switch (param_value.kind) {
  2940. case ParameterValue_Constant:
  2941. if (is_type_constant_type(parameter_type)) {
  2942. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  2943. return res;
  2944. } else {
  2945. ExactValue ev = param_value.value;
  2946. lbValue arg = {};
  2947. Type *type = type_of_expr(param_value.original_ast_expr);
  2948. if (type != nullptr) {
  2949. arg = lb_const_value(p->module, type, ev);
  2950. } else {
  2951. arg = lb_const_value(p->module, parameter_type, param_value.value);
  2952. }
  2953. return lb_emit_conv(p, arg, parameter_type);
  2954. }
  2955. case ParameterValue_Nil:
  2956. return lb_const_nil(p->module, parameter_type);
  2957. case ParameterValue_Location:
  2958. {
  2959. String proc_name = {};
  2960. if (p->entity != nullptr) {
  2961. proc_name = p->entity->token.string;
  2962. }
  2963. ast_node(ce, CallExpr, call_expression);
  2964. TokenPos pos = ast_token(ce->proc).pos;
  2965. return lb_emit_source_code_location_as_global(p, proc_name, pos);
  2966. }
  2967. case ParameterValue_Expression:
  2968. {
  2969. Ast *orig = param_value.original_ast_expr;
  2970. if (orig->kind == Ast_BasicDirective) {
  2971. gbString expr = expr_to_string(call_expression, temporary_allocator());
  2972. return lb_const_string(p->module, make_string_c(expr));
  2973. }
  2974. isize param_idx = -1;
  2975. String param_str = {0};
  2976. {
  2977. Ast *call = unparen_expr(orig);
  2978. GB_ASSERT(call->kind == Ast_CallExpr);
  2979. ast_node(ce, CallExpr, call);
  2980. GB_ASSERT(ce->proc->kind == Ast_BasicDirective);
  2981. GB_ASSERT(ce->args.count == 1);
  2982. Ast *target = ce->args[0];
  2983. GB_ASSERT(target->kind == Ast_Ident);
  2984. String target_str = target->Ident.token.string;
  2985. param_idx = lookup_procedure_parameter(procedure_type, target_str);
  2986. param_str = target_str;
  2987. }
  2988. GB_ASSERT(param_idx >= 0);
  2989. Ast *target_expr = nullptr;
  2990. ast_node(ce, CallExpr, call_expression);
  2991. if (ce->split_args->positional.count > param_idx) {
  2992. target_expr = ce->split_args->positional[param_idx];
  2993. }
  2994. for_array(i, ce->split_args->named) {
  2995. Ast *arg = ce->split_args->named[i];
  2996. ast_node(fv, FieldValue, arg);
  2997. GB_ASSERT(fv->field->kind == Ast_Ident);
  2998. String name = fv->field->Ident.token.string;
  2999. if (name == param_str) {
  3000. target_expr = fv->value;
  3001. break;
  3002. }
  3003. }
  3004. gbString expr = expr_to_string(target_expr, temporary_allocator());
  3005. return lb_const_string(p->module, make_string_c(expr));
  3006. }
  3007. case ParameterValue_Value:
  3008. return lb_build_expr(p, param_value.ast_value);
  3009. }
  3010. return lb_const_nil(p->module, parameter_type);
  3011. }
  3012. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr);
  3013. gb_internal lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  3014. expr = unparen_expr(expr);
  3015. ast_node(ce, CallExpr, expr);
  3016. lbValue res = lb_build_call_expr_internal(p, expr);
  3017. if (ce->optional_ok_one) {
  3018. GB_ASSERT(is_type_tuple(res.type));
  3019. GB_ASSERT(res.type->Tuple.variables.count == 2);
  3020. return lb_emit_struct_ev(p, res, 0);
  3021. }
  3022. return res;
  3023. }
  3024. gb_internal void lb_add_values_to_array(lbProcedure *p, Array<lbValue> *args, lbValue value) {
  3025. if (is_type_tuple(value.type)) {
  3026. for_array(i, value.type->Tuple.variables) {
  3027. lbValue sub_value = lb_emit_struct_ev(p, value, cast(i32)i);
  3028. array_add(args, sub_value);
  3029. }
  3030. } else {
  3031. array_add(args, value);
  3032. }
  3033. }
  3034. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr) {
  3035. lbModule *m = p->module;
  3036. TypeAndValue tv = type_and_value_of_expr(expr);
  3037. ast_node(ce, CallExpr, expr);
  3038. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  3039. AddressingMode proc_mode = proc_tv.mode;
  3040. if (proc_mode == Addressing_Type) {
  3041. GB_ASSERT(ce->args.count == 1);
  3042. lbValue x = lb_build_expr(p, ce->args[0]);
  3043. lbValue y = lb_emit_conv(p, x, tv.type);
  3044. return y;
  3045. }
  3046. Ast *proc_expr = unparen_expr(ce->proc);
  3047. if (proc_mode == Addressing_Builtin) {
  3048. Entity *e = entity_of_node(proc_expr);
  3049. BuiltinProcId id = BuiltinProc_Invalid;
  3050. if (e != nullptr) {
  3051. id = cast(BuiltinProcId)e->Builtin.id;
  3052. } else {
  3053. id = BuiltinProc_DIRECTIVE;
  3054. }
  3055. return lb_build_builtin_proc(p, expr, tv, id);
  3056. }
  3057. // NOTE(bill): Regular call
  3058. lbValue value = {};
  3059. Entity *proc_entity = entity_of_node(proc_expr);
  3060. if (proc_entity != nullptr) {
  3061. if (proc_entity->flags & EntityFlag_Disabled) {
  3062. GB_ASSERT(tv.type == nullptr);
  3063. return {};
  3064. }
  3065. }
  3066. if (proc_expr->tav.mode == Addressing_Constant) {
  3067. ExactValue v = proc_expr->tav.value;
  3068. switch (v.kind) {
  3069. case ExactValue_Integer:
  3070. {
  3071. u64 u = big_int_to_u64(&v.value_integer);
  3072. lbValue x = {};
  3073. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  3074. x.type = t_uintptr;
  3075. x = lb_emit_conv(p, x, t_rawptr);
  3076. value = lb_emit_conv(p, x, proc_expr->tav.type);
  3077. break;
  3078. }
  3079. case ExactValue_Pointer:
  3080. {
  3081. u64 u = cast(u64)v.value_pointer;
  3082. lbValue x = {};
  3083. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  3084. x.type = t_uintptr;
  3085. x = lb_emit_conv(p, x, t_rawptr);
  3086. value = lb_emit_conv(p, x, proc_expr->tav.type);
  3087. break;
  3088. }
  3089. }
  3090. }
  3091. if (value.value == nullptr) {
  3092. value = lb_build_expr(p, proc_expr);
  3093. }
  3094. GB_ASSERT(value.value != nullptr);
  3095. Type *proc_type_ = base_type(value.type);
  3096. GB_ASSERT(proc_type_->kind == Type_Proc);
  3097. TypeProc *pt = &proc_type_->Proc;
  3098. GB_ASSERT(ce->split_args != nullptr);
  3099. auto args = array_make<lbValue>(permanent_allocator(), 0, pt->param_count);
  3100. bool vari_expand = (ce->ellipsis.pos.line != 0);
  3101. bool is_c_vararg = pt->c_vararg;
  3102. for_array(i, ce->split_args->positional) {
  3103. Entity *e = pt->params->Tuple.variables[i];
  3104. if (e->kind == Entity_TypeName) {
  3105. array_add(&args, lb_const_nil(p->module, e->type));
  3106. continue;
  3107. } else if (e->kind == Entity_Constant) {
  3108. array_add(&args, lb_const_value(p->module, e->type, e->Constant.value));
  3109. continue;
  3110. }
  3111. GB_ASSERT(e->kind == Entity_Variable);
  3112. if (pt->variadic && pt->variadic_index == i) {
  3113. lbValue variadic_args = lb_const_nil(p->module, e->type);
  3114. auto variadic = slice(ce->split_args->positional, pt->variadic_index, ce->split_args->positional.count);
  3115. if (variadic.count != 0) {
  3116. // variadic call argument generation
  3117. Type *slice_type = e->type;
  3118. GB_ASSERT(slice_type->kind == Type_Slice);
  3119. if (is_c_vararg) {
  3120. GB_ASSERT(!vari_expand);
  3121. Type *elem_type = slice_type->Slice.elem;
  3122. for (Ast *var_arg : variadic) {
  3123. lbValue arg = lb_build_expr(p, var_arg);
  3124. if (is_type_any(elem_type)) {
  3125. if (is_type_untyped_nil(arg.type)) {
  3126. arg = lb_const_nil(p->module, t_rawptr);
  3127. }
  3128. array_add(&args, lb_emit_c_vararg(p, arg, arg.type));
  3129. } else {
  3130. array_add(&args, lb_emit_c_vararg(p, arg, elem_type));
  3131. }
  3132. }
  3133. break;
  3134. } else if (vari_expand) {
  3135. GB_ASSERT(variadic.count == 1);
  3136. variadic_args = lb_build_expr(p, variadic[0]);
  3137. variadic_args = lb_emit_conv(p, variadic_args, slice_type);
  3138. } else {
  3139. Type *elem_type = slice_type->Slice.elem;
  3140. auto var_args = array_make<lbValue>(heap_allocator(), 0, variadic.count);
  3141. defer (array_free(&var_args));
  3142. for (Ast *var_arg : variadic) {
  3143. lbValue v = lb_build_expr(p, var_arg);
  3144. lb_add_values_to_array(p, &var_args, v);
  3145. }
  3146. isize slice_len = var_args.count;
  3147. if (slice_len > 0) {
  3148. lbAddr slice = {};
  3149. for (auto const &vr : p->variadic_reuses) {
  3150. if (are_types_identical(vr.slice_type, slice_type)) {
  3151. slice = vr.slice_addr;
  3152. break;
  3153. }
  3154. }
  3155. DeclInfo *d = decl_info_of_entity(p->entity);
  3156. if (d != nullptr && slice.addr.value == nullptr) {
  3157. for (auto const &vr : d->variadic_reuses) {
  3158. if (are_types_identical(vr.slice_type, slice_type)) {
  3159. #if LLVM_VERSION_MAJOR >= 13
  3160. // NOTE(bill): No point wasting even more memory, just reuse this stack variable too
  3161. if (p->variadic_reuses.count > 0) {
  3162. slice = p->variadic_reuses[0].slice_addr;
  3163. } else {
  3164. slice = lb_add_local_generated(p, slice_type, true);
  3165. }
  3166. // NOTE(bill): Change the underlying type to match the specific type
  3167. slice.addr.type = alloc_type_pointer(slice_type);
  3168. #else
  3169. slice = lb_add_local_generated(p, slice_type, true);
  3170. #endif
  3171. array_add(&p->variadic_reuses, lbVariadicReuseSlices{slice_type, slice});
  3172. break;
  3173. }
  3174. }
  3175. }
  3176. lbValue base_array_ptr = p->variadic_reuse_base_array_ptr.addr;
  3177. if (base_array_ptr.value == nullptr) {
  3178. if (d != nullptr) {
  3179. i64 max_bytes = d->variadic_reuse_max_bytes;
  3180. i64 max_align = gb_max(d->variadic_reuse_max_align, 16);
  3181. p->variadic_reuse_base_array_ptr = lb_add_local_generated(p, alloc_type_array(t_u8, max_bytes), true);
  3182. lb_try_update_alignment(p->variadic_reuse_base_array_ptr.addr, cast(unsigned)max_align);
  3183. base_array_ptr = p->variadic_reuse_base_array_ptr.addr;
  3184. } else {
  3185. base_array_ptr = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true).addr;
  3186. }
  3187. }
  3188. if (slice.addr.value == nullptr) {
  3189. slice = lb_add_local_generated(p, slice_type, true);
  3190. }
  3191. GB_ASSERT(base_array_ptr.value != nullptr);
  3192. GB_ASSERT(slice.addr.value != nullptr);
  3193. base_array_ptr = lb_emit_conv(p, base_array_ptr, alloc_type_pointer(alloc_type_array(elem_type, slice_len)));
  3194. for (isize i = 0; i < var_args.count; i++) {
  3195. lbValue addr = lb_emit_array_epi(p, base_array_ptr, cast(i32)i);
  3196. lbValue var_arg = var_args[i];
  3197. var_arg = lb_emit_conv(p, var_arg, elem_type);
  3198. lb_emit_store(p, addr, var_arg);
  3199. }
  3200. lbValue base_elem = lb_emit_array_epi(p, base_array_ptr, 0);
  3201. lbValue len = lb_const_int(p->module, t_int, slice_len);
  3202. lb_fill_slice(p, slice, base_elem, len);
  3203. variadic_args = lb_addr_load(p, slice);
  3204. }
  3205. }
  3206. }
  3207. array_add(&args, variadic_args);
  3208. break;
  3209. } else {
  3210. lbValue value = lb_build_expr(p, ce->split_args->positional[i]);
  3211. lb_add_values_to_array(p, &args, value);
  3212. }
  3213. }
  3214. if (!is_c_vararg) {
  3215. array_resize(&args, pt->param_count);
  3216. }
  3217. for (Ast *arg : ce->split_args->named) {
  3218. ast_node(fv, FieldValue, arg);
  3219. GB_ASSERT(fv->field->kind == Ast_Ident);
  3220. String name = fv->field->Ident.token.string;
  3221. gb_unused(name);
  3222. isize param_index = lookup_procedure_parameter(pt, name);
  3223. GB_ASSERT(param_index >= 0);
  3224. Entity *e = pt->params->Tuple.variables[param_index];
  3225. if (e->kind == Entity_TypeName) {
  3226. lbValue value = lb_const_nil(p->module, e->type);
  3227. args[param_index] = value;
  3228. } else if (is_c_vararg && pt->variadic && pt->variadic_index == param_index) {
  3229. GB_ASSERT(param_index == pt->param_count-1);
  3230. Type *slice_type = e->type;
  3231. GB_ASSERT(slice_type->kind == Type_Slice);
  3232. Type *elem_type = slice_type->Slice.elem;
  3233. if (fv->value->kind == Ast_CompoundLit) {
  3234. ast_node(literal, CompoundLit, fv->value);
  3235. for (Ast *var_arg : literal->elems) {
  3236. lbValue arg = lb_build_expr(p, var_arg);
  3237. if (is_type_any(elem_type)) {
  3238. if (is_type_untyped_nil(arg.type)) {
  3239. arg = lb_const_nil(p->module, t_rawptr);
  3240. }
  3241. array_add(&args, lb_emit_c_vararg(p, arg, arg.type));
  3242. } else {
  3243. array_add(&args, lb_emit_c_vararg(p, arg, elem_type));
  3244. }
  3245. }
  3246. } else {
  3247. lbValue value = lb_build_expr(p, fv->value);
  3248. GB_ASSERT(!is_type_tuple(value.type));
  3249. array_add(&args, lb_emit_c_vararg(p, value, value.type));
  3250. }
  3251. } else {
  3252. lbValue value = lb_build_expr(p, fv->value);
  3253. GB_ASSERT(!is_type_tuple(value.type));
  3254. args[param_index] = value;
  3255. }
  3256. }
  3257. if (pt->params != nullptr) {
  3258. isize min_count = pt->params->Tuple.variables.count;
  3259. if (is_c_vararg) {
  3260. min_count -= 1;
  3261. }
  3262. GB_ASSERT(args.count >= min_count);
  3263. for_array(arg_index, pt->params->Tuple.variables) {
  3264. Entity *e = pt->params->Tuple.variables[arg_index];
  3265. if (pt->variadic && arg_index == pt->variadic_index) {
  3266. if (!is_c_vararg && args[arg_index].value == 0) {
  3267. args[arg_index] = lb_const_nil(p->module, e->type);
  3268. }
  3269. continue;
  3270. }
  3271. lbValue arg = args[arg_index];
  3272. if (arg.value == nullptr && arg.type == nullptr) {
  3273. switch (e->kind) {
  3274. case Entity_TypeName:
  3275. args[arg_index] = lb_const_nil(p->module, e->type);
  3276. break;
  3277. case Entity_Variable:
  3278. args[arg_index] = lb_handle_param_value(p, e->type, e->Variable.param_value, pt, expr);
  3279. break;
  3280. case Entity_Constant:
  3281. args[arg_index] = lb_const_value(p->module, e->type, e->Constant.value);
  3282. break;
  3283. default:
  3284. GB_PANIC("Unknown entity kind %.*s\n", LIT(entity_strings[e->kind]));
  3285. }
  3286. } else {
  3287. args[arg_index] = lb_emit_conv(p, arg, e->type);
  3288. }
  3289. }
  3290. }
  3291. isize final_count = is_c_vararg ? args.count : pt->param_count;
  3292. auto call_args = array_slice(args, 0, final_count);
  3293. return lb_emit_call(p, value, call_args, ce->inlining);
  3294. }