llvm_backend_proc.cpp 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599
  1. void lb_mem_copy_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  2. dst = lb_emit_conv(p, dst, t_rawptr);
  3. src = lb_emit_conv(p, src, t_rawptr);
  4. len = lb_emit_conv(p, len, t_int);
  5. char const *name = "llvm.memmove";
  6. if (LLVMIsConstant(len.value)) {
  7. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  8. if (const_len <= 4*build_context.word_size) {
  9. name = "llvm.memmove.inline";
  10. }
  11. }
  12. LLVMTypeRef types[3] = {
  13. lb_type(p->module, t_rawptr),
  14. lb_type(p->module, t_rawptr),
  15. lb_type(p->module, t_int)
  16. };
  17. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  18. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]), LLVMPrintTypeToString(types[2]));
  19. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  20. LLVMValueRef args[4] = {};
  21. args[0] = dst.value;
  22. args[1] = src.value;
  23. args[2] = len.value;
  24. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile);
  25. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  26. }
  27. void lb_mem_copy_non_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  28. dst = lb_emit_conv(p, dst, t_rawptr);
  29. src = lb_emit_conv(p, src, t_rawptr);
  30. len = lb_emit_conv(p, len, t_int);
  31. char const *name = "llvm.memcpy";
  32. if (LLVMIsConstant(len.value)) {
  33. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  34. if (const_len <= 4*build_context.word_size) {
  35. name = "llvm.memcpy.inline";
  36. }
  37. }
  38. LLVMTypeRef types[3] = {
  39. lb_type(p->module, t_rawptr),
  40. lb_type(p->module, t_rawptr),
  41. lb_type(p->module, t_int)
  42. };
  43. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  44. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]), LLVMPrintTypeToString(types[2]));
  45. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  46. LLVMValueRef args[4] = {};
  47. args[0] = dst.value;
  48. args[1] = src.value;
  49. args[2] = len.value;
  50. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile);
  51. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  52. }
  53. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  54. GB_ASSERT(entity != nullptr);
  55. GB_ASSERT(entity->kind == Entity_Procedure);
  56. if (!entity->Procedure.is_foreign) {
  57. GB_ASSERT_MSG(entity->flags & EntityFlag_ProcBodyChecked, "%.*s :: %s", LIT(entity->token.string), type_to_string(entity->type));
  58. }
  59. String link_name = {};
  60. if (ignore_body) {
  61. lbModule *other_module = lb_pkg_module(m->gen, entity->pkg);
  62. link_name = lb_get_entity_name(other_module, entity);
  63. } else {
  64. link_name = lb_get_entity_name(m, entity);
  65. }
  66. {
  67. StringHashKey key = string_hash_string(link_name);
  68. lbValue *found = string_map_get(&m->members, key);
  69. if (found) {
  70. lb_add_entity(m, entity, *found);
  71. return string_map_must_get(&m->procedures, key);
  72. }
  73. }
  74. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  75. p->module = m;
  76. entity->code_gen_module = m;
  77. entity->code_gen_procedure = p;
  78. p->entity = entity;
  79. p->name = link_name;
  80. DeclInfo *decl = entity->decl_info;
  81. ast_node(pl, ProcLit, decl->proc_lit);
  82. Type *pt = base_type(entity->type);
  83. GB_ASSERT(pt->kind == Type_Proc);
  84. p->type = entity->type;
  85. p->type_expr = decl->type_expr;
  86. p->body = pl->body;
  87. p->inlining = pl->inlining;
  88. p->is_foreign = entity->Procedure.is_foreign;
  89. p->is_export = entity->Procedure.is_export;
  90. p->is_entry_point = false;
  91. gbAllocator a = heap_allocator();
  92. p->children.allocator = a;
  93. p->defer_stmts.allocator = a;
  94. p->blocks.allocator = a;
  95. p->branch_blocks.allocator = a;
  96. p->context_stack.allocator = a;
  97. p->scope_stack.allocator = a;
  98. if (p->is_foreign) {
  99. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  100. }
  101. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  102. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  103. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  104. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  105. lb_ensure_abi_function_type(m, p);
  106. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  107. if (pt->Proc.diverging) {
  108. lb_add_attribute_to_proc(m, p->value, "noreturn");
  109. }
  110. if (pt->Proc.calling_convention == ProcCC_Naked) {
  111. lb_add_attribute_to_proc(m, p->value, "naked");
  112. }
  113. if (!entity->Procedure.is_foreign && build_context.disable_red_zone) {
  114. lb_add_attribute_to_proc(m, p->value, "noredzone");
  115. }
  116. if (build_context.optimization_level == 0 && build_context.ODIN_DEBUG) {
  117. lb_add_attribute_to_proc(m, p->value, "noinline");
  118. lb_add_attribute_to_proc(m, p->value, "optnone");
  119. } else {
  120. switch (p->inlining) {
  121. case ProcInlining_inline:
  122. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  123. break;
  124. case ProcInlining_no_inline:
  125. lb_add_attribute_to_proc(m, p->value, "noinline");
  126. break;
  127. }
  128. switch (entity->Procedure.optimization_mode) {
  129. case ProcedureOptimizationMode_None:
  130. lb_add_attribute_to_proc(m, p->value, "optnone");
  131. break;
  132. case ProcedureOptimizationMode_Minimal:
  133. lb_add_attribute_to_proc(m, p->value, "optnone");
  134. break;
  135. case ProcedureOptimizationMode_Size:
  136. lb_add_attribute_to_proc(m, p->value, "optsize");
  137. break;
  138. case ProcedureOptimizationMode_Speed:
  139. // TODO(bill): handle this correctly
  140. lb_add_attribute_to_proc(m, p->value, "optsize");
  141. break;
  142. }
  143. }
  144. if (entity->flags & EntityFlag_Cold) {
  145. lb_add_attribute_to_proc(m, p->value, "cold");
  146. }
  147. lbValue proc_value = {p->value, p->type};
  148. lb_add_entity(m, entity, proc_value);
  149. lb_add_member(m, p->name, proc_value);
  150. lb_add_procedure_value(m, p);
  151. if (p->is_export) {
  152. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  153. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  154. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  155. lb_set_wasm_export_attributes(p->value, p->name);
  156. } else if (!p->is_foreign) {
  157. if (!USE_SEPARATE_MODULES) {
  158. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  159. // NOTE(bill): if a procedure is defined in package runtime and uses a custom link name,
  160. // then it is very likely it is required by LLVM and thus cannot have internal linkage
  161. if (entity->pkg != nullptr && entity->pkg->kind == Package_Runtime && p->body != nullptr) {
  162. GB_ASSERT(entity->kind == Entity_Procedure);
  163. String link_name = entity->Procedure.link_name;
  164. if (entity->flags & EntityFlag_CustomLinkName &&
  165. link_name != "") {
  166. if (string_starts_with(link_name, str_lit("__"))) {
  167. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  168. } else {
  169. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  170. }
  171. }
  172. }
  173. }
  174. }
  175. lb_set_linkage_from_entity_flags(p->module, p->value, entity->flags);
  176. if (p->is_foreign) {
  177. lb_set_wasm_import_attributes(p->value, entity, p->name);
  178. }
  179. // NOTE(bill): offset==0 is the return value
  180. isize offset = 1;
  181. if (pt->Proc.return_by_pointer) {
  182. offset = 2;
  183. }
  184. isize parameter_index = 0;
  185. if (pt->Proc.param_count) {
  186. TypeTuple *params = &pt->Proc.params->Tuple;
  187. for (isize i = 0; i < pt->Proc.param_count; i++) {
  188. Entity *e = params->variables[i];
  189. if (e->kind != Entity_Variable) {
  190. continue;
  191. }
  192. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  193. continue;
  194. }
  195. if (e->flags&EntityFlag_NoAlias) {
  196. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  197. }
  198. parameter_index += 1;
  199. }
  200. }
  201. if (ignore_body) {
  202. p->body = nullptr;
  203. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  204. }
  205. if (m->debug_builder) { // Debug Information
  206. Type *bt = base_type(p->type);
  207. unsigned line = cast(unsigned)entity->token.pos.line;
  208. LLVMMetadataRef scope = nullptr;
  209. LLVMMetadataRef file = nullptr;
  210. LLVMMetadataRef type = nullptr;
  211. scope = p->module->debug_compile_unit;
  212. type = lb_debug_type_internal_proc(m, bt);
  213. Ast *ident = entity->identifier.load();
  214. if (entity->file != nullptr) {
  215. file = lb_get_llvm_metadata(m, entity->file);
  216. scope = file;
  217. } else if (ident != nullptr && ident->file_id != 0) {
  218. file = lb_get_llvm_metadata(m, ident->file());
  219. scope = file;
  220. } else if (entity->scope != nullptr) {
  221. file = lb_get_llvm_metadata(m, entity->scope->file);
  222. scope = file;
  223. }
  224. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  225. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  226. LLVMBool is_local_to_unit = false;
  227. LLVMBool is_definition = p->body != nullptr;
  228. unsigned scope_line = line;
  229. u32 flags = LLVMDIFlagStaticMember;
  230. LLVMBool is_optimized = false;
  231. if (bt->Proc.diverging) {
  232. flags |= LLVMDIFlagNoReturn;
  233. }
  234. if (p->body == nullptr) {
  235. flags |= LLVMDIFlagPrototyped;
  236. is_optimized = false;
  237. }
  238. if (p->body != nullptr) {
  239. // String debug_name = entity->token.string.text;
  240. String debug_name = p->name;
  241. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  242. cast(char const *)debug_name.text, debug_name.len,
  243. cast(char const *)p->name.text, p->name.len,
  244. file, line, type,
  245. is_local_to_unit, is_definition,
  246. scope_line, cast(LLVMDIFlags)flags, is_optimized
  247. );
  248. GB_ASSERT(p->debug_info != nullptr);
  249. LLVMSetSubprogram(p->value, p->debug_info);
  250. lb_set_llvm_metadata(m, p, p->debug_info);
  251. }
  252. }
  253. return p;
  254. }
  255. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  256. {
  257. lbValue *found = string_map_get(&m->members, link_name);
  258. GB_ASSERT_MSG(found == nullptr, "failed to create dummy procedure for: %.*s", LIT(link_name));
  259. }
  260. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  261. p->module = m;
  262. p->name = link_name;
  263. p->type = type;
  264. p->type_expr = nullptr;
  265. p->body = nullptr;
  266. p->tags = 0;
  267. p->inlining = ProcInlining_none;
  268. p->is_foreign = false;
  269. p->is_export = false;
  270. p->is_entry_point = false;
  271. gbAllocator a = permanent_allocator();
  272. p->children.allocator = a;
  273. p->defer_stmts.allocator = a;
  274. p->blocks.allocator = a;
  275. p->branch_blocks.allocator = a;
  276. p->context_stack.allocator = a;
  277. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  278. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  279. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  280. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  281. Type *pt = p->type;
  282. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  283. // TODO(bill): Clean up this logic
  284. if (!is_arch_wasm()) {
  285. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  286. }
  287. LLVMSetFunctionCallConv(p->value, cc_kind);
  288. lbValue proc_value = {p->value, p->type};
  289. lb_add_member(m, p->name, proc_value);
  290. lb_add_procedure_value(m, p);
  291. // NOTE(bill): offset==0 is the return value
  292. isize offset = 1;
  293. if (pt->Proc.return_by_pointer) {
  294. lb_add_proc_attribute_at_index(p, 1, "sret");
  295. lb_add_proc_attribute_at_index(p, 1, "noalias");
  296. offset = 2;
  297. }
  298. isize parameter_index = 0;
  299. if (pt->Proc.calling_convention == ProcCC_Odin) {
  300. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  301. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  302. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  303. }
  304. return p;
  305. }
  306. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  307. lbParamPasskind kind = lbParamPass_Value;
  308. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  309. if (is_type_pointer(abi_type)) {
  310. GB_ASSERT(e->kind == Entity_Variable);
  311. Type *av = core_type(type_deref(abi_type));
  312. if (are_types_identical(av, core_type(e->type))) {
  313. kind = lbParamPass_Pointer;
  314. if (e->flags&EntityFlag_Value) {
  315. kind = lbParamPass_ConstRef;
  316. }
  317. } else {
  318. kind = lbParamPass_BitCast;
  319. }
  320. } else if (is_type_integer(abi_type)) {
  321. kind = lbParamPass_Integer;
  322. } else if (abi_type == t_llvm_bool) {
  323. kind = lbParamPass_Value;
  324. } else if (is_type_boolean(abi_type)) {
  325. kind = lbParamPass_Integer;
  326. } else if (is_type_simd_vector(abi_type)) {
  327. kind = lbParamPass_BitCast;
  328. } else if (is_type_float(abi_type)) {
  329. kind = lbParamPass_BitCast;
  330. } else if (is_type_tuple(abi_type)) {
  331. kind = lbParamPass_Tuple;
  332. } else if (is_type_proc(abi_type)) {
  333. kind = lbParamPass_Value;
  334. } else {
  335. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  336. }
  337. }
  338. if (kind_) *kind_ = kind;
  339. lbValue res = {};
  340. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  341. res.type = abi_type;
  342. return res;
  343. }
  344. void lb_start_block(lbProcedure *p, lbBlock *b) {
  345. GB_ASSERT(b != nullptr);
  346. if (!b->appended) {
  347. b->appended = true;
  348. LLVMAppendExistingBasicBlock(p->value, b->block);
  349. }
  350. LLVMPositionBuilderAtEnd(p->builder, b->block);
  351. p->curr_block = b;
  352. }
  353. void lb_begin_procedure_body(lbProcedure *p) {
  354. DeclInfo *decl = decl_info_of_entity(p->entity);
  355. if (decl != nullptr) {
  356. for_array(i, decl->labels) {
  357. BlockLabel bl = decl->labels[i];
  358. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  359. array_add(&p->branch_blocks, bb);
  360. }
  361. }
  362. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  363. p->decl_block = lb_create_block(p, "decls", true);
  364. p->entry_block = lb_create_block(p, "entry", true);
  365. lb_start_block(p, p->entry_block);
  366. GB_ASSERT(p->type != nullptr);
  367. lb_ensure_abi_function_type(p->module, p);
  368. {
  369. lbFunctionType *ft = p->abi_function_type;
  370. unsigned param_offset = 0;
  371. lbValue return_ptr_value = {};
  372. if (ft->ret.kind == lbArg_Indirect) {
  373. // NOTE(bill): this must be parameter 0
  374. String name = str_lit("agg.result");
  375. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  376. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  377. e->flags |= EntityFlag_NoAlias;
  378. return_ptr_value.value = LLVMGetParam(p->value, 0);
  379. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  380. return_ptr_value.type = ptr_type;
  381. p->return_ptr = lb_addr(return_ptr_value);
  382. lb_add_entity(p->module, e, return_ptr_value);
  383. param_offset += 1;
  384. }
  385. if (p->type->Proc.params != nullptr) {
  386. TypeTuple *params = &p->type->Proc.params->Tuple;
  387. unsigned param_index = 0;
  388. for_array(i, params->variables) {
  389. Entity *e = params->variables[i];
  390. if (e->kind != Entity_Variable) {
  391. continue;
  392. }
  393. lbArgType *arg_type = &ft->args[param_index];
  394. defer (param_index += 1);
  395. if (arg_type->kind == lbArg_Ignore) {
  396. continue;
  397. } else if (arg_type->kind == lbArg_Direct) {
  398. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  399. LLVMTypeRef param_type = lb_type(p->module, e->type);
  400. LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index);
  401. LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type);
  402. lbValue param = {};
  403. param.value = value;
  404. param.type = e->type;
  405. lbValue ptr = lb_address_from_load_or_generate_local(p, param);
  406. GB_ASSERT(LLVMIsAAllocaInst(ptr.value));
  407. lb_add_entity(p->module, e, ptr);
  408. lbBlock *block = p->decl_block;
  409. if (original_value != value) {
  410. block = p->curr_block;
  411. }
  412. LLVMValueRef debug_storage_value = value;
  413. if (original_value != value && LLVMIsALoadInst(value)) {
  414. debug_storage_value = LLVMGetOperand(value, 0);
  415. }
  416. lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block);
  417. }
  418. } else if (arg_type->kind == lbArg_Indirect) {
  419. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  420. lbValue ptr = {};
  421. ptr.value = LLVMGetParam(p->value, param_offset+param_index);
  422. ptr.type = alloc_type_pointer(e->type);
  423. lb_add_entity(p->module, e, ptr);
  424. lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block);
  425. }
  426. }
  427. }
  428. }
  429. if (p->type->Proc.has_named_results) {
  430. GB_ASSERT(p->type->Proc.result_count > 0);
  431. TypeTuple *results = &p->type->Proc.results->Tuple;
  432. for_array(i, results->variables) {
  433. Entity *e = results->variables[i];
  434. GB_ASSERT(e->kind == Entity_Variable);
  435. if (e->token.string != "") {
  436. GB_ASSERT(!is_blank_ident(e->token));
  437. lbAddr res = {};
  438. if (return_ptr_value.value) {
  439. lbValue ptr = return_ptr_value;
  440. if (results->variables.count != 1) {
  441. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  442. }
  443. res = lb_addr(ptr);
  444. lb_add_entity(p->module, e, ptr);
  445. } else {
  446. res = lb_add_local(p, e->type, e);
  447. }
  448. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  449. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  450. lb_addr_store(p, res, c);
  451. }
  452. }
  453. }
  454. }
  455. }
  456. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  457. lb_push_context_onto_stack_from_implicit_parameter(p);
  458. }
  459. lb_start_block(p, p->entry_block);
  460. if (p->debug_info != nullptr) {
  461. TokenPos pos = {};
  462. if (p->body != nullptr) {
  463. pos = ast_token(p->body).pos;
  464. } else if (p->type_expr != nullptr) {
  465. pos = ast_token(p->type_expr).pos;
  466. } else if (p->entity != nullptr) {
  467. pos = p->entity->token.pos;
  468. }
  469. if (pos.file_id != 0) {
  470. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  471. }
  472. if (p->context_stack.count != 0) {
  473. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  474. }
  475. }
  476. }
  477. void lb_end_procedure_body(lbProcedure *p) {
  478. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  479. LLVMBuildBr(p->builder, p->entry_block->block);
  480. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  481. LLVMValueRef instr = nullptr;
  482. // Make sure there is a "ret void" at the end of a procedure with no return type
  483. if (p->type->Proc.result_count == 0) {
  484. instr = LLVMGetLastInstruction(p->curr_block->block);
  485. if (!lb_is_instr_terminating(instr)) {
  486. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  487. LLVMBuildRetVoid(p->builder);
  488. }
  489. }
  490. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  491. LLVMBasicBlockRef block = nullptr;
  492. // Make sure every block terminates, and if not, make it unreachable
  493. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  494. instr = LLVMGetLastInstruction(block);
  495. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  496. LLVMPositionBuilderAtEnd(p->builder, block);
  497. LLVMBuildUnreachable(p->builder);
  498. }
  499. }
  500. p->curr_block = nullptr;
  501. p->state_flags = 0;
  502. }
  503. void lb_end_procedure(lbProcedure *p) {
  504. LLVMDisposeBuilder(p->builder);
  505. }
  506. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  507. GB_ASSERT(pd->body != nullptr);
  508. lbModule *m = p->module;
  509. auto *min_dep_set = &m->info->minimum_dependency_set;
  510. if (ptr_set_exists(min_dep_set, e) == false) {
  511. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  512. return;
  513. }
  514. // NOTE(bill): Generate a new name
  515. // parent.name-guid
  516. String original_name = e->token.string;
  517. String pd_name = original_name;
  518. if (e->Procedure.link_name.len > 0) {
  519. pd_name = e->Procedure.link_name;
  520. }
  521. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  522. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  523. i32 guid = cast(i32)p->children.count;
  524. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  525. String name = make_string(cast(u8 *)name_text, name_len-1);
  526. e->Procedure.link_name = name;
  527. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  528. e->code_gen_procedure = nested_proc;
  529. lbValue value = {};
  530. value.value = nested_proc->value;
  531. value.type = nested_proc->type;
  532. lb_add_entity(m, e, value);
  533. array_add(&p->children, nested_proc);
  534. array_add(&m->procedures_to_generate, nested_proc);
  535. }
  536. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  537. Array<lbValue> array = {};
  538. Type *t = base_type(value.type);
  539. if (t == nullptr) {
  540. // Do nothing
  541. } else if (is_type_tuple(t)) {
  542. GB_ASSERT(t->kind == Type_Tuple);
  543. auto *rt = &t->Tuple;
  544. if (rt->variables.count > 0) {
  545. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  546. for_array(i, rt->variables) {
  547. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  548. array[i] = elem;
  549. }
  550. }
  551. } else {
  552. array = array_make<lbValue>(permanent_allocator(), 1);
  553. array[0] = value;
  554. }
  555. return array;
  556. }
  557. 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) {
  558. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  559. unsigned arg_count = cast(unsigned)processed_args.count;
  560. if (return_ptr.value != nullptr) {
  561. arg_count += 1;
  562. }
  563. if (context_ptr.addr.value != nullptr) {
  564. arg_count += 1;
  565. }
  566. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  567. isize arg_index = 0;
  568. if (return_ptr.value != nullptr) {
  569. args[arg_index++] = return_ptr.value;
  570. }
  571. for_array(i, processed_args) {
  572. lbValue arg = processed_args[i];
  573. args[arg_index++] = arg.value;
  574. }
  575. if (context_ptr.addr.value != nullptr) {
  576. LLVMValueRef cp = context_ptr.addr.value;
  577. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  578. args[arg_index++] = cp;
  579. }
  580. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  581. GB_ASSERT(curr_block != p->decl_block->block);
  582. {
  583. LLVMTypeRef ftp = lb_type(p->module, value.type);
  584. LLVMValueRef fn = value.value;
  585. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  586. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  587. }
  588. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  589. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  590. {
  591. unsigned param_count = LLVMCountParamTypes(fnp);
  592. GB_ASSERT(arg_count >= param_count);
  593. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  594. LLVMGetParamTypes(fnp, param_types);
  595. for (unsigned i = 0; i < param_count; i++) {
  596. LLVMTypeRef param_type = param_types[i];
  597. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  598. // LLVMTypeKind param_kind = LLVMGetTypeKind(param_type);
  599. // LLVMTypeKind arg_kind = LLVMGetTypeKind(arg_type);
  600. GB_ASSERT_MSG(
  601. arg_type == param_type,
  602. "Parameter types do not match: %s != %s, argument: %s",
  603. LLVMPrintTypeToString(arg_type),
  604. LLVMPrintTypeToString(param_type),
  605. LLVMPrintValueToString(args[i])
  606. );
  607. }
  608. }
  609. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  610. if (return_ptr.value != nullptr) {
  611. LLVMAddCallSiteAttribute(ret, 1, lb_create_enum_attribute_with_type(p->module->ctx, "sret", LLVMTypeOf(args[0])));
  612. }
  613. switch (inlining) {
  614. case ProcInlining_none:
  615. break;
  616. case ProcInlining_inline:
  617. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  618. break;
  619. case ProcInlining_no_inline:
  620. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  621. break;
  622. }
  623. lbValue res = {};
  624. res.value = ret;
  625. res.type = abi_rt;
  626. return res;
  627. }
  628. }
  629. lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  630. AstPackage *pkg = m->info->runtime_package;
  631. Entity *e = scope_lookup_current(pkg->scope, name);
  632. return lb_find_procedure_value_from_entity(m, e);
  633. }
  634. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  635. String name = make_string_c(c_name);
  636. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  637. return lb_emit_call(p, proc, args);
  638. }
  639. lbValue lb_emit_conjugate(lbProcedure *p, lbValue val, Type *type) {
  640. lbValue res = {};
  641. Type *t = val.type;
  642. if (is_type_complex(t)) {
  643. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  644. lbValue real = lb_emit_struct_ev(p, val, 0);
  645. lbValue imag = lb_emit_struct_ev(p, val, 1);
  646. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  647. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  648. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  649. } else if (is_type_quaternion(t)) {
  650. // @QuaternionLayout
  651. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  652. lbValue real = lb_emit_struct_ev(p, val, 3);
  653. lbValue imag = lb_emit_struct_ev(p, val, 0);
  654. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  655. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  656. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  657. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  658. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  659. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  660. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  661. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  662. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  663. } else if (is_type_array_like(t)) {
  664. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  665. Type *elem_type = base_array_type(t);
  666. i64 count = get_array_type_count(t);
  667. for (i64 i = 0; i < count; i++) {
  668. lbValue dst = lb_emit_array_epi(p, res, i);
  669. lbValue elem = lb_emit_struct_ev(p, val, cast(i32)i);
  670. elem = lb_emit_conjugate(p, elem, elem_type);
  671. lb_emit_store(p, dst, elem);
  672. }
  673. } else if (is_type_matrix(t)) {
  674. Type *mt = base_type(t);
  675. GB_ASSERT(mt->kind == Type_Matrix);
  676. Type *elem_type = mt->Matrix.elem;
  677. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  678. for (i64 j = 0; j < mt->Matrix.column_count; j++) {
  679. for (i64 i = 0; i < mt->Matrix.row_count; i++) {
  680. lbValue dst = lb_emit_matrix_epi(p, res, i, j);
  681. lbValue elem = lb_emit_matrix_ev(p, val, i, j);
  682. elem = lb_emit_conjugate(p, elem, elem_type);
  683. lb_emit_store(p, dst, elem);
  684. }
  685. }
  686. }
  687. return lb_emit_load(p, res);
  688. }
  689. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_copy_elision_hint) {
  690. lbModule *m = p->module;
  691. Type *pt = base_type(value.type);
  692. GB_ASSERT(pt->kind == Type_Proc);
  693. Type *results = pt->Proc.results;
  694. lbAddr context_ptr = {};
  695. if (pt->Proc.calling_convention == ProcCC_Odin) {
  696. context_ptr = lb_find_or_generate_context_ptr(p);
  697. }
  698. defer (if (pt->Proc.diverging) {
  699. LLVMBuildUnreachable(p->builder);
  700. });
  701. bool is_c_vararg = pt->Proc.c_vararg;
  702. isize param_count = pt->Proc.param_count;
  703. if (is_c_vararg) {
  704. GB_ASSERT(param_count-1 <= args.count);
  705. param_count -= 1;
  706. } else {
  707. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  708. }
  709. lbValue result = {};
  710. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  711. {
  712. lbFunctionType *ft = lb_get_function_type(m, p, pt);
  713. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  714. unsigned param_index = 0;
  715. for (isize i = 0; i < param_count; i++) {
  716. Entity *e = pt->Proc.params->Tuple.variables[i];
  717. if (e->kind != Entity_Variable) {
  718. continue;
  719. }
  720. GB_ASSERT(e->flags & EntityFlag_Param);
  721. Type *original_type = e->type;
  722. lbArgType *arg = &ft->args[param_index];
  723. if (arg->kind == lbArg_Ignore) {
  724. continue;
  725. }
  726. lbValue x = lb_emit_conv(p, args[i], original_type);
  727. LLVMTypeRef xt = lb_type(p->module, x.type);
  728. if (arg->kind == lbArg_Direct) {
  729. LLVMTypeRef abi_type = arg->cast_type;
  730. if (!abi_type) {
  731. abi_type = arg->type;
  732. }
  733. if (xt == abi_type) {
  734. array_add(&processed_args, x);
  735. } else {
  736. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  737. array_add(&processed_args, x);
  738. }
  739. } else if (arg->kind == lbArg_Indirect) {
  740. lbValue ptr = {};
  741. if (arg->is_byval) {
  742. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  743. } else if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  744. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  745. // i.e. `T const &` in C++
  746. ptr = lb_address_from_load_or_generate_local(p, x);
  747. } else {
  748. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  749. }
  750. array_add(&processed_args, ptr);
  751. }
  752. param_index += 1;
  753. }
  754. if (is_c_vararg) {
  755. for (isize i = processed_args.count; i < args.count; i++) {
  756. array_add(&processed_args, args[i]);
  757. }
  758. }
  759. if (inlining == ProcInlining_none) {
  760. inlining = p->inlining;
  761. }
  762. Type *rt = reduce_tuple_to_single_type(results);
  763. if (return_by_pointer) {
  764. lbValue return_ptr = {};
  765. if (use_copy_elision_hint && p->copy_elision_hint.ptr.value != nullptr) {
  766. if (are_types_identical(type_deref(p->copy_elision_hint.ptr.type), rt)) {
  767. return_ptr = lb_consume_copy_elision_hint(p);
  768. }
  769. }
  770. if (return_ptr.value == nullptr) {
  771. lbAddr r = lb_add_local_generated(p, rt, true);
  772. return_ptr = r.addr;
  773. }
  774. GB_ASSERT(is_type_pointer(return_ptr.type));
  775. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  776. result = lb_emit_load(p, return_ptr);
  777. } else if (rt != nullptr) {
  778. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  779. if (ft->ret.cast_type) {
  780. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  781. }
  782. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  783. result.type = rt;
  784. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  785. result.type = t_llvm_bool;
  786. }
  787. if (!is_type_tuple(rt)) {
  788. result = lb_emit_conv(p, result, rt);
  789. }
  790. } else {
  791. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  792. }
  793. }
  794. Entity **found = map_get(&p->module->procedure_values, value.value);
  795. if (found != nullptr) {
  796. Entity *e = *found;
  797. if (e != nullptr && entity_has_deferred_procedure(e)) {
  798. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  799. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  800. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  801. auto in_args = args;
  802. Array<lbValue> result_as_args = {};
  803. switch (kind) {
  804. case DeferredProcedure_none:
  805. break;
  806. case DeferredProcedure_in:
  807. result_as_args = in_args;
  808. break;
  809. case DeferredProcedure_out:
  810. result_as_args = lb_value_to_array(p, result);
  811. break;
  812. case DeferredProcedure_in_out:
  813. {
  814. auto out_args = lb_value_to_array(p, result);
  815. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  816. array_copy(&result_as_args, in_args, 0);
  817. array_copy(&result_as_args, out_args, in_args.count);
  818. }
  819. break;
  820. }
  821. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  822. }
  823. }
  824. return result;
  825. }
  826. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  827. ast_node(ce, CallExpr, expr);
  828. switch (id) {
  829. case BuiltinProc_DIRECTIVE: {
  830. ast_node(bd, BasicDirective, ce->proc);
  831. String name = bd->name.string;
  832. GB_ASSERT(name == "location");
  833. String procedure = p->entity->token.string;
  834. TokenPos pos = ast_token(ce->proc).pos;
  835. if (ce->args.count > 0) {
  836. Ast *ident = unselector_expr(ce->args[0]);
  837. GB_ASSERT(ident->kind == Ast_Ident);
  838. Entity *e = entity_of_node(ident);
  839. GB_ASSERT(e != nullptr);
  840. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  841. procedure = e->parent_proc_decl->entity->token.string;
  842. } else {
  843. procedure = str_lit("");
  844. }
  845. pos = e->token.pos;
  846. }
  847. return lb_emit_source_code_location(p, procedure, pos);
  848. }
  849. case BuiltinProc_type_info_of: {
  850. Ast *arg = ce->args[0];
  851. TypeAndValue tav = type_and_value_of_expr(arg);
  852. if (tav.mode == Addressing_Type) {
  853. Type *t = default_type(type_of_expr(arg));
  854. return lb_type_info(p->module, t);
  855. }
  856. GB_ASSERT(is_type_typeid(tav.type));
  857. auto args = array_make<lbValue>(permanent_allocator(), 1);
  858. args[0] = lb_build_expr(p, arg);
  859. return lb_emit_runtime_call(p, "__type_info_of", args);
  860. }
  861. case BuiltinProc_typeid_of: {
  862. Ast *arg = ce->args[0];
  863. TypeAndValue tav = type_and_value_of_expr(arg);
  864. GB_ASSERT(tav.mode == Addressing_Type);
  865. Type *t = default_type(type_of_expr(arg));
  866. return lb_typeid(p->module, t);
  867. }
  868. case BuiltinProc_len: {
  869. lbValue v = lb_build_expr(p, ce->args[0]);
  870. Type *t = base_type(v.type);
  871. if (is_type_pointer(t)) {
  872. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  873. v = lb_emit_load(p, v);
  874. t = type_deref(t);
  875. }
  876. if (is_type_cstring(t)) {
  877. return lb_cstring_len(p, v);
  878. } else if (is_type_string(t)) {
  879. return lb_string_len(p, v);
  880. } else if (is_type_array(t)) {
  881. GB_PANIC("Array lengths are constant");
  882. } else if (is_type_slice(t) || is_type_relative_slice(t)) {
  883. return lb_slice_len(p, v);
  884. } else if (is_type_dynamic_array(t)) {
  885. return lb_dynamic_array_len(p, v);
  886. } else if (is_type_map(t)) {
  887. return lb_map_len(p, v);
  888. } else if (is_type_soa_struct(t)) {
  889. return lb_soa_struct_len(p, v);
  890. }
  891. GB_PANIC("Unreachable");
  892. break;
  893. }
  894. case BuiltinProc_cap: {
  895. lbValue v = lb_build_expr(p, ce->args[0]);
  896. Type *t = base_type(v.type);
  897. if (is_type_pointer(t)) {
  898. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  899. v = lb_emit_load(p, v);
  900. t = type_deref(t);
  901. }
  902. if (is_type_string(t)) {
  903. GB_PANIC("Unreachable");
  904. } else if (is_type_array(t)) {
  905. GB_PANIC("Array lengths are constant");
  906. } else if (is_type_slice(t) || is_type_relative_slice(t)) {
  907. return lb_slice_len(p, v);
  908. } else if (is_type_dynamic_array(t)) {
  909. return lb_dynamic_array_cap(p, v);
  910. } else if (is_type_map(t)) {
  911. return lb_map_cap(p, v);
  912. } else if (is_type_soa_struct(t)) {
  913. return lb_soa_struct_cap(p, v);
  914. }
  915. GB_PANIC("Unreachable");
  916. break;
  917. }
  918. case BuiltinProc_swizzle: {
  919. isize index_count = ce->args.count-1;
  920. if (is_type_simd_vector(tv.type)) {
  921. lbValue vec = lb_build_expr(p, ce->args[0]);
  922. if (index_count == 0) {
  923. return vec;
  924. }
  925. unsigned mask_len = cast(unsigned)index_count;
  926. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  927. for (isize i = 1; i < ce->args.count; i++) {
  928. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  929. GB_ASSERT(is_type_integer(tv.type));
  930. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  931. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  932. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  933. }
  934. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  935. LLVMValueRef v1 = vec.value;
  936. LLVMValueRef v2 = vec.value;
  937. lbValue res = {};
  938. res.type = tv.type;
  939. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  940. return res;
  941. }
  942. lbAddr addr = lb_build_array_swizzle_addr(p, ce, tv);
  943. return lb_addr_load(p, addr);
  944. }
  945. case BuiltinProc_complex: {
  946. lbValue real = lb_build_expr(p, ce->args[0]);
  947. lbValue imag = lb_build_expr(p, ce->args[1]);
  948. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  949. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  950. Type *ft = base_complex_elem_type(tv.type);
  951. real = lb_emit_conv(p, real, ft);
  952. imag = lb_emit_conv(p, imag, ft);
  953. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  954. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  955. return lb_emit_load(p, dst);
  956. }
  957. case BuiltinProc_quaternion: {
  958. lbValue real = lb_build_expr(p, ce->args[0]);
  959. lbValue imag = lb_build_expr(p, ce->args[1]);
  960. lbValue jmag = lb_build_expr(p, ce->args[2]);
  961. lbValue kmag = lb_build_expr(p, ce->args[3]);
  962. // @QuaternionLayout
  963. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  964. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  965. Type *ft = base_complex_elem_type(tv.type);
  966. real = lb_emit_conv(p, real, ft);
  967. imag = lb_emit_conv(p, imag, ft);
  968. jmag = lb_emit_conv(p, jmag, ft);
  969. kmag = lb_emit_conv(p, kmag, ft);
  970. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  971. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  972. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  973. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  974. return lb_emit_load(p, dst);
  975. }
  976. case BuiltinProc_real: {
  977. lbValue val = lb_build_expr(p, ce->args[0]);
  978. if (is_type_complex(val.type)) {
  979. lbValue real = lb_emit_struct_ev(p, val, 0);
  980. return lb_emit_conv(p, real, tv.type);
  981. } else if (is_type_quaternion(val.type)) {
  982. // @QuaternionLayout
  983. lbValue real = lb_emit_struct_ev(p, val, 3);
  984. return lb_emit_conv(p, real, tv.type);
  985. }
  986. GB_PANIC("invalid type for real");
  987. return {};
  988. }
  989. case BuiltinProc_imag: {
  990. lbValue val = lb_build_expr(p, ce->args[0]);
  991. if (is_type_complex(val.type)) {
  992. lbValue imag = lb_emit_struct_ev(p, val, 1);
  993. return lb_emit_conv(p, imag, tv.type);
  994. } else if (is_type_quaternion(val.type)) {
  995. // @QuaternionLayout
  996. lbValue imag = lb_emit_struct_ev(p, val, 0);
  997. return lb_emit_conv(p, imag, tv.type);
  998. }
  999. GB_PANIC("invalid type for imag");
  1000. return {};
  1001. }
  1002. case BuiltinProc_jmag: {
  1003. lbValue val = lb_build_expr(p, ce->args[0]);
  1004. if (is_type_quaternion(val.type)) {
  1005. // @QuaternionLayout
  1006. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1007. return lb_emit_conv(p, imag, tv.type);
  1008. }
  1009. GB_PANIC("invalid type for jmag");
  1010. return {};
  1011. }
  1012. case BuiltinProc_kmag: {
  1013. lbValue val = lb_build_expr(p, ce->args[0]);
  1014. if (is_type_quaternion(val.type)) {
  1015. // @QuaternionLayout
  1016. lbValue imag = lb_emit_struct_ev(p, val, 2);
  1017. return lb_emit_conv(p, imag, tv.type);
  1018. }
  1019. GB_PANIC("invalid type for kmag");
  1020. return {};
  1021. }
  1022. case BuiltinProc_conj: {
  1023. lbValue val = lb_build_expr(p, ce->args[0]);
  1024. return lb_emit_conjugate(p, val, tv.type);
  1025. }
  1026. case BuiltinProc_expand_to_tuple: {
  1027. lbValue val = lb_build_expr(p, ce->args[0]);
  1028. Type *t = base_type(val.type);
  1029. if (!is_type_tuple(tv.type)) {
  1030. if (t->kind == Type_Struct) {
  1031. GB_ASSERT(t->Struct.fields.count == 1);
  1032. return lb_emit_struct_ev(p, val, 0);
  1033. } else if (t->kind == Type_Array) {
  1034. GB_ASSERT(t->Array.count == 1);
  1035. return lb_emit_array_epi(p, val, 0);
  1036. } else {
  1037. GB_PANIC("Unknown type of expand_to_tuple");
  1038. }
  1039. }
  1040. GB_ASSERT(is_type_tuple(tv.type));
  1041. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1042. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  1043. if (t->kind == Type_Struct) {
  1044. for_array(src_index, t->Struct.fields) {
  1045. Entity *field = t->Struct.fields[src_index];
  1046. i32 field_index = field->Variable.field_index;
  1047. lbValue f = lb_emit_struct_ev(p, val, field_index);
  1048. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  1049. lb_emit_store(p, ep, f);
  1050. }
  1051. } else if (is_type_array_like(t)) {
  1052. // TODO(bill): Clean-up this code
  1053. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  1054. i32 n = cast(i32)get_array_type_count(t);
  1055. for (i32 i = 0; i < n; i++) {
  1056. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  1057. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  1058. lb_emit_store(p, ep, f);
  1059. }
  1060. } else {
  1061. GB_PANIC("Unknown type of expand_to_tuple");
  1062. }
  1063. return lb_emit_load(p, tuple);
  1064. }
  1065. case BuiltinProc_min: {
  1066. Type *t = type_of_expr(expr);
  1067. if (ce->args.count == 2) {
  1068. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1069. } else {
  1070. lbValue x = lb_build_expr(p, ce->args[0]);
  1071. for (isize i = 1; i < ce->args.count; i++) {
  1072. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  1073. }
  1074. return x;
  1075. }
  1076. }
  1077. case BuiltinProc_max: {
  1078. Type *t = type_of_expr(expr);
  1079. if (ce->args.count == 2) {
  1080. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1081. } else {
  1082. lbValue x = lb_build_expr(p, ce->args[0]);
  1083. for (isize i = 1; i < ce->args.count; i++) {
  1084. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  1085. }
  1086. return x;
  1087. }
  1088. }
  1089. case BuiltinProc_abs: {
  1090. lbValue x = lb_build_expr(p, ce->args[0]);
  1091. Type *t = x.type;
  1092. if (is_type_unsigned(t)) {
  1093. return x;
  1094. }
  1095. if (is_type_quaternion(t)) {
  1096. i64 sz = 8*type_size_of(t);
  1097. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1098. args[0] = x;
  1099. switch (sz) {
  1100. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  1101. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  1102. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  1103. }
  1104. GB_PANIC("Unknown complex type");
  1105. } else if (is_type_complex(t)) {
  1106. i64 sz = 8*type_size_of(t);
  1107. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1108. args[0] = x;
  1109. switch (sz) {
  1110. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  1111. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  1112. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  1113. }
  1114. GB_PANIC("Unknown complex type");
  1115. }
  1116. lbValue zero = lb_const_nil(p->module, t);
  1117. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  1118. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  1119. return lb_emit_select(p, cond, neg, x);
  1120. }
  1121. case BuiltinProc_clamp:
  1122. return lb_emit_clamp(p, type_of_expr(expr),
  1123. lb_build_expr(p, ce->args[0]),
  1124. lb_build_expr(p, ce->args[1]),
  1125. lb_build_expr(p, ce->args[2]));
  1126. case BuiltinProc_soa_zip:
  1127. return lb_soa_zip(p, ce, tv);
  1128. case BuiltinProc_soa_unzip:
  1129. return lb_soa_unzip(p, ce, tv);
  1130. case BuiltinProc_transpose:
  1131. {
  1132. lbValue m = lb_build_expr(p, ce->args[0]);
  1133. return lb_emit_matrix_tranpose(p, m, tv.type);
  1134. }
  1135. case BuiltinProc_outer_product:
  1136. {
  1137. lbValue a = lb_build_expr(p, ce->args[0]);
  1138. lbValue b = lb_build_expr(p, ce->args[1]);
  1139. return lb_emit_outer_product(p, a, b, tv.type);
  1140. }
  1141. case BuiltinProc_hadamard_product:
  1142. {
  1143. lbValue a = lb_build_expr(p, ce->args[0]);
  1144. lbValue b = lb_build_expr(p, ce->args[1]);
  1145. if (is_type_array(tv.type)) {
  1146. return lb_emit_arith(p, Token_Mul, a, b, tv.type);
  1147. }
  1148. GB_ASSERT(is_type_matrix(tv.type));
  1149. return lb_emit_arith_matrix(p, Token_Mul, a, b, tv.type, true);
  1150. }
  1151. case BuiltinProc_matrix_flatten:
  1152. {
  1153. lbValue m = lb_build_expr(p, ce->args[0]);
  1154. return lb_emit_matrix_flatten(p, m, tv.type);
  1155. }
  1156. // "Intrinsics"
  1157. case BuiltinProc_alloca:
  1158. {
  1159. lbValue sz = lb_build_expr(p, ce->args[0]);
  1160. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  1161. lbValue res = {};
  1162. res.type = t_u8_ptr;
  1163. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  1164. LLVMSetAlignment(res.value, cast(unsigned)al);
  1165. return res;
  1166. }
  1167. case BuiltinProc_cpu_relax:
  1168. if (build_context.metrics.arch == TargetArch_i386 ||
  1169. build_context.metrics.arch == TargetArch_amd64) {
  1170. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1171. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("pause"), {}, true);
  1172. GB_ASSERT(the_asm != nullptr);
  1173. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1174. } else if (build_context.metrics.arch == TargetArch_arm64) {
  1175. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1176. // NOTE(bill, 2022-03-30): `isb` appears to a better option that `yield`
  1177. // See: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8258604
  1178. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("isb"), {}, true);
  1179. GB_ASSERT(the_asm != nullptr);
  1180. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1181. } else {
  1182. // NOTE: default to something to prevent optimization
  1183. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1184. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit(""), {}, true);
  1185. GB_ASSERT(the_asm != nullptr);
  1186. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1187. }
  1188. return {};
  1189. case BuiltinProc_debug_trap:
  1190. case BuiltinProc_trap:
  1191. {
  1192. char const *name = nullptr;
  1193. switch (id) {
  1194. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  1195. case BuiltinProc_trap: name = "llvm.trap"; break;
  1196. }
  1197. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1198. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  1199. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  1200. LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  1201. if (id == BuiltinProc_trap) {
  1202. LLVMBuildUnreachable(p->builder);
  1203. }
  1204. return {};
  1205. }
  1206. case BuiltinProc_read_cycle_counter:
  1207. {
  1208. lbValue res = {};
  1209. res.type = tv.type;
  1210. if (build_context.metrics.arch == TargetArch_arm64) {
  1211. LLVMTypeRef func_type = LLVMFunctionType(LLVMInt64TypeInContext(p->module->ctx), nullptr, 0, false);
  1212. bool has_side_effects = false;
  1213. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("mrs x9, cntvct_el0"), str_lit("=r"), has_side_effects);
  1214. GB_ASSERT(the_asm != nullptr);
  1215. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1216. } else {
  1217. char const *name = "llvm.readcyclecounter";
  1218. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1219. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  1220. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  1221. res.value = LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  1222. }
  1223. return res;
  1224. }
  1225. case BuiltinProc_count_trailing_zeros:
  1226. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1227. case BuiltinProc_count_leading_zeros:
  1228. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1229. case BuiltinProc_count_ones:
  1230. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  1231. case BuiltinProc_count_zeros:
  1232. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1233. case BuiltinProc_reverse_bits:
  1234. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  1235. case BuiltinProc_byte_swap:
  1236. {
  1237. lbValue x = lb_build_expr(p, ce->args[0]);
  1238. x = lb_emit_conv(p, x, tv.type);
  1239. return lb_emit_byte_swap(p, x, tv.type);
  1240. }
  1241. case BuiltinProc_overflow_add:
  1242. case BuiltinProc_overflow_sub:
  1243. case BuiltinProc_overflow_mul:
  1244. {
  1245. Type *main_type = tv.type;
  1246. Type *type = main_type;
  1247. if (is_type_tuple(main_type)) {
  1248. type = main_type->Tuple.variables[0]->type;
  1249. }
  1250. lbValue x = lb_build_expr(p, ce->args[0]);
  1251. lbValue y = lb_build_expr(p, ce->args[1]);
  1252. x = lb_emit_conv(p, x, type);
  1253. y = lb_emit_conv(p, y, type);
  1254. char const *name = nullptr;
  1255. if (is_type_unsigned(type)) {
  1256. switch (id) {
  1257. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  1258. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  1259. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  1260. }
  1261. } else {
  1262. switch (id) {
  1263. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  1264. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  1265. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  1266. }
  1267. }
  1268. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1269. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1270. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1271. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1272. LLVMValueRef args[2] = {};
  1273. args[0] = x.value;
  1274. args[1] = y.value;
  1275. lbValue res = {};
  1276. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1277. if (is_type_tuple(main_type)) {
  1278. Type *res_type = nullptr;
  1279. gbAllocator a = permanent_allocator();
  1280. res_type = alloc_type_tuple();
  1281. slice_init(&res_type->Tuple.variables, a, 2);
  1282. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  1283. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  1284. res.type = res_type;
  1285. } else {
  1286. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  1287. res.type = type;
  1288. }
  1289. return res;
  1290. }
  1291. case BuiltinProc_sqrt:
  1292. {
  1293. Type *type = tv.type;
  1294. lbValue x = lb_build_expr(p, ce->args[0]);
  1295. x = lb_emit_conv(p, x, type);
  1296. char const *name = "llvm.sqrt";
  1297. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1298. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1299. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1300. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1301. LLVMValueRef args[1] = {};
  1302. args[0] = x.value;
  1303. lbValue res = {};
  1304. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1305. res.type = type;
  1306. return res;
  1307. }
  1308. case BuiltinProc_mem_copy:
  1309. {
  1310. lbValue dst = lb_build_expr(p, ce->args[0]);
  1311. lbValue src = lb_build_expr(p, ce->args[1]);
  1312. lbValue len = lb_build_expr(p, ce->args[2]);
  1313. lb_mem_copy_overlapping(p, dst, src, len, false);
  1314. return {};
  1315. }
  1316. case BuiltinProc_mem_copy_non_overlapping:
  1317. {
  1318. lbValue dst = lb_build_expr(p, ce->args[0]);
  1319. lbValue src = lb_build_expr(p, ce->args[1]);
  1320. lbValue len = lb_build_expr(p, ce->args[2]);
  1321. lb_mem_copy_non_overlapping(p, dst, src, len, false);
  1322. return {};
  1323. }
  1324. case BuiltinProc_mem_zero:
  1325. {
  1326. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1327. lbValue len = lb_build_expr(p, ce->args[1]);
  1328. ptr = lb_emit_conv(p, ptr, t_rawptr);
  1329. len = lb_emit_conv(p, len, t_int);
  1330. unsigned alignment = 1;
  1331. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, false);
  1332. return {};
  1333. }
  1334. case BuiltinProc_mem_zero_volatile:
  1335. {
  1336. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1337. lbValue len = lb_build_expr(p, ce->args[1]);
  1338. ptr = lb_emit_conv(p, ptr, t_rawptr);
  1339. len = lb_emit_conv(p, len, t_int);
  1340. unsigned alignment = 1;
  1341. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, true);
  1342. return {};
  1343. }
  1344. case BuiltinProc_ptr_offset:
  1345. {
  1346. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1347. lbValue len = lb_build_expr(p, ce->args[1]);
  1348. len = lb_emit_conv(p, len, t_int);
  1349. LLVMValueRef indices[1] = {
  1350. len.value,
  1351. };
  1352. lbValue res = {};
  1353. res.type = tv.type;
  1354. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, gb_count_of(indices), "");
  1355. return res;
  1356. }
  1357. case BuiltinProc_ptr_sub:
  1358. {
  1359. lbValue ptr0 = lb_build_expr(p, ce->args[0]);
  1360. lbValue ptr1 = lb_build_expr(p, ce->args[1]);
  1361. LLVMTypeRef type_int = lb_type(p->module, t_int);
  1362. LLVMValueRef diff = LLVMBuildPtrDiff(p->builder, ptr0.value, ptr1.value, "");
  1363. diff = LLVMBuildIntCast2(p->builder, diff, type_int, /*signed*/true, "");
  1364. lbValue res = {};
  1365. res.type = t_int;
  1366. res.value = diff;
  1367. return res;
  1368. }
  1369. // TODO(bill): Which is correct?
  1370. case BuiltinProc_atomic_thread_fence:
  1371. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), false, "");
  1372. return {};
  1373. case BuiltinProc_atomic_signal_fence:
  1374. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), true, "");
  1375. return {};
  1376. case BuiltinProc_volatile_store:
  1377. case BuiltinProc_atomic_store:
  1378. case BuiltinProc_atomic_store_explicit: {
  1379. lbValue dst = lb_build_expr(p, ce->args[0]);
  1380. lbValue val = lb_build_expr(p, ce->args[1]);
  1381. val = lb_emit_conv(p, val, type_deref(dst.type));
  1382. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  1383. switch (id) {
  1384. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  1385. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  1386. case BuiltinProc_atomic_store_explicit: LLVMSetOrdering(instr, llvm_atomic_ordering_from_odin(ce->args[2])); break;
  1387. }
  1388. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  1389. return {};
  1390. }
  1391. case BuiltinProc_volatile_load:
  1392. case BuiltinProc_atomic_load:
  1393. case BuiltinProc_atomic_load_explicit: {
  1394. lbValue dst = lb_build_expr(p, ce->args[0]);
  1395. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  1396. switch (id) {
  1397. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  1398. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  1399. case BuiltinProc_atomic_load_explicit: LLVMSetOrdering(instr, llvm_atomic_ordering_from_odin(ce->args[1])); break;
  1400. }
  1401. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  1402. lbValue res = {};
  1403. res.value = instr;
  1404. res.type = type_deref(dst.type);
  1405. return res;
  1406. }
  1407. case BuiltinProc_unaligned_store:
  1408. {
  1409. lbValue dst = lb_build_expr(p, ce->args[0]);
  1410. lbValue src = lb_build_expr(p, ce->args[1]);
  1411. src = lb_address_from_load_or_generate_local(p, src);
  1412. Type *t = type_deref(dst.type);
  1413. lb_mem_copy_non_overlapping(p, dst, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  1414. return {};
  1415. }
  1416. case BuiltinProc_unaligned_load:
  1417. {
  1418. lbValue src = lb_build_expr(p, ce->args[0]);
  1419. Type *t = type_deref(src.type);
  1420. lbAddr dst = lb_add_local_generated(p, t, false);
  1421. lb_mem_copy_non_overlapping(p, dst.addr, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  1422. return lb_addr_load(p, dst);
  1423. }
  1424. case BuiltinProc_atomic_add:
  1425. case BuiltinProc_atomic_sub:
  1426. case BuiltinProc_atomic_and:
  1427. case BuiltinProc_atomic_nand:
  1428. case BuiltinProc_atomic_or:
  1429. case BuiltinProc_atomic_xor:
  1430. case BuiltinProc_atomic_exchange:
  1431. case BuiltinProc_atomic_add_explicit:
  1432. case BuiltinProc_atomic_sub_explicit:
  1433. case BuiltinProc_atomic_and_explicit:
  1434. case BuiltinProc_atomic_nand_explicit:
  1435. case BuiltinProc_atomic_or_explicit:
  1436. case BuiltinProc_atomic_xor_explicit:
  1437. case BuiltinProc_atomic_exchange_explicit: {
  1438. lbValue dst = lb_build_expr(p, ce->args[0]);
  1439. lbValue val = lb_build_expr(p, ce->args[1]);
  1440. val = lb_emit_conv(p, val, type_deref(dst.type));
  1441. LLVMAtomicRMWBinOp op = {};
  1442. LLVMAtomicOrdering ordering = {};
  1443. switch (id) {
  1444. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1445. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1446. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1447. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1448. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1449. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1450. case BuiltinProc_atomic_exchange: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1451. case BuiltinProc_atomic_add_explicit: op = LLVMAtomicRMWBinOpAdd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  1452. case BuiltinProc_atomic_sub_explicit: op = LLVMAtomicRMWBinOpSub; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  1453. case BuiltinProc_atomic_and_explicit: op = LLVMAtomicRMWBinOpAnd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  1454. case BuiltinProc_atomic_nand_explicit: op = LLVMAtomicRMWBinOpNand; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  1455. case BuiltinProc_atomic_or_explicit: op = LLVMAtomicRMWBinOpOr; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  1456. case BuiltinProc_atomic_xor_explicit: op = LLVMAtomicRMWBinOpXor; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  1457. case BuiltinProc_atomic_exchange_explicit: op = LLVMAtomicRMWBinOpXchg; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  1458. }
  1459. lbValue res = {};
  1460. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  1461. res.type = tv.type;
  1462. return res;
  1463. }
  1464. case BuiltinProc_atomic_compare_exchange_strong:
  1465. case BuiltinProc_atomic_compare_exchange_weak:
  1466. case BuiltinProc_atomic_compare_exchange_strong_explicit:
  1467. case BuiltinProc_atomic_compare_exchange_weak_explicit: {
  1468. lbValue address = lb_build_expr(p, ce->args[0]);
  1469. Type *elem = type_deref(address.type);
  1470. lbValue old_value = lb_build_expr(p, ce->args[1]);
  1471. lbValue new_value = lb_build_expr(p, ce->args[2]);
  1472. old_value = lb_emit_conv(p, old_value, elem);
  1473. new_value = lb_emit_conv(p, new_value, elem);
  1474. LLVMAtomicOrdering success_ordering = {};
  1475. LLVMAtomicOrdering failure_ordering = {};
  1476. LLVMBool weak = false;
  1477. switch (id) {
  1478. case BuiltinProc_atomic_compare_exchange_strong: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  1479. case BuiltinProc_atomic_compare_exchange_weak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  1480. 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;
  1481. 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;
  1482. }
  1483. // TODO(bill): Figure out how to make it weak
  1484. LLVMBool single_threaded = false;
  1485. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  1486. p->builder, address.value,
  1487. old_value.value, new_value.value,
  1488. success_ordering,
  1489. failure_ordering,
  1490. single_threaded
  1491. );
  1492. LLVMSetWeak(value, weak);
  1493. if (tv.type->kind == Type_Tuple) {
  1494. Type *fix_typed = alloc_type_tuple();
  1495. slice_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  1496. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  1497. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  1498. lbValue res = {};
  1499. res.value = value;
  1500. res.type = fix_typed;
  1501. return res;
  1502. } else {
  1503. lbValue res = {};
  1504. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  1505. res.type = tv.type;
  1506. return res;
  1507. }
  1508. }
  1509. case BuiltinProc_type_equal_proc:
  1510. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  1511. case BuiltinProc_type_hasher_proc:
  1512. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  1513. case BuiltinProc_fixed_point_mul:
  1514. case BuiltinProc_fixed_point_div:
  1515. case BuiltinProc_fixed_point_mul_sat:
  1516. case BuiltinProc_fixed_point_div_sat:
  1517. {
  1518. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  1519. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  1520. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  1521. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  1522. char const *name = nullptr;
  1523. if (is_type_unsigned(tv.type)) {
  1524. switch (id) {
  1525. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  1526. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  1527. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  1528. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  1529. }
  1530. } else {
  1531. switch (id) {
  1532. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  1533. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  1534. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  1535. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  1536. }
  1537. }
  1538. GB_ASSERT(name != nullptr);
  1539. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  1540. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1541. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1542. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1543. lbValue res = {};
  1544. LLVMValueRef args[3] = {};
  1545. args[0] = x.value;
  1546. args[1] = y.value;
  1547. args[2] = scale.value;
  1548. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1549. res.type = platform_type;
  1550. return lb_emit_conv(p, res, tv.type);
  1551. }
  1552. case BuiltinProc_expect:
  1553. {
  1554. Type *t = default_type(tv.type);
  1555. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  1556. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  1557. char const *name = "llvm.expect";
  1558. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  1559. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1560. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1561. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1562. lbValue res = {};
  1563. LLVMValueRef args[2] = {};
  1564. args[0] = x.value;
  1565. args[1] = y.value;
  1566. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1567. res.type = t;
  1568. return lb_emit_conv(p, res, t);
  1569. }
  1570. case BuiltinProc_prefetch_read_instruction:
  1571. case BuiltinProc_prefetch_read_data:
  1572. case BuiltinProc_prefetch_write_instruction:
  1573. case BuiltinProc_prefetch_write_data:
  1574. {
  1575. lbValue ptr = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_rawptr);
  1576. unsigned long long locality = cast(unsigned long long)exact_value_to_i64(ce->args[1]->tav.value);
  1577. unsigned long long rw = 0;
  1578. unsigned long long cache = 0;
  1579. switch (id) {
  1580. case BuiltinProc_prefetch_read_instruction:
  1581. rw = 0;
  1582. cache = 0;
  1583. break;
  1584. case BuiltinProc_prefetch_read_data:
  1585. rw = 0;
  1586. cache = 1;
  1587. break;
  1588. case BuiltinProc_prefetch_write_instruction:
  1589. rw = 1;
  1590. cache = 0;
  1591. break;
  1592. case BuiltinProc_prefetch_write_data:
  1593. rw = 1;
  1594. cache = 1;
  1595. break;
  1596. }
  1597. char const *name = "llvm.prefetch";
  1598. LLVMTypeRef types[1] = {lb_type(p->module, t_rawptr)};
  1599. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1600. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1601. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1602. LLVMTypeRef llvm_i32 = lb_type(p->module, t_i32);
  1603. LLVMValueRef args[4] = {};
  1604. args[0] = ptr.value;
  1605. args[1] = LLVMConstInt(llvm_i32, rw, false);
  1606. args[2] = LLVMConstInt(llvm_i32, locality, false);
  1607. args[3] = LLVMConstInt(llvm_i32, cache, false);
  1608. lbValue res = {};
  1609. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1610. res.type = nullptr;
  1611. return res;
  1612. }
  1613. case BuiltinProc___entry_point:
  1614. if (p->module->info->entry_point) {
  1615. lbValue entry_point = lb_find_procedure_value_from_entity(p->module, p->module->info->entry_point);
  1616. GB_ASSERT(entry_point.value != nullptr);
  1617. lb_emit_call(p, entry_point, {});
  1618. }
  1619. return {};
  1620. case BuiltinProc_syscall:
  1621. {
  1622. unsigned arg_count = cast(unsigned)ce->args.count;
  1623. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  1624. for_array(i, ce->args) {
  1625. lbValue arg = lb_build_expr(p, ce->args[i]);
  1626. arg = lb_emit_conv(p, arg, t_uintptr);
  1627. args[i] = arg.value;
  1628. }
  1629. LLVMTypeRef llvm_uintptr = lb_type(p->module, t_uintptr);
  1630. LLVMTypeRef *llvm_arg_types = gb_alloc_array(permanent_allocator(), LLVMTypeRef, arg_count);
  1631. for (unsigned i = 0; i < arg_count; i++) {
  1632. llvm_arg_types[i] = llvm_uintptr;
  1633. }
  1634. LLVMTypeRef func_type = LLVMFunctionType(llvm_uintptr, llvm_arg_types, arg_count, false);
  1635. LLVMValueRef inline_asm = nullptr;
  1636. switch (build_context.metrics.arch) {
  1637. case TargetArch_amd64:
  1638. {
  1639. GB_ASSERT(arg_count <= 7);
  1640. char asm_string[] = "syscall";
  1641. gbString constraints = gb_string_make(heap_allocator(), "={rax}");
  1642. for (unsigned i = 0; i < arg_count; i++) {
  1643. constraints = gb_string_appendc(constraints, ",{");
  1644. static char const *regs[] = {
  1645. "rax",
  1646. "rdi",
  1647. "rsi",
  1648. "rdx",
  1649. "r10",
  1650. "r8",
  1651. "r9"
  1652. };
  1653. constraints = gb_string_appendc(constraints, regs[i]);
  1654. constraints = gb_string_appendc(constraints, "}");
  1655. }
  1656. // The SYSCALL instruction stores the address of the
  1657. // following instruction into RCX, and RFLAGS in R11.
  1658. //
  1659. // RSP is not saved, but at least on Linux it appears
  1660. // that the kernel system-call handler does the right
  1661. // thing.
  1662. //
  1663. // Some but not all system calls will additionally
  1664. // clobber memory.
  1665. //
  1666. // TODO: FreeBSD is different and will also clobber
  1667. // R8, R9, and R10. Additionally CF is used to
  1668. // indicate an error instead of -errno.
  1669. constraints = gb_string_appendc(constraints, ",~{rcx},~{r11},~{memory}");
  1670. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  1671. }
  1672. break;
  1673. case TargetArch_i386:
  1674. {
  1675. GB_ASSERT(arg_count <= 7);
  1676. char asm_string_default[] = "int $0x80";
  1677. char *asm_string = asm_string_default;
  1678. gbString constraints = gb_string_make(heap_allocator(), "={eax}");
  1679. for (unsigned i = 0; i < gb_min(arg_count, 6); i++) {
  1680. constraints = gb_string_appendc(constraints, ",{");
  1681. static char const *regs[] = {
  1682. "eax",
  1683. "ebx",
  1684. "ecx",
  1685. "edx",
  1686. "esi",
  1687. "edi",
  1688. };
  1689. constraints = gb_string_appendc(constraints, regs[i]);
  1690. constraints = gb_string_appendc(constraints, "}");
  1691. }
  1692. if (arg_count == 7) {
  1693. char asm_string7[] = "push %[arg6]\npush %%ebp\nmov 4(%%esp), %%ebp\nint $0x80\npop %%ebp\nadd $4, %%esp";
  1694. asm_string = asm_string7;
  1695. constraints = gb_string_appendc(constraints, ",rm");
  1696. }
  1697. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  1698. }
  1699. break;
  1700. case TargetArch_arm64:
  1701. {
  1702. GB_ASSERT(arg_count <= 7);
  1703. if(build_context.metrics.os == TargetOs_darwin) {
  1704. char asm_string[] = "svc #0x80";
  1705. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  1706. for (unsigned i = 0; i < arg_count; i++) {
  1707. constraints = gb_string_appendc(constraints, ",{");
  1708. static char const *regs[] = {
  1709. "x16",
  1710. "x0",
  1711. "x1",
  1712. "x2",
  1713. "x3",
  1714. "x4",
  1715. "x5",
  1716. };
  1717. constraints = gb_string_appendc(constraints, regs[i]);
  1718. constraints = gb_string_appendc(constraints, "}");
  1719. }
  1720. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  1721. } else {
  1722. char asm_string[] = "svc #0";
  1723. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  1724. for (unsigned i = 0; i < arg_count; i++) {
  1725. constraints = gb_string_appendc(constraints, ",{");
  1726. static char const *regs[] = {
  1727. "x8",
  1728. "x0",
  1729. "x1",
  1730. "x2",
  1731. "x3",
  1732. "x4",
  1733. "x5",
  1734. };
  1735. constraints = gb_string_appendc(constraints, regs[i]);
  1736. constraints = gb_string_appendc(constraints, "}");
  1737. }
  1738. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  1739. }
  1740. }
  1741. break;
  1742. case TargetArch_arm32:
  1743. {
  1744. // TODO(bill): Check this is correct
  1745. GB_ASSERT(arg_count <= 7);
  1746. char asm_string[] = "svc #0";
  1747. gbString constraints = gb_string_make(heap_allocator(), "={r0}");
  1748. for (unsigned i = 0; i < arg_count; i++) {
  1749. constraints = gb_string_appendc(constraints, ",{");
  1750. static char const *regs[] = {
  1751. "r8",
  1752. "r0",
  1753. "r1",
  1754. "r2",
  1755. "r3",
  1756. "r4",
  1757. "r5",
  1758. };
  1759. constraints = gb_string_appendc(constraints, regs[i]);
  1760. constraints = gb_string_appendc(constraints, "}");
  1761. }
  1762. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  1763. }
  1764. break;
  1765. default:
  1766. GB_PANIC("Unsupported platform");
  1767. }
  1768. lbValue res = {};
  1769. res.value = LLVMBuildCall2(p->builder, func_type, inline_asm, args, arg_count, "");
  1770. res.type = t_uintptr;
  1771. return res;
  1772. }
  1773. case BuiltinProc_objc_send:
  1774. return lb_handle_objc_send(p, expr);
  1775. case BuiltinProc_objc_find_selector: return lb_handle_objc_find_selector(p, expr);
  1776. case BuiltinProc_objc_find_class: return lb_handle_objc_find_class(p, expr);
  1777. case BuiltinProc_objc_register_selector: return lb_handle_objc_register_selector(p, expr);
  1778. case BuiltinProc_objc_register_class: return lb_handle_objc_register_class(p, expr);
  1779. case BuiltinProc_constant_utf16_cstring:
  1780. {
  1781. auto const encode_surrogate_pair = [](Rune r, u16 *r1, u16 *r2) {
  1782. if (r < 0x10000 || r > 0x10ffff) {
  1783. *r1 = 0xfffd;
  1784. *r2 = 0xfffd;
  1785. } else {
  1786. r -= 0x10000;
  1787. *r1 = 0xd800 + ((r>>10)&0x3ff);
  1788. *r2 = 0xdc00 + (r&0x3ff);
  1789. }
  1790. };
  1791. lbModule *m = p->module;
  1792. auto tav = type_and_value_of_expr(ce->args[0]);
  1793. GB_ASSERT(tav.value.kind == ExactValue_String);
  1794. String value = tav.value.value_string;
  1795. LLVMTypeRef llvm_u16 = lb_type(m, t_u16);
  1796. isize max_len = value.len*2 + 1;
  1797. LLVMValueRef *buffer = gb_alloc_array(temporary_allocator(), LLVMValueRef, max_len);
  1798. isize n = 0;
  1799. while (value.len > 0) {
  1800. Rune r = 0;
  1801. isize w = gb_utf8_decode(value.text, value.len, &r);
  1802. value.text += w;
  1803. value.len -= w;
  1804. if ((0 <= r && r < 0xd800) || (0xe000 <= r && r < 0x10000)) {
  1805. buffer[n++] = LLVMConstInt(llvm_u16, cast(u16)r, false);
  1806. } else if (0x10000 <= r && r <= 0x10ffff) {
  1807. u16 r1, r2;
  1808. encode_surrogate_pair(r, &r1, &r2);
  1809. buffer[n++] = LLVMConstInt(llvm_u16, r1, false);
  1810. buffer[n++] = LLVMConstInt(llvm_u16, r2, false);
  1811. } else {
  1812. buffer[n++] = LLVMConstInt(llvm_u16, 0xfffd, false);
  1813. }
  1814. }
  1815. buffer[n++] = LLVMConstInt(llvm_u16, 0, false);
  1816. LLVMValueRef array = LLVMConstArray(llvm_u16, buffer, cast(unsigned int)n);
  1817. char *name = nullptr;
  1818. {
  1819. isize max_len = 7+8+1;
  1820. name = gb_alloc_array(permanent_allocator(), char, max_len);
  1821. u32 id = m->gen->global_array_index.fetch_add(1);
  1822. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  1823. len -= 1;
  1824. }
  1825. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(array), name);
  1826. LLVMSetInitializer(global_data, array);
  1827. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  1828. LLVMValueRef indices[] = {
  1829. LLVMConstInt(lb_type(m, t_u32), 0, false),
  1830. LLVMConstInt(lb_type(m, t_u32), 0, false),
  1831. };
  1832. lbValue res = {};
  1833. res.type = tv.type;
  1834. res.value = LLVMBuildInBoundsGEP(p->builder, global_data, indices, gb_count_of(indices), "");
  1835. return res;
  1836. }
  1837. case BuiltinProc_wasm_memory_grow:
  1838. {
  1839. char const *name = "llvm.wasm.memory.grow";
  1840. LLVMTypeRef types[1] = {
  1841. lb_type(p->module, t_uintptr),
  1842. };
  1843. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1844. GB_ASSERT_MSG(id != 0, "Unable to find %s", name, LLVMPrintTypeToString(types[0]));
  1845. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1846. LLVMValueRef args[2] = {};
  1847. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  1848. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr).value;
  1849. lbValue res = {};
  1850. res.type = tv.type;
  1851. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1852. return res;
  1853. }
  1854. case BuiltinProc_wasm_memory_size:
  1855. {
  1856. char const *name = "llvm.wasm.memory.size";
  1857. LLVMTypeRef types[1] = {
  1858. lb_type(p->module, t_uintptr),
  1859. };
  1860. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1861. GB_ASSERT_MSG(id != 0, "Unable to find %s", name, LLVMPrintTypeToString(types[0]));
  1862. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1863. LLVMValueRef args[1] = {};
  1864. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  1865. lbValue res = {};
  1866. res.type = tv.type;
  1867. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1868. return res;
  1869. }
  1870. case BuiltinProc_wasm_memory_atomic_wait32:
  1871. {
  1872. char const *name = "llvm.wasm.memory.atomic.wait32";
  1873. LLVMTypeRef types[1] = {
  1874. lb_type(p->module, t_u32),
  1875. };
  1876. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1877. GB_ASSERT_MSG(id != 0, "Unable to find %s", name, LLVMPrintTypeToString(types[0]));
  1878. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1879. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  1880. LLVMValueRef args[3] = {};
  1881. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value;
  1882. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  1883. args[2] = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i64).value;
  1884. lbValue res = {};
  1885. res.type = tv.type;
  1886. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1887. return res;
  1888. }
  1889. case BuiltinProc_wasm_memory_atomic_notify32:
  1890. {
  1891. char const *name = "llvm.wasm.memory.atomic.notify";
  1892. LLVMTypeRef types[1] = {
  1893. lb_type(p->module, t_u32),
  1894. };
  1895. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1896. GB_ASSERT_MSG(id != 0, "Unable to find %s", name, LLVMPrintTypeToString(types[0]));
  1897. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1898. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  1899. LLVMValueRef args[2] = {};
  1900. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value;
  1901. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  1902. lbValue res = {};
  1903. res.type = tv.type;
  1904. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1905. return res;
  1906. }
  1907. }
  1908. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  1909. return {};
  1910. }
  1911. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  1912. switch (param_value.kind) {
  1913. case ParameterValue_Constant:
  1914. if (is_type_constant_type(parameter_type)) {
  1915. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  1916. return res;
  1917. } else {
  1918. ExactValue ev = param_value.value;
  1919. lbValue arg = {};
  1920. Type *type = type_of_expr(param_value.original_ast_expr);
  1921. if (type != nullptr) {
  1922. arg = lb_const_value(p->module, type, ev);
  1923. } else {
  1924. arg = lb_const_value(p->module, parameter_type, param_value.value);
  1925. }
  1926. return lb_emit_conv(p, arg, parameter_type);
  1927. }
  1928. case ParameterValue_Nil:
  1929. return lb_const_nil(p->module, parameter_type);
  1930. case ParameterValue_Location:
  1931. {
  1932. String proc_name = {};
  1933. if (p->entity != nullptr) {
  1934. proc_name = p->entity->token.string;
  1935. }
  1936. return lb_emit_source_code_location(p, proc_name, pos);
  1937. }
  1938. case ParameterValue_Value:
  1939. return lb_build_expr(p, param_value.ast_value);
  1940. }
  1941. return lb_const_nil(p->module, parameter_type);
  1942. }
  1943. lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr);
  1944. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  1945. expr = unparen_expr(expr);
  1946. ast_node(ce, CallExpr, expr);
  1947. if (ce->sce_temp_data) {
  1948. return *(lbValue *)ce->sce_temp_data;
  1949. }
  1950. lbValue res = lb_build_call_expr_internal(p, expr);
  1951. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  1952. GB_ASSERT(is_type_tuple(res.type));
  1953. GB_ASSERT(res.type->Tuple.variables.count == 2);
  1954. return lb_emit_struct_ev(p, res, 0);
  1955. }
  1956. return res;
  1957. }
  1958. lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr) {
  1959. lbModule *m = p->module;
  1960. TypeAndValue tv = type_and_value_of_expr(expr);
  1961. ast_node(ce, CallExpr, expr);
  1962. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  1963. AddressingMode proc_mode = proc_tv.mode;
  1964. if (proc_mode == Addressing_Type) {
  1965. GB_ASSERT(ce->args.count == 1);
  1966. lbValue x = lb_build_expr(p, ce->args[0]);
  1967. lbValue y = lb_emit_conv(p, x, tv.type);
  1968. return y;
  1969. }
  1970. Ast *pexpr = unparen_expr(ce->proc);
  1971. if (proc_mode == Addressing_Builtin) {
  1972. Entity *e = entity_of_node(pexpr);
  1973. BuiltinProcId id = BuiltinProc_Invalid;
  1974. if (e != nullptr) {
  1975. id = cast(BuiltinProcId)e->Builtin.id;
  1976. } else {
  1977. id = BuiltinProc_DIRECTIVE;
  1978. }
  1979. return lb_build_builtin_proc(p, expr, tv, id);
  1980. }
  1981. // NOTE(bill): Regular call
  1982. lbValue value = {};
  1983. Ast *proc_expr = unparen_expr(ce->proc);
  1984. Entity *proc_entity = entity_of_node(proc_expr);
  1985. if (proc_entity != nullptr) {
  1986. if (proc_entity->flags & EntityFlag_Disabled) {
  1987. GB_ASSERT(tv.type == nullptr);
  1988. return {};
  1989. }
  1990. }
  1991. if (proc_expr->tav.mode == Addressing_Constant) {
  1992. ExactValue v = proc_expr->tav.value;
  1993. switch (v.kind) {
  1994. case ExactValue_Integer:
  1995. {
  1996. u64 u = big_int_to_u64(&v.value_integer);
  1997. lbValue x = {};
  1998. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  1999. x.type = t_uintptr;
  2000. x = lb_emit_conv(p, x, t_rawptr);
  2001. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2002. break;
  2003. }
  2004. case ExactValue_Pointer:
  2005. {
  2006. u64 u = cast(u64)v.value_pointer;
  2007. lbValue x = {};
  2008. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  2009. x.type = t_uintptr;
  2010. x = lb_emit_conv(p, x, t_rawptr);
  2011. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2012. break;
  2013. }
  2014. }
  2015. }
  2016. if (value.value == nullptr) {
  2017. value = lb_build_expr(p, proc_expr);
  2018. }
  2019. GB_ASSERT(value.value != nullptr);
  2020. Type *proc_type_ = base_type(value.type);
  2021. GB_ASSERT(proc_type_->kind == Type_Proc);
  2022. TypeProc *pt = &proc_type_->Proc;
  2023. if (is_call_expr_field_value(ce)) {
  2024. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  2025. for_array(arg_index, ce->args) {
  2026. Ast *arg = ce->args[arg_index];
  2027. ast_node(fv, FieldValue, arg);
  2028. GB_ASSERT(fv->field->kind == Ast_Ident);
  2029. String name = fv->field->Ident.token.string;
  2030. isize index = lookup_procedure_parameter(pt, name);
  2031. GB_ASSERT(index >= 0);
  2032. TypeAndValue tav = type_and_value_of_expr(fv->value);
  2033. if (tav.mode == Addressing_Type) {
  2034. args[index] = lb_const_nil(m, tav.type);
  2035. } else {
  2036. args[index] = lb_build_expr(p, fv->value);
  2037. }
  2038. }
  2039. TypeTuple *params = &pt->params->Tuple;
  2040. for (isize i = 0; i < args.count; i++) {
  2041. Entity *e = params->variables[i];
  2042. if (e->kind == Entity_TypeName) {
  2043. args[i] = lb_const_nil(m, e->type);
  2044. } else if (e->kind == Entity_Constant) {
  2045. continue;
  2046. } else {
  2047. GB_ASSERT(e->kind == Entity_Variable);
  2048. if (args[i].value == nullptr) {
  2049. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  2050. } else {
  2051. args[i] = lb_emit_conv(p, args[i], e->type);
  2052. }
  2053. }
  2054. }
  2055. for (isize i = 0; i < args.count; i++) {
  2056. Entity *e = params->variables[i];
  2057. if (args[i].type == nullptr) {
  2058. continue;
  2059. } else if (is_type_untyped_nil(args[i].type)) {
  2060. args[i] = lb_const_nil(m, e->type);
  2061. } else if (is_type_untyped_undef(args[i].type)) {
  2062. args[i] = lb_const_undef(m, e->type);
  2063. }
  2064. }
  2065. return lb_emit_call(p, value, args, ce->inlining, p->copy_elision_hint.ast == expr);
  2066. }
  2067. isize arg_index = 0;
  2068. isize arg_count = 0;
  2069. for_array(i, ce->args) {
  2070. Ast *arg = ce->args[i];
  2071. TypeAndValue tav = type_and_value_of_expr(arg);
  2072. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s %d", expr_to_string(arg), expr_to_string(expr), tav.mode);
  2073. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  2074. Type *at = tav.type;
  2075. if (at->kind == Type_Tuple) {
  2076. arg_count += at->Tuple.variables.count;
  2077. } else {
  2078. arg_count++;
  2079. }
  2080. }
  2081. isize param_count = 0;
  2082. if (pt->params) {
  2083. GB_ASSERT(pt->params->kind == Type_Tuple);
  2084. param_count = pt->params->Tuple.variables.count;
  2085. }
  2086. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  2087. isize variadic_index = pt->variadic_index;
  2088. bool variadic = pt->variadic && variadic_index >= 0;
  2089. bool vari_expand = ce->ellipsis.pos.line != 0;
  2090. bool is_c_vararg = pt->c_vararg;
  2091. String proc_name = {};
  2092. if (p->entity != nullptr) {
  2093. proc_name = p->entity->token.string;
  2094. }
  2095. TokenPos pos = ast_token(ce->proc).pos;
  2096. TypeTuple *param_tuple = nullptr;
  2097. if (pt->params) {
  2098. GB_ASSERT(pt->params->kind == Type_Tuple);
  2099. param_tuple = &pt->params->Tuple;
  2100. }
  2101. for_array(i, ce->args) {
  2102. Ast *arg = ce->args[i];
  2103. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  2104. if (arg_tv.mode == Addressing_Type) {
  2105. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  2106. } else {
  2107. lbValue a = lb_build_expr(p, arg);
  2108. Type *at = a.type;
  2109. if (at->kind == Type_Tuple) {
  2110. for_array(i, at->Tuple.variables) {
  2111. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  2112. args[arg_index++] = v;
  2113. }
  2114. } else {
  2115. args[arg_index++] = a;
  2116. }
  2117. }
  2118. }
  2119. if (param_count > 0) {
  2120. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  2121. GB_ASSERT(param_count < 1000000);
  2122. if (arg_count < param_count) {
  2123. isize end = cast(isize)param_count;
  2124. if (variadic) {
  2125. end = variadic_index;
  2126. }
  2127. while (arg_index < end) {
  2128. Entity *e = param_tuple->variables[arg_index];
  2129. GB_ASSERT(e->kind == Entity_Variable);
  2130. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  2131. }
  2132. }
  2133. if (is_c_vararg) {
  2134. GB_ASSERT(variadic);
  2135. GB_ASSERT(!vari_expand);
  2136. isize i = 0;
  2137. for (; i < variadic_index; i++) {
  2138. Entity *e = param_tuple->variables[i];
  2139. if (e->kind == Entity_Variable) {
  2140. args[i] = lb_emit_conv(p, args[i], e->type);
  2141. }
  2142. }
  2143. Type *variadic_type = param_tuple->variables[i]->type;
  2144. GB_ASSERT(is_type_slice(variadic_type));
  2145. variadic_type = base_type(variadic_type)->Slice.elem;
  2146. if (!is_type_any(variadic_type)) {
  2147. for (; i < arg_count; i++) {
  2148. args[i] = lb_emit_conv(p, args[i], variadic_type);
  2149. }
  2150. } else {
  2151. for (; i < arg_count; i++) {
  2152. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  2153. }
  2154. }
  2155. } else if (variadic) {
  2156. isize i = 0;
  2157. for (; i < variadic_index; i++) {
  2158. Entity *e = param_tuple->variables[i];
  2159. if (e->kind == Entity_Variable) {
  2160. args[i] = lb_emit_conv(p, args[i], e->type);
  2161. }
  2162. }
  2163. if (!vari_expand) {
  2164. Type *variadic_type = param_tuple->variables[i]->type;
  2165. GB_ASSERT(is_type_slice(variadic_type));
  2166. variadic_type = base_type(variadic_type)->Slice.elem;
  2167. for (; i < arg_count; i++) {
  2168. args[i] = lb_emit_conv(p, args[i], variadic_type);
  2169. }
  2170. }
  2171. } else {
  2172. for (isize i = 0; i < param_count; i++) {
  2173. Entity *e = param_tuple->variables[i];
  2174. if (e->kind == Entity_Variable) {
  2175. if (args[i].value == nullptr) {
  2176. continue;
  2177. }
  2178. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  2179. args[i] = lb_emit_conv(p, args[i], e->type);
  2180. }
  2181. }
  2182. }
  2183. if (variadic && !vari_expand && !is_c_vararg) {
  2184. // variadic call argument generation
  2185. Type *slice_type = param_tuple->variables[variadic_index]->type;
  2186. Type *elem_type = base_type(slice_type)->Slice.elem;
  2187. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  2188. isize slice_len = arg_count+1 - (variadic_index+1);
  2189. if (slice_len > 0) {
  2190. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  2191. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  2192. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  2193. lb_emit_store(p, addr, args[i]);
  2194. }
  2195. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  2196. lbValue len = lb_const_int(m, t_int, slice_len);
  2197. lb_fill_slice(p, slice, base_elem, len);
  2198. }
  2199. arg_count = param_count;
  2200. args[variadic_index] = lb_addr_load(p, slice);
  2201. }
  2202. }
  2203. if (variadic && variadic_index+1 < param_count) {
  2204. for (isize i = variadic_index+1; i < param_count; i++) {
  2205. Entity *e = param_tuple->variables[i];
  2206. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  2207. }
  2208. }
  2209. isize final_count = param_count;
  2210. if (is_c_vararg) {
  2211. final_count = arg_count;
  2212. }
  2213. if (param_tuple != nullptr) {
  2214. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  2215. Entity *e = param_tuple->variables[i];
  2216. if (args[i].type == nullptr) {
  2217. continue;
  2218. } else if (is_type_untyped_nil(args[i].type)) {
  2219. args[i] = lb_const_nil(m, e->type);
  2220. } else if (is_type_untyped_undef(args[i].type)) {
  2221. args[i] = lb_const_undef(m, e->type);
  2222. }
  2223. }
  2224. }
  2225. auto call_args = array_slice(args, 0, final_count);
  2226. return lb_emit_call(p, value, call_args, ce->inlining, p->copy_elision_hint.ast == expr);
  2227. }