llvm_backend.cpp 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518
  1. #define MULTITHREAD_OBJECT_GENERATION 1
  2. #ifndef USE_SEPARATE_MODULES
  3. #define USE_SEPARATE_MODULES build_context.use_separate_modules
  4. #endif
  5. #ifndef MULTITHREAD_OBJECT_GENERATION
  6. #define MULTITHREAD_OBJECT_GENERATION 0
  7. #endif
  8. #include "llvm_backend.hpp"
  9. #include "llvm_abi.cpp"
  10. #include "llvm_backend_opt.cpp"
  11. #include "llvm_backend_general.cpp"
  12. #include "llvm_backend_debug.cpp"
  13. #include "llvm_backend_const.cpp"
  14. #include "llvm_backend_type.cpp"
  15. #include "llvm_backend_utility.cpp"
  16. #include "llvm_backend_expr.cpp"
  17. #include "llvm_backend_stmt.cpp"
  18. #include "llvm_backend_proc.cpp"
  19. gb_internal void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  20. if (e == nullptr) {
  21. return;
  22. }
  23. GB_ASSERT(e->kind == Entity_LibraryName);
  24. GB_ASSERT(e->flags & EntityFlag_Used);
  25. mutex_lock(&m->gen->foreign_mutex);
  26. if (!ptr_set_update(&m->gen->foreign_libraries_set, e)) {
  27. array_add(&m->gen->foreign_libraries, e);
  28. }
  29. mutex_unlock(&m->gen->foreign_mutex);
  30. }
  31. gb_internal GB_COMPARE_PROC(foreign_library_cmp) {
  32. int cmp = 0;
  33. Entity *x = *(Entity **)a;
  34. Entity *y = *(Entity **)b;
  35. if (x == y) {
  36. return 0;
  37. }
  38. GB_ASSERT(x->kind == Entity_LibraryName);
  39. GB_ASSERT(y->kind == Entity_LibraryName);
  40. cmp = i64_cmp(x->LibraryName.priority_index, y->LibraryName.priority_index);
  41. if (cmp) {
  42. return cmp;
  43. }
  44. if (x->pkg != y->pkg) {
  45. isize order_x = x->pkg ? x->pkg->order : 0;
  46. isize order_y = y->pkg ? y->pkg->order : 0;
  47. cmp = isize_cmp(order_x, order_y);
  48. if (cmp) {
  49. return cmp;
  50. }
  51. }
  52. if (x->file != y->file) {
  53. String fullpath_x = x->file ? x->file->fullpath : (String{});
  54. String fullpath_y = y->file ? y->file->fullpath : (String{});
  55. String file_x = filename_from_path(fullpath_x);
  56. String file_y = filename_from_path(fullpath_y);
  57. cmp = string_compare(file_x, file_y);
  58. if (cmp) {
  59. return cmp;
  60. }
  61. }
  62. cmp = u64_cmp(x->order_in_src, y->order_in_src);
  63. if (cmp) {
  64. return cmp;
  65. }
  66. return i32_cmp(x->token.pos.offset, y->token.pos.offset);
  67. }
  68. gb_internal void lb_set_entity_from_other_modules_linkage_correctly(lbModule *other_module, Entity *e, String const &name) {
  69. if (other_module == nullptr) {
  70. return;
  71. }
  72. char const *cname = alloc_cstring(temporary_allocator(), name);
  73. LLVMValueRef other_global = nullptr;
  74. if (e->kind == Entity_Variable) {
  75. other_global = LLVMGetNamedGlobal(other_module->mod, cname);
  76. } else if (e->kind == Entity_Procedure) {
  77. other_global = LLVMGetNamedFunction(other_module->mod, cname);
  78. }
  79. if (other_global) {
  80. LLVMSetLinkage(other_global, LLVMExternalLinkage);
  81. }
  82. }
  83. gb_internal void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  84. TEMPORARY_ALLOCATOR_GUARD();
  85. GB_ASSERT(addr.kind == lbAddr_Context);
  86. GB_ASSERT(addr.ctx.sel.index.count == 0);
  87. auto args = array_make<lbValue>(temporary_allocator(), 1);
  88. args[0] = addr.addr;
  89. lb_emit_runtime_call(p, "__init_context", args);
  90. }
  91. gb_internal lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  92. Type *pt = base_type(p->type);
  93. GB_ASSERT(pt->kind == Type_Proc);
  94. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  95. String name = str_lit("__.context_ptr");
  96. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  97. e->flags |= EntityFlag_NoAlias;
  98. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  99. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  100. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  101. lbValue param = {context_ptr, e->type};
  102. lb_add_entity(p->module, e, param);
  103. lbAddr ctx_addr = {};
  104. ctx_addr.kind = lbAddr_Context;
  105. ctx_addr.addr = param;
  106. lbContextData *cd = array_add_and_get(&p->context_stack);
  107. cd->ctx = ctx_addr;
  108. cd->scope_index = -1;
  109. cd->uses = +1; // make sure it has been used already
  110. return cd;
  111. }
  112. gb_internal lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  113. ctx.kind = lbAddr_Context;
  114. lbContextData *cd = array_add_and_get(&p->context_stack);
  115. cd->ctx = ctx;
  116. cd->scope_index = p->scope_index;
  117. return cd;
  118. }
  119. gb_internal lbValue lb_equal_proc_for_type(lbModule *m, Type *type) {
  120. type = base_type(type);
  121. GB_ASSERT(is_type_comparable(type));
  122. Type *pt = alloc_type_pointer(type);
  123. LLVMTypeRef ptr_type = lb_type(m, pt);
  124. lbProcedure **found = map_get(&m->equal_procs, type);
  125. lbProcedure *compare_proc = nullptr;
  126. if (found) {
  127. compare_proc = *found;
  128. GB_ASSERT(compare_proc != nullptr);
  129. return {compare_proc->value, compare_proc->type};
  130. }
  131. static u32 proc_index = 0;
  132. char buf[32] = {};
  133. isize n = gb_snprintf(buf, 32, "__$equal%u", ++proc_index);
  134. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  135. String proc_name = make_string_c(str);
  136. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  137. map_set(&m->equal_procs, type, p);
  138. lb_begin_procedure_body(p);
  139. lb_add_attribute_to_proc(m, p->value, "readonly");
  140. lb_add_attribute_to_proc(m, p->value, "nounwind");
  141. LLVMValueRef x = LLVMGetParam(p->value, 0);
  142. LLVMValueRef y = LLVMGetParam(p->value, 1);
  143. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  144. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  145. lbValue lhs = {x, pt};
  146. lbValue rhs = {y, pt};
  147. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  148. lb_add_proc_attribute_at_index(p, 1+1, "nonnull");
  149. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  150. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  151. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  152. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  153. lb_start_block(p, block_same_ptr);
  154. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  155. lb_start_block(p, block_diff_ptr);
  156. if (type->kind == Type_Struct) {
  157. type_set_offsets(type);
  158. lbBlock *block_false = lb_create_block(p, "bfalse");
  159. lbValue res = lb_const_bool(m, t_bool, true);
  160. for_array(i, type->Struct.fields) {
  161. lbBlock *next_block = lb_create_block(p, "btrue");
  162. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  163. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  164. lbValue left = lb_emit_load(p, pleft);
  165. lbValue right = lb_emit_load(p, pright);
  166. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  167. lb_emit_if(p, ok, next_block, block_false);
  168. lb_emit_jump(p, next_block);
  169. lb_start_block(p, next_block);
  170. }
  171. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  172. lb_start_block(p, block_false);
  173. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  174. } else if (type->kind == Type_Union) {
  175. if (is_type_union_maybe_pointer(type)) {
  176. Type *v = type->Union.variants[0];
  177. Type *pv = alloc_type_pointer(v);
  178. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  179. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  180. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  181. ok = lb_emit_conv(p, ok, t_bool);
  182. LLVMBuildRet(p->builder, ok.value);
  183. } else {
  184. lbBlock *block_false = lb_create_block(p, "bfalse");
  185. lbBlock *block_switch = lb_create_block(p, "bswitch");
  186. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  187. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  188. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  189. lb_emit_if(p, tag_eq, block_switch, block_false);
  190. lb_start_block(p, block_switch);
  191. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, cast(unsigned)type->Union.variants.count);
  192. for (Type *v : type->Union.variants) {
  193. lbBlock *case_block = lb_create_block(p, "bcase");
  194. lb_start_block(p, case_block);
  195. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  196. Type *vp = alloc_type_pointer(v);
  197. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  198. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  199. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  200. ok = lb_emit_conv(p, ok, t_bool);
  201. LLVMBuildRet(p->builder, ok.value);
  202. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  203. }
  204. lb_start_block(p, block_false);
  205. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  206. }
  207. } else {
  208. lbValue left = lb_emit_load(p, lhs);
  209. lbValue right = lb_emit_load(p, rhs);
  210. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  211. ok = lb_emit_conv(p, ok, t_bool);
  212. LLVMBuildRet(p->builder, ok.value);
  213. }
  214. lb_end_procedure_body(p);
  215. compare_proc = p;
  216. return {compare_proc->value, compare_proc->type};
  217. }
  218. gb_internal lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  219. TEMPORARY_ALLOCATOR_GUARD();
  220. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  221. auto args = array_make<lbValue>(temporary_allocator(), 3);
  222. args[0] = data;
  223. args[1] = seed;
  224. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  225. return lb_emit_runtime_call(p, "default_hasher", args);
  226. }
  227. gb_internal void lb_add_callsite_force_inline(lbProcedure *p, lbValue ret_value) {
  228. LLVMAddCallSiteAttribute(ret_value.value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  229. }
  230. gb_internal lbValue lb_hasher_proc_for_type(lbModule *m, Type *type) {
  231. type = core_type(type);
  232. GB_ASSERT_MSG(is_type_valid_for_keys(type), "%s", type_to_string(type));
  233. Type *pt = alloc_type_pointer(type);
  234. lbProcedure **found = map_get(&m->hasher_procs, type);
  235. if (found) {
  236. GB_ASSERT(*found != nullptr);
  237. return {(*found)->value, (*found)->type};
  238. }
  239. static std::atomic<u32> proc_index;
  240. char buf[32] = {};
  241. isize n = gb_snprintf(buf, 32, "__$hasher%u", 1+proc_index.fetch_add(1));
  242. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  243. String proc_name = make_string_c(str);
  244. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  245. map_set(&m->hasher_procs, type, p);
  246. lb_begin_procedure_body(p);
  247. defer (lb_end_procedure_body(p));
  248. lb_add_attribute_to_proc(m, p->value, "readonly");
  249. lb_add_attribute_to_proc(m, p->value, "nounwind");
  250. LLVMValueRef x = LLVMGetParam(p->value, 0);
  251. LLVMValueRef y = LLVMGetParam(p->value, 1);
  252. lbValue data = {x, t_rawptr};
  253. lbValue seed = {y, t_uintptr};
  254. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  255. lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  256. if (is_type_simple_compare(type)) {
  257. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  258. lb_add_callsite_force_inline(p, res);
  259. LLVMBuildRet(p->builder, res.value);
  260. return {p->value, p->type};
  261. }
  262. TEMPORARY_ALLOCATOR_GUARD();
  263. if (type->kind == Type_Struct) {
  264. type_set_offsets(type);
  265. data = lb_emit_conv(p, data, t_u8_ptr);
  266. auto args = array_make<lbValue>(temporary_allocator(), 2);
  267. for_array(i, type->Struct.fields) {
  268. GB_ASSERT(type->Struct.offsets != nullptr);
  269. i64 offset = type->Struct.offsets[i];
  270. Entity *field = type->Struct.fields[i];
  271. lbValue field_hasher = lb_hasher_proc_for_type(m, field->type);
  272. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  273. args[0] = ptr;
  274. args[1] = seed;
  275. seed = lb_emit_call(p, field_hasher, args);
  276. }
  277. LLVMBuildRet(p->builder, seed.value);
  278. } else if (type->kind == Type_Union) {
  279. auto args = array_make<lbValue>(temporary_allocator(), 2);
  280. if (is_type_union_maybe_pointer(type)) {
  281. Type *v = type->Union.variants[0];
  282. lbValue variant_hasher = lb_hasher_proc_for_type(m, v);
  283. args[0] = data;
  284. args[1] = seed;
  285. lbValue res = lb_emit_call(p, variant_hasher, args);
  286. lb_add_callsite_force_inline(p, res);
  287. LLVMBuildRet(p->builder, res.value);
  288. }
  289. lbBlock *end_block = lb_create_block(p, "bend");
  290. data = lb_emit_conv(p, data, pt);
  291. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  292. lbValue tag = lb_emit_load(p, tag_ptr);
  293. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  294. for (Type *v : type->Union.variants) {
  295. lbBlock *case_block = lb_create_block(p, "bcase");
  296. lb_start_block(p, case_block);
  297. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  298. lbValue variant_hasher = lb_hasher_proc_for_type(m, v);
  299. args[0] = data;
  300. args[1] = seed;
  301. lbValue res = lb_emit_call(p, variant_hasher, args);
  302. LLVMBuildRet(p->builder, res.value);
  303. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  304. }
  305. lb_start_block(p, end_block);
  306. LLVMBuildRet(p->builder, seed.value);
  307. } else if (type->kind == Type_Array) {
  308. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  309. lb_addr_store(p, pres, seed);
  310. auto args = array_make<lbValue>(temporary_allocator(), 2);
  311. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->Array.elem);
  312. auto loop_data = lb_loop_start(p, cast(isize)type->Array.count, t_i32);
  313. data = lb_emit_conv(p, data, pt);
  314. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  315. args[0] = ptr;
  316. args[1] = lb_addr_load(p, pres);
  317. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  318. lb_addr_store(p, pres, new_seed);
  319. lb_loop_end(p, loop_data);
  320. lbValue res = lb_addr_load(p, pres);
  321. LLVMBuildRet(p->builder, res.value);
  322. } else if (type->kind == Type_EnumeratedArray) {
  323. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  324. lb_addr_store(p, res, seed);
  325. auto args = array_make<lbValue>(temporary_allocator(), 2);
  326. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  327. auto loop_data = lb_loop_start(p, cast(isize)type->EnumeratedArray.count, t_i32);
  328. data = lb_emit_conv(p, data, pt);
  329. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  330. args[0] = ptr;
  331. args[1] = lb_addr_load(p, res);
  332. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  333. lb_addr_store(p, res, new_seed);
  334. lb_loop_end(p, loop_data);
  335. lbValue vres = lb_addr_load(p, res);
  336. LLVMBuildRet(p->builder, vres.value);
  337. } else if (is_type_cstring(type)) {
  338. auto args = array_make<lbValue>(temporary_allocator(), 2);
  339. args[0] = data;
  340. args[1] = seed;
  341. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  342. lb_add_callsite_force_inline(p, res);
  343. LLVMBuildRet(p->builder, res.value);
  344. } else if (is_type_string(type)) {
  345. auto args = array_make<lbValue>(temporary_allocator(), 2);
  346. args[0] = data;
  347. args[1] = seed;
  348. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  349. lb_add_callsite_force_inline(p, res);
  350. LLVMBuildRet(p->builder, res.value);
  351. } else {
  352. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  353. }
  354. return {p->value, p->type};
  355. }
  356. #define LLVM_SET_VALUE_NAME(value, name) LLVMSetValueName2((value), (name), gb_count_of((name))-1);
  357. gb_internal lbValue lb_map_get_proc_for_type(lbModule *m, Type *type) {
  358. GB_ASSERT(!build_context.dynamic_map_calls);
  359. type = base_type(type);
  360. GB_ASSERT(type->kind == Type_Map);
  361. lbProcedure **found = map_get(&m->map_get_procs, type);
  362. if (found) {
  363. GB_ASSERT(*found != nullptr);
  364. return {(*found)->value, (*found)->type};
  365. }
  366. static std::atomic<u32> proc_index;
  367. char buf[32] = {};
  368. isize n = gb_snprintf(buf, 32, "__$map_get-%u", 1+proc_index.fetch_add(1));
  369. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  370. String proc_name = make_string_c(str);
  371. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_get_proc);
  372. map_set(&m->map_get_procs, type, p);
  373. lb_begin_procedure_body(p);
  374. defer (lb_end_procedure_body(p));
  375. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  376. lb_add_attribute_to_proc(m, p->value, "nounwind");
  377. // if (build_context.ODIN_DEBUG) {
  378. lb_add_attribute_to_proc(m, p->value, "noinline");
  379. // }
  380. LLVMValueRef x = LLVMGetParam(p->value, 0);
  381. LLVMValueRef y = LLVMGetParam(p->value, 1);
  382. LLVMValueRef z = LLVMGetParam(p->value, 2);
  383. lbValue map_ptr = {x, t_rawptr};
  384. lbValue h = {y, t_uintptr};
  385. lbValue key_ptr = {z, t_rawptr};
  386. LLVM_SET_VALUE_NAME(h.value, "hash");
  387. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  388. lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  389. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  390. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  391. lbBlock *loop_block = lb_create_block(p, "loop");
  392. lbBlock *hash_block = lb_create_block(p, "hash");
  393. lbBlock *probe_block = lb_create_block(p, "probe");
  394. lbBlock *increment_block = lb_create_block(p, "increment");
  395. lbBlock *hash_compare_block = lb_create_block(p, "hash_compare");
  396. lbBlock *key_compare_block = lb_create_block(p, "key_compare");
  397. lbBlock *value_block = lb_create_block(p, "value");
  398. lbBlock *nil_block = lb_create_block(p, "nil");
  399. map_ptr = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  400. LLVM_SET_VALUE_NAME(map_ptr.value, "map_ptr");
  401. lbValue map = lb_emit_load(p, map_ptr);
  402. LLVM_SET_VALUE_NAME(map.value, "map");
  403. lbValue length = lb_map_len(p, map);
  404. LLVM_SET_VALUE_NAME(length.value, "length");
  405. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, length, lb_const_nil(m, t_int)), nil_block, hash_block);
  406. lb_start_block(p, hash_block);
  407. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  408. LLVM_SET_VALUE_NAME(key_ptr.value, "key_ptr");
  409. lbValue key = lb_emit_load(p, key_ptr);
  410. LLVM_SET_VALUE_NAME(key.value, "key");
  411. lbAddr pos = lb_add_local_generated(p, t_uintptr, false);
  412. lbAddr distance = lb_add_local_generated(p, t_uintptr, true);
  413. LLVM_SET_VALUE_NAME(pos.addr.value, "pos");
  414. LLVM_SET_VALUE_NAME(distance.addr.value, "distance");
  415. lbValue capacity = lb_map_cap(p, map);
  416. LLVM_SET_VALUE_NAME(capacity.value, "capacity");
  417. lbValue cap_minus_1 = lb_emit_arith(p, Token_Sub, capacity, lb_const_int(m, t_int, 1), t_int);
  418. lbValue mask = lb_emit_conv(p, cap_minus_1, t_uintptr);
  419. LLVM_SET_VALUE_NAME(mask.value, "mask");
  420. {
  421. // map_desired_position inlined
  422. lbValue the_pos = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  423. the_pos = lb_emit_conv(p, the_pos, t_uintptr);
  424. lb_addr_store(p, pos, the_pos);
  425. }
  426. lbValue zero_uintptr = lb_const_int(m, t_uintptr, 0);
  427. lbValue one_uintptr = lb_const_int(m, t_uintptr, 1);
  428. lbValue ks = lb_map_data_uintptr(p, map);
  429. lbValue vs = lb_map_cell_index_static(p, type->Map.key, ks, capacity);
  430. lbValue hs = lb_map_cell_index_static(p, type->Map.value, vs, capacity);
  431. ks = lb_emit_conv(p, ks, alloc_type_pointer(type->Map.key));
  432. vs = lb_emit_conv(p, vs, alloc_type_pointer(type->Map.value));
  433. hs = lb_emit_conv(p, hs, alloc_type_pointer(t_uintptr));
  434. LLVM_SET_VALUE_NAME(ks.value, "ks");
  435. LLVM_SET_VALUE_NAME(vs.value, "vs");
  436. LLVM_SET_VALUE_NAME(hs.value, "hs");
  437. lb_emit_jump(p, loop_block);
  438. lb_start_block(p, loop_block);
  439. lbValue element_hash = lb_emit_load(p, lb_emit_ptr_offset(p, hs, lb_addr_load(p, pos)));
  440. LLVM_SET_VALUE_NAME(element_hash.value, "element_hash");
  441. {
  442. // if element_hash == 0 { return nil }
  443. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, zero_uintptr), nil_block, probe_block);
  444. }
  445. lb_start_block(p, probe_block);
  446. {
  447. // map_probe_distance inlined
  448. lbValue probe_distance = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  449. probe_distance = lb_emit_conv(p, probe_distance, t_uintptr);
  450. lbValue cap = lb_emit_conv(p, capacity, t_uintptr);
  451. lbValue base = lb_emit_arith(p, Token_Add, lb_addr_load(p, pos), cap, t_uintptr);
  452. probe_distance = lb_emit_arith(p, Token_Sub, base, probe_distance, t_uintptr);
  453. probe_distance = lb_emit_arith(p, Token_And, probe_distance, mask, t_uintptr);
  454. LLVM_SET_VALUE_NAME(probe_distance.value, "probe_distance");
  455. lbValue cond = lb_emit_comp(p, Token_Gt, lb_addr_load(p, distance), probe_distance);
  456. lb_emit_if(p, cond, nil_block, hash_compare_block);
  457. }
  458. lb_start_block(p, hash_compare_block);
  459. {
  460. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, h), key_compare_block, increment_block);
  461. }
  462. lb_start_block(p, key_compare_block);
  463. {
  464. lbValue element_key = lb_map_cell_index_static(p, type->Map.key, ks, lb_addr_load(p, pos));
  465. element_key = lb_emit_conv(p, element_key, ks.type);
  466. LLVM_SET_VALUE_NAME(element_key.value, "element_key_ptr");
  467. lbValue cond = lb_emit_comp(p, Token_CmpEq, lb_emit_load(p, element_key), key);
  468. lb_emit_if(p, cond, value_block, increment_block);
  469. }
  470. lb_start_block(p, value_block);
  471. {
  472. lbValue element_value = lb_map_cell_index_static(p, type->Map.value, vs, lb_addr_load(p, pos));
  473. LLVM_SET_VALUE_NAME(element_value.value, "element_value_ptr");
  474. element_value = lb_emit_conv(p, element_value, t_rawptr);
  475. LLVMBuildRet(p->builder, element_value.value);
  476. }
  477. lb_start_block(p, increment_block);
  478. {
  479. lbValue pp = lb_addr_load(p, pos);
  480. pp = lb_emit_arith(p, Token_Add, pp, one_uintptr, t_uintptr);
  481. pp = lb_emit_arith(p, Token_And, pp, mask, t_uintptr);
  482. lb_addr_store(p, pos, pp);
  483. lb_emit_increment(p, distance.addr);
  484. }
  485. lb_emit_jump(p, loop_block);
  486. lb_start_block(p, nil_block);
  487. {
  488. lbValue res = lb_const_nil(m, t_rawptr);
  489. LLVMBuildRet(p->builder, res.value);
  490. }
  491. // gb_printf_err("%s\n", LLVMPrintValueToString(p->value));
  492. return {p->value, p->type};
  493. }
  494. // gb_internal void lb_debug_print(lbProcedure *p, String const &str) {
  495. // auto args = array_make<lbValue>(heap_allocator(), 1);
  496. // args[0] = lb_const_string(p->module, str);
  497. // lb_emit_runtime_call(p, "print_string", args);
  498. // }
  499. gb_internal lbValue lb_map_set_proc_for_type(lbModule *m, Type *type) {
  500. TEMPORARY_ALLOCATOR_GUARD();
  501. GB_ASSERT(!build_context.dynamic_map_calls);
  502. type = base_type(type);
  503. GB_ASSERT(type->kind == Type_Map);
  504. lbProcedure **found = map_get(&m->map_set_procs, type);
  505. if (found) {
  506. GB_ASSERT(*found != nullptr);
  507. return {(*found)->value, (*found)->type};
  508. }
  509. static u32 proc_index = 0;
  510. char buf[32] = {};
  511. isize n = gb_snprintf(buf, 32, "__$map_set-%u", ++proc_index);
  512. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  513. String proc_name = make_string_c(str);
  514. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_set_proc);
  515. map_set(&m->map_set_procs, type, p);
  516. lb_begin_procedure_body(p);
  517. defer (lb_end_procedure_body(p));
  518. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  519. lb_add_attribute_to_proc(m, p->value, "nounwind");
  520. if (build_context.ODIN_DEBUG) {
  521. lb_add_attribute_to_proc(m, p->value, "noinline");
  522. }
  523. lbValue map_ptr = {LLVMGetParam(p->value, 0), t_rawptr};
  524. lbValue hash = {LLVMGetParam(p->value, 1), t_uintptr};
  525. lbValue key_ptr = {LLVMGetParam(p->value, 2), t_rawptr};
  526. lbValue value_ptr = {LLVMGetParam(p->value, 3), t_rawptr};
  527. lbValue location_ptr = {LLVMGetParam(p->value, 4), t_source_code_location_ptr};
  528. map_ptr = lb_emit_conv(p, map_ptr, alloc_type_pointer(type));
  529. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  530. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  531. lb_add_proc_attribute_at_index(p, 1+0, "noalias");
  532. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  533. if (!are_types_identical(type->Map.key, type->Map.value)) {
  534. lb_add_proc_attribute_at_index(p, 1+2, "noalias");
  535. }
  536. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  537. lb_add_proc_attribute_at_index(p, 1+3, "nonnull");
  538. if (!are_types_identical(type->Map.key, type->Map.value)) {
  539. lb_add_proc_attribute_at_index(p, 1+3, "noalias");
  540. }
  541. lb_add_proc_attribute_at_index(p, 1+3, "readonly");
  542. lb_add_proc_attribute_at_index(p, 1+4, "nonnull");
  543. lb_add_proc_attribute_at_index(p, 1+4, "noalias");
  544. lb_add_proc_attribute_at_index(p, 1+4, "readonly");
  545. ////
  546. lbValue found_ptr = {};
  547. {
  548. lbValue map_get_proc = lb_map_get_proc_for_type(m, type);
  549. auto args = array_make<lbValue>(temporary_allocator(), 3);
  550. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  551. args[1] = hash;
  552. args[2] = key_ptr;
  553. found_ptr = lb_emit_call(p, map_get_proc, args);
  554. }
  555. lbBlock *found_block = lb_create_block(p, "found");
  556. lbBlock *check_grow_block = lb_create_block(p, "check-grow");
  557. lbBlock *grow_fail_block = lb_create_block(p, "grow-fail");
  558. lbBlock *insert_block = lb_create_block(p, "insert");
  559. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, found_ptr), found_block, check_grow_block);
  560. lb_start_block(p, found_block);
  561. {
  562. lb_mem_copy_non_overlapping(p, found_ptr, value_ptr, lb_const_int(m, t_int, type_size_of(type->Map.value)));
  563. LLVMBuildRet(p->builder, lb_emit_conv(p, found_ptr, t_rawptr).value);
  564. }
  565. lb_start_block(p, check_grow_block);
  566. lbValue map_info = lb_gen_map_info_ptr(p->module, type);
  567. {
  568. auto args = array_make<lbValue>(temporary_allocator(), 3);
  569. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  570. args[1] = map_info;
  571. args[2] = lb_emit_load(p, location_ptr);
  572. lbValue grow_err = lb_emit_runtime_call(p, "__dynamic_map_check_grow", args);
  573. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, grow_err), grow_fail_block, insert_block);
  574. lb_start_block(p, grow_fail_block);
  575. LLVMBuildRet(p->builder, LLVMConstNull(lb_type(m, t_rawptr)));
  576. }
  577. lb_start_block(p, insert_block);
  578. {
  579. auto args = array_make<lbValue>(temporary_allocator(), 5);
  580. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  581. args[1] = map_info;
  582. args[2] = hash;
  583. args[3] = lb_emit_conv(p, key_ptr, t_uintptr);
  584. args[4] = lb_emit_conv(p, value_ptr, t_uintptr);
  585. lbValue result = lb_emit_runtime_call(p, "map_insert_hash_dynamic", args);
  586. lb_emit_increment(p, lb_map_len_ptr(p, map_ptr));
  587. LLVMBuildRet(p->builder, lb_emit_conv(p, result, t_rawptr).value);
  588. }
  589. return {p->value, p->type};
  590. }
  591. gb_internal lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  592. MUTEX_GUARD(&m->gen->anonymous_proc_lits_mutex);
  593. lbProcedure **found = map_get(&m->gen->anonymous_proc_lits, expr);
  594. if (found) {
  595. return lb_find_procedure_value_from_entity(m, (*found)->entity);
  596. }
  597. ast_node(pl, ProcLit, expr);
  598. // NOTE(bill): Generate a new name
  599. // parent$count
  600. isize name_len = prefix_name.len + 1 + 8 + 1;
  601. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  602. i32 name_id = cast(i32)m->gen->anonymous_proc_lits.count;
  603. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  604. String name = make_string((u8 *)name_text, name_len-1);
  605. Type *type = type_of_expr(expr);
  606. Token token = {};
  607. token.pos = ast_token(expr).pos;
  608. token.kind = Token_Ident;
  609. token.string = name;
  610. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  611. e->file = expr->file();
  612. e->decl_info = pl->decl;
  613. e->code_gen_module = m;
  614. e->flags |= EntityFlag_ProcBodyChecked;
  615. lbProcedure *p = lb_create_procedure(m, e);
  616. lbValue value = {};
  617. value.value = p->value;
  618. value.type = p->type;
  619. array_add(&m->procedures_to_generate, p);
  620. if (parent != nullptr) {
  621. array_add(&parent->children, p);
  622. } else {
  623. string_map_set(&m->members, name, value);
  624. }
  625. map_set(&m->gen->anonymous_proc_lits, expr, p);
  626. return value;
  627. }
  628. gb_internal lbValue lb_gen_map_cell_info_ptr(lbModule *m, Type *type) {
  629. lbAddr *found = map_get(&m->map_cell_info_map, type);
  630. if (found) {
  631. return found->addr;
  632. }
  633. i64 size = 0, len = 0;
  634. map_cell_size_and_len(type, &size, &len);
  635. LLVMValueRef const_values[4] = {};
  636. const_values[0] = lb_const_int(m, t_uintptr, type_size_of(type)).value;
  637. const_values[1] = lb_const_int(m, t_uintptr, type_align_of(type)).value;
  638. const_values[2] = lb_const_int(m, t_uintptr, size).value;
  639. const_values[3] = lb_const_int(m, t_uintptr, len).value;
  640. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_cell_info, const_values, gb_count_of(const_values));
  641. lbValue res = {llvm_res, t_map_cell_info};
  642. lbAddr addr = lb_add_global_generated(m, t_map_cell_info, res, nullptr);
  643. lb_make_global_private_const(addr);
  644. map_set(&m->map_cell_info_map, type, addr);
  645. return addr.addr;
  646. }
  647. gb_internal lbValue lb_gen_map_info_ptr(lbModule *m, Type *map_type) {
  648. map_type = base_type(map_type);
  649. GB_ASSERT(map_type->kind == Type_Map);
  650. lbAddr *found = map_get(&m->map_info_map, map_type);
  651. if (found) {
  652. return found->addr;
  653. }
  654. GB_ASSERT(t_map_info != nullptr);
  655. GB_ASSERT(t_map_cell_info != nullptr);
  656. LLVMValueRef key_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.key).value;
  657. LLVMValueRef value_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.value).value;
  658. LLVMValueRef const_values[4] = {};
  659. const_values[0] = key_cell_info;
  660. const_values[1] = value_cell_info;
  661. const_values[2] = lb_hasher_proc_for_type(m, map_type->Map.key).value;
  662. const_values[3] = lb_equal_proc_for_type(m, map_type->Map.key).value;
  663. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_info, const_values, gb_count_of(const_values));
  664. lbValue res = {llvm_res, t_map_info};
  665. lbAddr addr = lb_add_global_generated(m, t_map_info, res, nullptr);
  666. lb_make_global_private_const(addr);
  667. map_set(&m->map_info_map, map_type, addr);
  668. return addr.addr;
  669. }
  670. gb_internal lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  671. if (true) {
  672. return {};
  673. }
  674. lbValue hashed_key = {};
  675. #if 0
  676. if (lb_is_const(key)) {
  677. u64 hash = 0xcbf29ce484222325;
  678. if (is_type_cstring(key_type)) {
  679. size_t length = 0;
  680. char const *text = LLVMGetAsString(key.value, &length);
  681. hash = fnv64a(text, cast(isize)length);
  682. } else if (is_type_string(key_type)) {
  683. unsigned data_indices[] = {0};
  684. unsigned len_indices[] = {1};
  685. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  686. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  687. i64 length = LLVMConstIntGetSExtValue(len);
  688. char const *text = nullptr;
  689. if (false && length != 0) {
  690. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  691. return {};
  692. }
  693. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  694. size_t ulength = 0;
  695. text = LLVMGetAsString(data, &ulength);
  696. gb_printf_err("%lld %llu %s\n", length, ulength, text);
  697. length = gb_min(length, cast(i64)ulength);
  698. }
  699. hash = fnv64a(text, cast(isize)length);
  700. } else {
  701. return {};
  702. }
  703. // TODO(bill): other const hash types
  704. if (build_context.word_size == 4) {
  705. hash &= 0xffffffffull;
  706. }
  707. hashed_key = lb_const_int(m, t_uintptr, hash);
  708. }
  709. #endif
  710. return hashed_key;
  711. }
  712. gb_internal lbValue lb_gen_map_key_hash(lbProcedure *p, lbValue key, Type *key_type, lbValue *key_ptr_) {
  713. TEMPORARY_ALLOCATOR_GUARD();
  714. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  715. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  716. if (key_ptr_) *key_ptr_ = key_ptr;
  717. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  718. if (hashed_key.value == nullptr) {
  719. lbValue hasher = lb_hasher_proc_for_type(p->module, key_type);
  720. auto args = array_make<lbValue>(temporary_allocator(), 2);
  721. args[0] = key_ptr;
  722. args[1] = lb_const_int(p->module, t_uintptr, 0);
  723. hashed_key = lb_emit_call(p, hasher, args);
  724. }
  725. return hashed_key;
  726. }
  727. gb_internal lbValue lb_internal_dynamic_map_get_ptr(lbProcedure *p, lbValue const &map_ptr, lbValue const &key) {
  728. TEMPORARY_ALLOCATOR_GUARD();
  729. Type *map_type = base_type(type_deref(map_ptr.type));
  730. GB_ASSERT(map_type->kind == Type_Map);
  731. lbValue ptr = {};
  732. lbValue key_ptr = {};
  733. lbValue hash = lb_gen_map_key_hash(p, key, map_type->Map.key, &key_ptr);
  734. if (build_context.dynamic_map_calls) {
  735. auto args = array_make<lbValue>(temporary_allocator(), 4);
  736. args[0] = lb_emit_transmute(p, map_ptr, t_raw_map_ptr);
  737. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  738. args[2] = hash;
  739. args[3] = key_ptr;
  740. ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  741. } else {
  742. lbValue map_get_proc = lb_map_get_proc_for_type(p->module, map_type);
  743. auto args = array_make<lbValue>(temporary_allocator(), 3);
  744. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  745. args[1] = hash;
  746. args[2] = key_ptr;
  747. ptr = lb_emit_call(p, map_get_proc, args);
  748. }
  749. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  750. }
  751. gb_internal void lb_internal_dynamic_map_set(lbProcedure *p, lbValue const &map_ptr, Type *map_type,
  752. lbValue const &map_key, lbValue const &map_value, Ast *node) {
  753. TEMPORARY_ALLOCATOR_GUARD();
  754. map_type = base_type(map_type);
  755. GB_ASSERT(map_type->kind == Type_Map);
  756. lbValue key_ptr = {};
  757. lbValue hash = lb_gen_map_key_hash(p, map_key, map_type->Map.key, &key_ptr);
  758. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  759. lbValue value_ptr = lb_address_from_load_or_generate_local(p, v);
  760. if (build_context.dynamic_map_calls) {
  761. auto args = array_make<lbValue>(temporary_allocator(), 6);
  762. args[0] = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  763. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  764. args[2] = hash;
  765. args[3] = lb_emit_conv(p, key_ptr, t_rawptr);
  766. args[4] = lb_emit_conv(p, value_ptr, t_rawptr);
  767. args[5] = lb_emit_source_code_location_as_global(p, node);
  768. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  769. } else {
  770. lbValue map_set_proc = lb_map_set_proc_for_type(p->module, map_type);
  771. auto args = array_make<lbValue>(temporary_allocator(), 5);
  772. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  773. args[1] = hash;
  774. args[2] = lb_emit_conv(p, key_ptr, t_rawptr);
  775. args[3] = lb_emit_conv(p, value_ptr, t_rawptr);
  776. args[4] = lb_emit_source_code_location_as_global(p, node);
  777. lb_emit_call(p, map_set_proc, args);
  778. }
  779. }
  780. gb_internal lbValue lb_dynamic_map_reserve(lbProcedure *p, lbValue const &map_ptr, isize const capacity, TokenPos const &pos) {
  781. GB_ASSERT(!build_context.no_dynamic_literals);
  782. TEMPORARY_ALLOCATOR_GUARD();
  783. String proc_name = {};
  784. if (p->entity) {
  785. proc_name = p->entity->token.string;
  786. }
  787. auto args = array_make<lbValue>(temporary_allocator(), 4);
  788. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  789. args[1] = lb_gen_map_info_ptr(p->module, type_deref(map_ptr.type));
  790. args[2] = lb_const_int(p->module, t_uint, capacity);
  791. args[3] = lb_emit_source_code_location_as_global(p, proc_name, pos);
  792. return lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  793. }
  794. struct lbGlobalVariable {
  795. lbValue var;
  796. lbValue init;
  797. DeclInfo *decl;
  798. bool is_initialized;
  799. };
  800. gb_internal lbProcedure *lb_create_startup_type_info(lbModule *m) {
  801. if (build_context.disallow_rtti) {
  802. return nullptr;
  803. }
  804. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  805. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  806. p->is_startup = true;
  807. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  808. lb_add_attribute_to_proc(m, p->value, "nounwind");
  809. lb_begin_procedure_body(p);
  810. lb_setup_type_info_data(p);
  811. lb_end_procedure_body(p);
  812. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  813. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  814. LLVMDumpValue(p->value);
  815. gb_printf_err("\n\n\n\n");
  816. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  817. }
  818. return p;
  819. }
  820. gb_internal lbProcedure *lb_create_objc_names(lbModule *main_module) {
  821. if (build_context.metrics.os != TargetOs_darwin) {
  822. return nullptr;
  823. }
  824. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  825. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit("__$init_objc_names"), proc_type);
  826. lb_add_attribute_to_proc(p->module, p->value, "nounwind");
  827. p->is_startup = true;
  828. return p;
  829. }
  830. gb_internal void lb_finalize_objc_names(lbProcedure *p) {
  831. if (p == nullptr) {
  832. return;
  833. }
  834. lbModule *m = p->module;
  835. TEMPORARY_ALLOCATOR_GUARD();
  836. auto args = array_make<lbValue>(temporary_allocator(), 1);
  837. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  838. lb_begin_procedure_body(p);
  839. for (auto const &entry : m->objc_classes) {
  840. String name = entry.key;
  841. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  842. lbValue ptr = lb_emit_runtime_call(p, "objc_lookUpClass", args);
  843. lb_addr_store(p, entry.value, ptr);
  844. }
  845. for (auto const &entry : m->objc_selectors) {
  846. String name = entry.key;
  847. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  848. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  849. lb_addr_store(p, entry.value, ptr);
  850. }
  851. lb_end_procedure_body(p);
  852. }
  853. gb_internal lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *startup_type_info, lbProcedure *objc_names, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  854. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  855. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  856. p->is_startup = true;
  857. lb_begin_procedure_body(p);
  858. if (startup_type_info) {
  859. LLVMBuildCall2(p->builder, lb_type_internal_for_procedures_raw(main_module, startup_type_info->type), startup_type_info->value, nullptr, 0, "");
  860. }
  861. if (objc_names) {
  862. LLVMBuildCall2(p->builder, lb_type_internal_for_procedures_raw(main_module, objc_names->type), objc_names->value, nullptr, 0, "");
  863. }
  864. for (auto &var : global_variables) {
  865. if (var.is_initialized) {
  866. continue;
  867. }
  868. lbModule *entity_module = main_module;
  869. Entity *e = var.decl->entity;
  870. GB_ASSERT(e->kind == Entity_Variable);
  871. e->code_gen_module = entity_module;
  872. Ast *init_expr = var.decl->init_expr;
  873. if (init_expr != nullptr) {
  874. lbValue init = lb_build_expr(p, init_expr);
  875. if (init.value == nullptr) {
  876. LLVMTypeRef global_type = llvm_addr_type(p->module, var.var);
  877. if (is_type_untyped_nil(init.type)) {
  878. LLVMSetInitializer(var.var.value, LLVMConstNull(global_type));
  879. var.is_initialized = true;
  880. continue;
  881. }
  882. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  883. }
  884. if (is_type_any(e->type) || is_type_union(e->type)) {
  885. var.init = init;
  886. } else if (lb_is_const_or_global(init)) {
  887. if (!var.is_initialized) {
  888. if (is_type_proc(init.type)) {
  889. init.value = LLVMConstPointerCast(init.value, lb_type(p->module, init.type));
  890. }
  891. LLVMSetInitializer(var.var.value, init.value);
  892. var.is_initialized = true;
  893. continue;
  894. }
  895. } else {
  896. var.init = init;
  897. }
  898. }
  899. if (var.init.value != nullptr) {
  900. GB_ASSERT(!var.is_initialized);
  901. Type *t = type_deref(var.var.type);
  902. if (is_type_any(t)) {
  903. // NOTE(bill): Edge case for 'any' type
  904. Type *var_type = default_type(var.init.type);
  905. lbAddr g = lb_add_global_generated(main_module, var_type, var.init);
  906. lb_addr_store(p, g, var.init);
  907. lbValue gp = lb_addr_get_ptr(p, g);
  908. lbValue data = lb_emit_struct_ep(p, var.var, 0);
  909. lbValue ti = lb_emit_struct_ep(p, var.var, 1);
  910. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  911. lb_emit_store(p, ti, lb_type_info(main_module, var_type));
  912. } else {
  913. LLVMTypeRef vt = llvm_addr_type(p->module, var.var);
  914. lbValue src0 = lb_emit_conv(p, var.init, t);
  915. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  916. LLVMValueRef dst = var.var.value;
  917. LLVMBuildStore(p->builder, src, dst);
  918. }
  919. var.is_initialized = true;
  920. }
  921. }
  922. CheckerInfo *info = main_module->gen->info;
  923. for (Entity *e : info->init_procedures) {
  924. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  925. lb_emit_call(p, value, {}, ProcInlining_none);
  926. }
  927. lb_end_procedure_body(p);
  928. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  929. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  930. LLVMDumpValue(p->value);
  931. gb_printf_err("\n\n\n\n");
  932. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  933. }
  934. return p;
  935. }
  936. gb_internal lbProcedure *lb_create_cleanup_runtime(lbModule *main_module) { // Cleanup Runtime
  937. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  938. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_CLEANUP_RUNTIME_PROC_NAME), proc_type);
  939. p->is_startup = true;
  940. lb_begin_procedure_body(p);
  941. CheckerInfo *info = main_module->gen->info;
  942. for (Entity *e : info->fini_procedures) {
  943. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  944. lb_emit_call(p, value, {}, ProcInlining_none);
  945. }
  946. lb_end_procedure_body(p);
  947. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  948. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  949. LLVMDumpValue(p->value);
  950. gb_printf_err("\n\n\n\n");
  951. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  952. }
  953. return p;
  954. }
  955. gb_internal WORKER_TASK_PROC(lb_generate_procedures_and_types_per_module) {
  956. lbModule *m = cast(lbModule *)data;
  957. for (Entity *e : m->global_procedures_and_types_to_create) {
  958. if (e->kind == Entity_TypeName) {
  959. (void)lb_get_entity_name(m, e);
  960. lb_type(m, e->type);
  961. }
  962. }
  963. for (Entity *e : m->global_procedures_and_types_to_create) {
  964. if (e->kind == Entity_Procedure) {
  965. (void)lb_get_entity_name(m, e);
  966. array_add(&m->procedures_to_generate, lb_create_procedure(m, e));
  967. }
  968. }
  969. return 0;
  970. }
  971. gb_internal void lb_create_global_procedures_and_types(lbGenerator *gen, CheckerInfo *info, bool do_threading) {
  972. auto *min_dep_set = &info->minimum_dependency_set;
  973. for (Entity *e : info->entities) {
  974. String name = e->token.string;
  975. Scope * scope = e->scope;
  976. if ((scope->flags & ScopeFlag_File) == 0) {
  977. continue;
  978. }
  979. Scope *package_scope = scope->parent;
  980. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  981. switch (e->kind) {
  982. case Entity_Variable:
  983. // NOTE(bill): Handled above as it requires a specific load order
  984. continue;
  985. case Entity_ProcGroup:
  986. continue;
  987. case Entity_TypeName:
  988. case Entity_Procedure:
  989. break;
  990. case Entity_Constant:
  991. if (build_context.ODIN_DEBUG) {
  992. add_debug_info_for_global_constant_from_entity(gen, e);
  993. }
  994. break;
  995. }
  996. bool polymorphic_struct = false;
  997. if (e->type != nullptr && e->kind == Entity_TypeName) {
  998. Type *bt = base_type(e->type);
  999. if (bt->kind == Type_Struct) {
  1000. polymorphic_struct = is_type_polymorphic(bt);
  1001. }
  1002. }
  1003. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1004. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1005. continue;
  1006. }
  1007. lbModule *m = &gen->default_module;
  1008. if (USE_SEPARATE_MODULES) {
  1009. m = lb_module_of_entity(gen, e);
  1010. }
  1011. array_add(&m->global_procedures_and_types_to_create, e);
  1012. }
  1013. for (auto const &entry : gen->modules) {
  1014. lbModule *m = entry.value;
  1015. if (do_threading) {
  1016. thread_pool_add_task(lb_generate_procedures_and_types_per_module, m);
  1017. } else {
  1018. lb_generate_procedures_and_types_per_module(m);
  1019. }
  1020. }
  1021. thread_pool_wait();
  1022. }
  1023. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p);
  1024. gb_internal bool lb_is_module_empty(lbModule *m) {
  1025. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  1026. LLVMGetFirstGlobal(m->mod) == nullptr) {
  1027. return true;
  1028. }
  1029. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  1030. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  1031. return false;
  1032. }
  1033. }
  1034. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  1035. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  1036. continue;
  1037. }
  1038. if (!LLVMIsExternallyInitialized(g)) {
  1039. return false;
  1040. }
  1041. }
  1042. return true;
  1043. }
  1044. struct lbLLVMEmitWorker {
  1045. LLVMTargetMachineRef target_machine;
  1046. LLVMCodeGenFileType code_gen_file_type;
  1047. String filepath_obj;
  1048. lbModule *m;
  1049. };
  1050. gb_internal WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  1051. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  1052. char *llvm_error = nullptr;
  1053. auto wd = cast(lbLLVMEmitWorker *)data;
  1054. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  1055. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1056. gb_exit(1);
  1057. }
  1058. debugf("Generated File: %.*s\n", LIT(wd->filepath_obj));
  1059. return 0;
  1060. }
  1061. gb_internal void lb_llvm_function_pass_per_function_internal(lbModule *module, lbProcedure *p, lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default) {
  1062. LLVMPassManagerRef pass_manager = module->function_pass_managers[pass_manager_kind];
  1063. lb_run_function_pass_manager(pass_manager, p);
  1064. }
  1065. gb_internal WORKER_TASK_PROC(lb_llvm_function_pass_per_module) {
  1066. lbModule *m = cast(lbModule *)data;
  1067. {
  1068. GB_ASSERT(m->function_pass_managers[lbFunctionPassManager_default] == nullptr);
  1069. m->function_pass_managers[lbFunctionPassManager_default] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1070. m->function_pass_managers[lbFunctionPassManager_default_without_memcpy] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1071. m->function_pass_managers[lbFunctionPassManager_none] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1072. m->function_pass_managers[lbFunctionPassManager_minimal] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1073. m->function_pass_managers[lbFunctionPassManager_size] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1074. m->function_pass_managers[lbFunctionPassManager_speed] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1075. LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_default]);
  1076. LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_default_without_memcpy]);
  1077. LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_none]);
  1078. LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_minimal]);
  1079. LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_size]);
  1080. LLVMInitializeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_speed]);
  1081. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default], false, build_context.optimization_level);
  1082. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default_without_memcpy], true, build_context.optimization_level);
  1083. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_none], -1);
  1084. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_minimal], 0);
  1085. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_size], 1);
  1086. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_speed], 2);
  1087. LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_default]);
  1088. LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_default_without_memcpy]);
  1089. LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_none]);
  1090. LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_minimal]);
  1091. LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_size]);
  1092. LLVMFinalizeFunctionPassManager(m->function_pass_managers[lbFunctionPassManager_speed]);
  1093. }
  1094. if (m == &m->gen->default_module) {
  1095. lb_llvm_function_pass_per_function_internal(m, m->gen->startup_type_info);
  1096. lb_llvm_function_pass_per_function_internal(m, m->gen->startup_runtime);
  1097. lb_llvm_function_pass_per_function_internal(m, m->gen->cleanup_runtime);
  1098. lb_llvm_function_pass_per_function_internal(m, m->gen->objc_names);
  1099. }
  1100. for (lbProcedure *p : m->procedures_to_generate) {
  1101. if (p->body != nullptr) { // Build Procedure
  1102. lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default;
  1103. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  1104. pass_manager_kind = lbFunctionPassManager_default_without_memcpy;
  1105. } else {
  1106. if (p->entity && p->entity->kind == Entity_Procedure) {
  1107. switch (p->entity->Procedure.optimization_mode) {
  1108. case ProcedureOptimizationMode_None:
  1109. case ProcedureOptimizationMode_Minimal:
  1110. pass_manager_kind = lbFunctionPassManager_minimal;
  1111. break;
  1112. case ProcedureOptimizationMode_Size:
  1113. pass_manager_kind = lbFunctionPassManager_size;
  1114. break;
  1115. case ProcedureOptimizationMode_Speed:
  1116. pass_manager_kind = lbFunctionPassManager_speed;
  1117. break;
  1118. }
  1119. }
  1120. }
  1121. lb_llvm_function_pass_per_function_internal(m, p, pass_manager_kind);
  1122. }
  1123. }
  1124. for (auto const &entry : m->equal_procs) {
  1125. lbProcedure *p = entry.value;
  1126. lb_llvm_function_pass_per_function_internal(m, p);
  1127. }
  1128. for (auto const &entry : m->hasher_procs) {
  1129. lbProcedure *p = entry.value;
  1130. lb_llvm_function_pass_per_function_internal(m, p);
  1131. }
  1132. for (auto const &entry : m->map_get_procs) {
  1133. lbProcedure *p = entry.value;
  1134. lb_llvm_function_pass_per_function_internal(m, p, lbFunctionPassManager_none);
  1135. }
  1136. for (auto const &entry : m->map_set_procs) {
  1137. lbProcedure *p = entry.value;
  1138. lb_llvm_function_pass_per_function_internal(m, p, lbFunctionPassManager_none);
  1139. }
  1140. return 0;
  1141. }
  1142. struct lbLLVMModulePassWorkerData {
  1143. lbModule *m;
  1144. LLVMTargetMachineRef target_machine;
  1145. };
  1146. gb_internal WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  1147. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  1148. lb_run_remove_unused_function_pass(wd->m);
  1149. lb_run_remove_unused_globals_pass(wd->m);
  1150. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  1151. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  1152. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  1153. return 0;
  1154. }
  1155. gb_internal WORKER_TASK_PROC(lb_generate_procedures_worker_proc) {
  1156. lbModule *m = cast(lbModule *)data;
  1157. for (isize i = 0; i < m->procedures_to_generate.count; i++) {
  1158. lbProcedure *p = m->procedures_to_generate[i];
  1159. lb_generate_procedure(p->module, p);
  1160. }
  1161. return 0;
  1162. }
  1163. gb_internal void lb_generate_procedures(lbGenerator *gen, bool do_threading) {
  1164. for (auto const &entry : gen->modules) {
  1165. lbModule *m = entry.value;
  1166. if (do_threading) {
  1167. thread_pool_add_task(lb_generate_procedures_worker_proc, m);
  1168. } else {
  1169. lb_generate_procedures_worker_proc(m);
  1170. }
  1171. }
  1172. thread_pool_wait();
  1173. }
  1174. gb_internal WORKER_TASK_PROC(lb_generate_missing_procedures_to_check_worker_proc) {
  1175. lbModule *m = cast(lbModule *)data;
  1176. for (isize i = 0; i < m->missing_procedures_to_check.count; i++) {
  1177. lbProcedure *p = m->missing_procedures_to_check[i];
  1178. debugf("Generate missing procedure: %.*s\n", LIT(p->name));
  1179. lb_generate_procedure(m, p);
  1180. }
  1181. return 0;
  1182. }
  1183. gb_internal void lb_generate_missing_procedures(lbGenerator *gen, bool do_threading) {
  1184. for (auto const &entry : gen->modules) {
  1185. lbModule *m = entry.value;
  1186. // NOTE(bill): procedures may be added during generation
  1187. if (do_threading) {
  1188. thread_pool_add_task(lb_generate_missing_procedures_to_check_worker_proc, m);
  1189. } else {
  1190. lb_generate_missing_procedures_to_check_worker_proc(m);
  1191. }
  1192. }
  1193. thread_pool_wait();
  1194. }
  1195. gb_internal void lb_debug_info_complete_types_and_finalize(lbGenerator *gen) {
  1196. for (auto const &entry : gen->modules) {
  1197. lbModule *m = entry.value;
  1198. if (m->debug_builder != nullptr) {
  1199. lb_debug_complete_types(m);
  1200. }
  1201. }
  1202. for (auto const &entry : gen->modules) {
  1203. lbModule *m = entry.value;
  1204. if (m->debug_builder != nullptr) {
  1205. LLVMDIBuilderFinalize(m->debug_builder);
  1206. }
  1207. }
  1208. }
  1209. gb_internal void lb_llvm_function_passes(lbGenerator *gen, bool do_threading) {
  1210. for (auto const &entry : gen->modules) {
  1211. lbModule *m = entry.value;
  1212. if (do_threading) {
  1213. thread_pool_add_task(lb_llvm_function_pass_per_module, m);
  1214. } else {
  1215. lb_llvm_function_pass_per_module(m);
  1216. }
  1217. }
  1218. thread_pool_wait();
  1219. }
  1220. gb_internal void lb_llvm_module_passes(lbGenerator *gen, bool do_threading) {
  1221. for (auto const &entry : gen->modules) {
  1222. lbModule *m = entry.value;
  1223. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  1224. wd->m = m;
  1225. wd->target_machine = m->target_machine;
  1226. if (do_threading) {
  1227. thread_pool_add_task(lb_llvm_module_pass_worker_proc, wd);
  1228. } else {
  1229. lb_llvm_module_pass_worker_proc(wd);
  1230. }
  1231. }
  1232. thread_pool_wait();
  1233. }
  1234. gb_internal String lb_filepath_ll_for_module(lbModule *m) {
  1235. String path = concatenate3_strings(permanent_allocator(),
  1236. build_context.build_paths[BuildPath_Output].basename,
  1237. STR_LIT("/"),
  1238. build_context.build_paths[BuildPath_Output].name
  1239. );
  1240. if (m->file) {
  1241. char buf[32] = {};
  1242. isize n = gb_snprintf(buf, gb_size_of(buf), "-%u", m->file->id);
  1243. String suffix = make_string((u8 *)buf, n-1);
  1244. path = concatenate_strings(permanent_allocator(), path, suffix);
  1245. } else if (m->pkg) {
  1246. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  1247. } else if (USE_SEPARATE_MODULES) {
  1248. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  1249. }
  1250. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  1251. return path;
  1252. }
  1253. gb_internal String lb_filepath_obj_for_module(lbModule *m) {
  1254. String path = concatenate3_strings(permanent_allocator(),
  1255. build_context.build_paths[BuildPath_Output].basename,
  1256. STR_LIT("/"),
  1257. build_context.build_paths[BuildPath_Output].name
  1258. );
  1259. if (m->file) {
  1260. char buf[32] = {};
  1261. isize n = gb_snprintf(buf, gb_size_of(buf), "-%u", m->file->id);
  1262. String suffix = make_string((u8 *)buf, n-1);
  1263. path = concatenate_strings(permanent_allocator(), path, suffix);
  1264. } else if (m->pkg) {
  1265. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  1266. }
  1267. String ext = {};
  1268. if (build_context.build_mode == BuildMode_Assembly) {
  1269. ext = STR_LIT(".S");
  1270. } else {
  1271. if (is_arch_wasm()) {
  1272. ext = STR_LIT(".wasm.o");
  1273. } else {
  1274. switch (build_context.metrics.os) {
  1275. case TargetOs_windows:
  1276. ext = STR_LIT(".obj");
  1277. break;
  1278. default:
  1279. case TargetOs_darwin:
  1280. case TargetOs_linux:
  1281. case TargetOs_essence:
  1282. ext = STR_LIT(".o");
  1283. break;
  1284. case TargetOs_freestanding:
  1285. switch (build_context.metrics.abi) {
  1286. default:
  1287. case TargetABI_Default:
  1288. case TargetABI_SysV:
  1289. ext = STR_LIT(".o");
  1290. break;
  1291. case TargetABI_Win64:
  1292. ext = STR_LIT(".obj");
  1293. break;
  1294. }
  1295. break;
  1296. }
  1297. }
  1298. }
  1299. return concatenate_strings(permanent_allocator(), path, ext);
  1300. }
  1301. gb_internal WORKER_TASK_PROC(lb_llvm_module_verification_worker_proc) {
  1302. char *llvm_error = nullptr;
  1303. defer (LLVMDisposeMessage(llvm_error));
  1304. lbModule *m = cast(lbModule *)data;
  1305. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  1306. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1307. if (build_context.keep_temp_files) {
  1308. TIME_SECTION("LLVM Print Module to File");
  1309. String filepath_ll = lb_filepath_ll_for_module(m);
  1310. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1311. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1312. gb_exit(1);
  1313. return false;
  1314. }
  1315. }
  1316. gb_exit(1);
  1317. return 1;
  1318. }
  1319. return 0;
  1320. }
  1321. gb_internal bool lb_llvm_module_verification(lbGenerator *gen, bool do_threading) {
  1322. for (auto const &entry : gen->modules) {
  1323. lbModule *m = entry.value;
  1324. if (do_threading) {
  1325. thread_pool_add_task(lb_llvm_module_verification_worker_proc, m);
  1326. } else {
  1327. if (lb_llvm_module_verification_worker_proc(m)) {
  1328. return false;
  1329. }
  1330. }
  1331. }
  1332. thread_pool_wait();
  1333. return true;
  1334. }
  1335. gb_internal void lb_add_foreign_library_paths(lbGenerator *gen) {
  1336. for (auto const &entry : gen->modules) {
  1337. lbModule *m = entry.value;
  1338. for (Entity *e : m->info->required_foreign_imports_through_force) {
  1339. lb_add_foreign_library_path(m, e);
  1340. }
  1341. if (lb_is_module_empty(m)) {
  1342. continue;
  1343. }
  1344. }
  1345. }
  1346. gb_internal bool lb_llvm_object_generation(lbGenerator *gen, bool do_threading) {
  1347. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  1348. if (build_context.build_mode == BuildMode_Assembly) {
  1349. code_gen_file_type = LLVMAssemblyFile;
  1350. }
  1351. char *llvm_error = nullptr;
  1352. defer (LLVMDisposeMessage(llvm_error));
  1353. if (do_threading) {
  1354. for (auto const &entry : gen->modules) {
  1355. lbModule *m = entry.value;
  1356. if (lb_is_module_empty(m)) {
  1357. continue;
  1358. }
  1359. String filepath_ll = lb_filepath_ll_for_module(m);
  1360. String filepath_obj = lb_filepath_obj_for_module(m);
  1361. // gb_printf_err("%.*s\n", LIT(filepath_obj));
  1362. array_add(&gen->output_object_paths, filepath_obj);
  1363. array_add(&gen->output_temp_paths, filepath_ll);
  1364. auto *wd = gb_alloc_item(permanent_allocator(), lbLLVMEmitWorker);
  1365. wd->target_machine = m->target_machine;
  1366. wd->code_gen_file_type = code_gen_file_type;
  1367. wd->filepath_obj = filepath_obj;
  1368. wd->m = m;
  1369. thread_pool_add_task(lb_llvm_emit_worker_proc, wd);
  1370. }
  1371. thread_pool_wait(&global_thread_pool);
  1372. } else {
  1373. for (auto const &entry : gen->modules) {
  1374. lbModule *m = entry.value;
  1375. if (lb_is_module_empty(m)) {
  1376. continue;
  1377. }
  1378. String filepath_obj = lb_filepath_obj_for_module(m);
  1379. array_add(&gen->output_object_paths, filepath_obj);
  1380. String short_name = remove_directory_from_path(filepath_obj);
  1381. gbString section_name = gb_string_make(permanent_allocator(), "LLVM Generate Object: ");
  1382. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  1383. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  1384. if (LLVMTargetMachineEmitToFile(m->target_machine, m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  1385. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1386. gb_exit(1);
  1387. return false;
  1388. }
  1389. debugf("Generated File: %.*s\n", LIT(filepath_obj));
  1390. }
  1391. }
  1392. return true;
  1393. }
  1394. gb_internal lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime, lbProcedure *cleanup_runtime) {
  1395. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  1396. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  1397. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  1398. Type *params = alloc_type_tuple();
  1399. Type *results = alloc_type_tuple();
  1400. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  1401. bool call_cleanup = true;
  1402. bool has_args = false;
  1403. bool is_dll_main = false;
  1404. String name = str_lit("main");
  1405. if (build_context.metrics.os == TargetOs_windows && build_context.build_mode == BuildMode_DynamicLibrary) {
  1406. is_dll_main = true;
  1407. name = str_lit("DllMain");
  1408. slice_init(&params->Tuple.variables, permanent_allocator(), 3);
  1409. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("hinstDLL"), t_rawptr, false, true);
  1410. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("fdwReason"), t_u32, false, true);
  1411. params->Tuple.variables[2] = alloc_entity_param(nullptr, make_token_ident("lpReserved"), t_rawptr, false, true);
  1412. call_cleanup = false;
  1413. } else if (build_context.metrics.os == TargetOs_windows && (build_context.metrics.arch == TargetArch_i386 || build_context.no_crt)) {
  1414. name = str_lit("mainCRTStartup");
  1415. } else if (is_arch_wasm()) {
  1416. name = str_lit("_start");
  1417. call_cleanup = false;
  1418. } else {
  1419. has_args = true;
  1420. slice_init(&params->Tuple.variables, permanent_allocator(), 2);
  1421. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  1422. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  1423. }
  1424. slice_init(&results->Tuple.variables, permanent_allocator(), 1);
  1425. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  1426. Type *proc_type = alloc_type_proc(nullptr,
  1427. params, params->Tuple.variables.count,
  1428. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  1429. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  1430. p->is_startup = true;
  1431. lb_begin_procedure_body(p);
  1432. if (has_args) { // initialize `runtime.args__`
  1433. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  1434. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  1435. LLVMSetValueName2(argc.value, "argc", 4);
  1436. LLVMSetValueName2(argv.value, "argv", 4);
  1437. argc = lb_emit_conv(p, argc, t_int);
  1438. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  1439. lb_fill_slice(p, args, argv, argc);
  1440. }
  1441. lbValue startup_runtime_value = {startup_runtime->value, startup_runtime->type};
  1442. lb_emit_call(p, startup_runtime_value, {}, ProcInlining_none);
  1443. if (build_context.command_kind == Command_test) {
  1444. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  1445. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  1446. Type *slice_type = alloc_type_slice(t_Internal_Test);
  1447. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  1448. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  1449. LLVMValueRef indices[2] = {};
  1450. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  1451. isize testing_proc_index = 0;
  1452. for (Entity *testing_proc : m->info->testing_procedures) {
  1453. String name = testing_proc->token.string;
  1454. String pkg_name = {};
  1455. if (testing_proc->pkg != nullptr) {
  1456. pkg_name = testing_proc->pkg->name;
  1457. }
  1458. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  1459. lbValue v_name = lb_find_or_add_entity_string(m, name);
  1460. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  1461. indices[1] = LLVMConstInt(lb_type(m, t_int), testing_proc_index++, false);
  1462. LLVMValueRef vals[3] = {};
  1463. vals[0] = v_pkg.value;
  1464. vals[1] = v_name.value;
  1465. vals[2] = v_proc.value;
  1466. GB_ASSERT(LLVMIsConstant(vals[0]));
  1467. GB_ASSERT(LLVMIsConstant(vals[1]));
  1468. GB_ASSERT(LLVMIsConstant(vals[2]));
  1469. LLVMValueRef dst = LLVMConstInBoundsGEP2(llvm_addr_type(m, all_tests_array), all_tests_array.value, indices, gb_count_of(indices));
  1470. LLVMValueRef src = llvm_const_named_struct(m, t_Internal_Test, vals, gb_count_of(vals));
  1471. LLVMBuildStore(p->builder, src, dst);
  1472. }
  1473. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  1474. lb_fill_slice(p, all_tests_slice,
  1475. lb_array_elem(p, all_tests_array),
  1476. lb_const_int(m, t_int, m->info->testing_procedures.count));
  1477. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  1478. TEMPORARY_ALLOCATOR_GUARD();
  1479. auto args = array_make<lbValue>(temporary_allocator(), 1);
  1480. args[0] = lb_addr_load(p, all_tests_slice);
  1481. lb_emit_call(p, runner, args);
  1482. } else {
  1483. if (m->info->entry_point != nullptr) {
  1484. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  1485. lb_emit_call(p, entry_point, {}, ProcInlining_no_inline);
  1486. }
  1487. }
  1488. if (call_cleanup) {
  1489. lbValue cleanup_runtime_value = {cleanup_runtime->value, cleanup_runtime->type};
  1490. lb_emit_call(p, cleanup_runtime_value, {}, ProcInlining_none);
  1491. }
  1492. if (is_dll_main) {
  1493. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 1, false));
  1494. } else {
  1495. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  1496. }
  1497. lb_end_procedure_body(p);
  1498. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  1499. if (is_arch_wasm()) {
  1500. lb_set_wasm_export_attributes(p->value, p->name);
  1501. }
  1502. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  1503. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  1504. LLVMDumpValue(p->value);
  1505. gb_printf_err("\n\n\n\n");
  1506. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  1507. }
  1508. lb_run_function_pass_manager(default_function_pass_manager, p);
  1509. return p;
  1510. }
  1511. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p) {
  1512. if (p->is_done) {
  1513. return;
  1514. }
  1515. if (p->body != nullptr) { // Build Procedure
  1516. m->curr_procedure = p;
  1517. lb_begin_procedure_body(p);
  1518. lb_build_stmt(p, p->body);
  1519. lb_end_procedure_body(p);
  1520. p->is_done = true;
  1521. m->curr_procedure = nullptr;
  1522. }
  1523. lb_end_procedure(p);
  1524. // Add Flags
  1525. if (p->body != nullptr) {
  1526. if (p->name == "memcpy" || p->name == "memmove" ||
  1527. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  1528. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  1529. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  1530. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  1531. }
  1532. }
  1533. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  1534. char *llvm_error = nullptr;
  1535. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  1536. LLVMDumpValue(p->value);
  1537. gb_printf_err("\n\n\n\n");
  1538. String filepath_ll = lb_filepath_ll_for_module(m);
  1539. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1540. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1541. }
  1542. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  1543. gb_exit(1);
  1544. }
  1545. }
  1546. gb_internal bool lb_generate_code(lbGenerator *gen) {
  1547. TIME_SECTION("LLVM Initializtion");
  1548. isize thread_count = gb_max(build_context.thread_count, 1);
  1549. isize worker_count = thread_count-1;
  1550. bool do_threading = !!(LLVMIsMultithreaded() && USE_SEPARATE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  1551. lbModule *default_module = &gen->default_module;
  1552. CheckerInfo *info = gen->info;
  1553. auto *min_dep_set = &info->minimum_dependency_set;
  1554. switch (build_context.metrics.arch) {
  1555. case TargetArch_amd64:
  1556. case TargetArch_i386:
  1557. LLVMInitializeX86TargetInfo();
  1558. LLVMInitializeX86Target();
  1559. LLVMInitializeX86TargetMC();
  1560. LLVMInitializeX86AsmPrinter();
  1561. LLVMInitializeX86AsmParser();
  1562. LLVMInitializeX86Disassembler();
  1563. break;
  1564. case TargetArch_arm64:
  1565. LLVMInitializeAArch64TargetInfo();
  1566. LLVMInitializeAArch64Target();
  1567. LLVMInitializeAArch64TargetMC();
  1568. LLVMInitializeAArch64AsmPrinter();
  1569. LLVMInitializeAArch64AsmParser();
  1570. LLVMInitializeAArch64Disassembler();
  1571. break;
  1572. case TargetArch_wasm32:
  1573. case TargetArch_wasm64:
  1574. LLVMInitializeWebAssemblyTargetInfo();
  1575. LLVMInitializeWebAssemblyTarget();
  1576. LLVMInitializeWebAssemblyTargetMC();
  1577. LLVMInitializeWebAssemblyAsmPrinter();
  1578. LLVMInitializeWebAssemblyAsmParser();
  1579. LLVMInitializeWebAssemblyDisassembler();
  1580. break;
  1581. default:
  1582. LLVMInitializeAllTargetInfos();
  1583. LLVMInitializeAllTargets();
  1584. LLVMInitializeAllTargetMCs();
  1585. LLVMInitializeAllAsmPrinters();
  1586. LLVMInitializeAllAsmParsers();
  1587. LLVMInitializeAllDisassemblers();
  1588. break;
  1589. }
  1590. if (build_context.microarch == "native") {
  1591. LLVMInitializeNativeTarget();
  1592. }
  1593. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  1594. for (auto const &entry : gen->modules) {
  1595. LLVMSetTarget(entry.value->mod, target_triple);
  1596. }
  1597. LLVMTargetRef target = {};
  1598. char *llvm_error = nullptr;
  1599. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  1600. GB_ASSERT(target != nullptr);
  1601. TIME_SECTION("LLVM Create Target Machine");
  1602. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  1603. if (is_arch_wasm()) {
  1604. code_mode = LLVMCodeModelJITDefault;
  1605. } else if (build_context.metrics.os == TargetOs_freestanding) {
  1606. code_mode = LLVMCodeModelKernel;
  1607. }
  1608. char const *host_cpu_name = LLVMGetHostCPUName();
  1609. char const *llvm_cpu = "generic";
  1610. char const *llvm_features = "";
  1611. if (build_context.microarch.len != 0) {
  1612. if (build_context.microarch == "native") {
  1613. llvm_cpu = host_cpu_name;
  1614. } else {
  1615. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  1616. }
  1617. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  1618. llvm_features = LLVMGetHostCPUFeatures();
  1619. }
  1620. } else if (build_context.metrics.arch == TargetArch_amd64) {
  1621. // NOTE(bill): x86-64-v2 is more than enough for everyone
  1622. //
  1623. // x86-64: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
  1624. // x86-64-v2: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
  1625. // x86-64-v3: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
  1626. // x86-64-v4: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
  1627. if (ODIN_LLVM_MINIMUM_VERSION_12) {
  1628. if (build_context.metrics.os == TargetOs_freestanding) {
  1629. llvm_cpu = "x86-64";
  1630. } else {
  1631. llvm_cpu = "x86-64-v2";
  1632. }
  1633. }
  1634. }
  1635. if (build_context.target_features_set.entries.count != 0) {
  1636. llvm_features = target_features_set_to_cstring(permanent_allocator(), false);
  1637. }
  1638. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  1639. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  1640. switch (build_context.optimization_level) {
  1641. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  1642. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  1643. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  1644. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  1645. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  1646. }
  1647. // NOTE(bill): Target Machine Creation
  1648. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  1649. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), 0, gen->modules.count);
  1650. // NOTE(dweiler): Dynamic libraries require position-independent code.
  1651. LLVMRelocMode reloc_mode = LLVMRelocDefault;
  1652. if (build_context.build_mode == BuildMode_DynamicLibrary) {
  1653. reloc_mode = LLVMRelocPIC;
  1654. }
  1655. switch (build_context.reloc_mode) {
  1656. case RelocMode_Default:
  1657. if (build_context.metrics.os == TargetOs_openbsd) {
  1658. // Always use PIC for OpenBSD: it defaults to PIE
  1659. reloc_mode = LLVMRelocPIC;
  1660. }
  1661. break;
  1662. case RelocMode_Static:
  1663. reloc_mode = LLVMRelocStatic;
  1664. break;
  1665. case RelocMode_PIC:
  1666. reloc_mode = LLVMRelocPIC;
  1667. break;
  1668. case RelocMode_DynamicNoPIC:
  1669. reloc_mode = LLVMRelocDynamicNoPic;
  1670. break;
  1671. }
  1672. for (auto const &entry : gen->modules) {
  1673. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(
  1674. target, target_triple, llvm_cpu,
  1675. llvm_features,
  1676. code_gen_level,
  1677. reloc_mode,
  1678. code_mode);
  1679. lbModule *m = entry.value;
  1680. m->target_machine = target_machine;
  1681. LLVMSetModuleDataLayout(m->mod, LLVMCreateTargetDataLayout(target_machine));
  1682. array_add(&target_machines, target_machine);
  1683. }
  1684. for (auto const &entry : gen->modules) {
  1685. lbModule *m = entry.value;
  1686. if (m->debug_builder) { // Debug Info
  1687. for (auto const &file_entry : info->files) {
  1688. AstFile *f = file_entry.value;
  1689. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  1690. cast(char const *)f->filename.text, f->filename.len,
  1691. cast(char const *)f->directory.text, f->directory.len);
  1692. lb_set_llvm_metadata(m, f, res);
  1693. }
  1694. TEMPORARY_ALLOCATOR_GUARD();
  1695. gbString producer = gb_string_make(temporary_allocator(), "odin");
  1696. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  1697. // #ifdef NIGHTLY
  1698. // producer = gb_string_appendc(producer, "-nightly");
  1699. // #endif
  1700. // #ifdef GIT_SHA
  1701. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  1702. // #endif
  1703. gbString split_name = gb_string_make(temporary_allocator(), "");
  1704. LLVMBool is_optimized = build_context.optimization_level > 0;
  1705. AstFile *init_file = m->info->init_package->files[0];
  1706. if (Entity *entry_point = m->info->entry_point) {
  1707. if (Ast *ident = entry_point->identifier.load()) {
  1708. if (ident->file_id) {
  1709. init_file = ident->file();
  1710. }
  1711. }
  1712. }
  1713. LLVMBool split_debug_inlining = build_context.build_mode == BuildMode_Assembly;
  1714. LLVMBool debug_info_for_profiling = false;
  1715. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  1716. lb_get_llvm_metadata(m, init_file),
  1717. producer, gb_string_length(producer),
  1718. is_optimized, "", 0,
  1719. 1, split_name, gb_string_length(split_name),
  1720. LLVMDWARFEmissionFull,
  1721. 0, split_debug_inlining,
  1722. debug_info_for_profiling,
  1723. "", 0, // sys_root
  1724. "", 0 // SDK
  1725. );
  1726. GB_ASSERT(m->debug_compile_unit != nullptr);
  1727. }
  1728. }
  1729. TIME_SECTION("LLVM Global Variables");
  1730. if (!build_context.disallow_rtti) {
  1731. lbModule *m = default_module;
  1732. { // Add type info data
  1733. isize max_type_info_count = info->minimum_dependency_type_info_set.count+1;
  1734. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  1735. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  1736. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  1737. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1738. LLVMSetLinkage(g, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
  1739. lbValue value = {};
  1740. value.value = g;
  1741. value.type = alloc_type_pointer(t);
  1742. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  1743. lb_add_entity(m, lb_global_type_info_data_entity, value);
  1744. }
  1745. { // Type info member buffer
  1746. // NOTE(bill): Removes need for heap allocation by making it global memory
  1747. isize count = 0;
  1748. for (Type *t : m->info->type_info_types) {
  1749. isize index = lb_type_info_index(m->info, t, false);
  1750. if (index < 0) {
  1751. continue;
  1752. }
  1753. switch (t->kind) {
  1754. case Type_Union:
  1755. count += t->Union.variants.count;
  1756. break;
  1757. case Type_Struct:
  1758. count += t->Struct.fields.count;
  1759. break;
  1760. case Type_Tuple:
  1761. count += t->Tuple.variables.count;
  1762. break;
  1763. }
  1764. }
  1765. if (count > 0) {
  1766. {
  1767. char const *name = LB_TYPE_INFO_TYPES_NAME;
  1768. Type *t = alloc_type_array(t_type_info_ptr, count);
  1769. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1770. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1771. LLVMSetLinkage(g, LLVMInternalLinkage);
  1772. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  1773. }
  1774. {
  1775. char const *name = LB_TYPE_INFO_NAMES_NAME;
  1776. Type *t = alloc_type_array(t_string, count);
  1777. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1778. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1779. LLVMSetLinkage(g, LLVMInternalLinkage);
  1780. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  1781. }
  1782. {
  1783. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  1784. Type *t = alloc_type_array(t_uintptr, count);
  1785. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1786. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1787. LLVMSetLinkage(g, LLVMInternalLinkage);
  1788. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  1789. }
  1790. {
  1791. char const *name = LB_TYPE_INFO_USINGS_NAME;
  1792. Type *t = alloc_type_array(t_bool, count);
  1793. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1794. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1795. LLVMSetLinkage(g, LLVMInternalLinkage);
  1796. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  1797. }
  1798. {
  1799. char const *name = LB_TYPE_INFO_TAGS_NAME;
  1800. Type *t = alloc_type_array(t_string, count);
  1801. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1802. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1803. LLVMSetLinkage(g, LLVMInternalLinkage);
  1804. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  1805. }
  1806. }
  1807. }
  1808. }
  1809. isize global_variable_max_count = 0;
  1810. bool already_has_entry_point = false;
  1811. for (Entity *e : info->entities) {
  1812. String name = e->token.string;
  1813. if (e->kind == Entity_Variable) {
  1814. global_variable_max_count++;
  1815. } else if (e->kind == Entity_Procedure) {
  1816. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  1817. GB_ASSERT(e == info->entry_point);
  1818. }
  1819. if (build_context.command_kind == Command_test &&
  1820. (e->Procedure.is_export || e->Procedure.link_name.len > 0)) {
  1821. String link_name = e->Procedure.link_name;
  1822. if (e->pkg->kind == Package_Runtime) {
  1823. if (link_name == "main" ||
  1824. link_name == "DllMain" ||
  1825. link_name == "WinMain" ||
  1826. link_name == "wWinMain" ||
  1827. link_name == "mainCRTStartup" ||
  1828. link_name == "_start") {
  1829. already_has_entry_point = true;
  1830. }
  1831. }
  1832. }
  1833. }
  1834. }
  1835. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  1836. for (DeclInfo *d : info->variable_init_order) {
  1837. Entity *e = d->entity;
  1838. if ((e->scope->flags & ScopeFlag_File) == 0) {
  1839. continue;
  1840. }
  1841. if (!ptr_set_exists(min_dep_set, e)) {
  1842. continue;
  1843. }
  1844. DeclInfo *decl = decl_info_of_entity(e);
  1845. if (decl == nullptr) {
  1846. continue;
  1847. }
  1848. GB_ASSERT(e->kind == Entity_Variable);
  1849. bool is_foreign = e->Variable.is_foreign;
  1850. bool is_export = e->Variable.is_export;
  1851. lbModule *m = &gen->default_module;
  1852. String name = lb_get_entity_name(m, e);
  1853. lbValue g = {};
  1854. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  1855. g.type = alloc_type_pointer(e->type);
  1856. if (e->Variable.thread_local_model != "") {
  1857. LLVMSetThreadLocal(g.value, true);
  1858. String m = e->Variable.thread_local_model;
  1859. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  1860. if (m == "default") {
  1861. mode = LLVMGeneralDynamicTLSModel;
  1862. } else if (m == "localdynamic") {
  1863. mode = LLVMLocalDynamicTLSModel;
  1864. } else if (m == "initialexec") {
  1865. mode = LLVMInitialExecTLSModel;
  1866. } else if (m == "localexec") {
  1867. mode = LLVMLocalExecTLSModel;
  1868. } else {
  1869. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  1870. }
  1871. LLVMSetThreadLocalMode(g.value, mode);
  1872. }
  1873. if (is_foreign) {
  1874. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1875. LLVMSetDLLStorageClass(g.value, LLVMDLLImportStorageClass);
  1876. LLVMSetExternallyInitialized(g.value, true);
  1877. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  1878. lb_set_wasm_import_attributes(g.value, e, name);
  1879. } else {
  1880. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  1881. }
  1882. if (is_export) {
  1883. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  1884. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  1885. } else if (!is_foreign) {
  1886. LLVMSetLinkage(g.value, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
  1887. }
  1888. lb_set_linkage_from_entity_flags(m, g.value, e->flags);
  1889. if (e->Variable.link_section.len > 0) {
  1890. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  1891. }
  1892. lbGlobalVariable var = {};
  1893. var.var = g;
  1894. var.decl = decl;
  1895. if (decl->init_expr != nullptr) {
  1896. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  1897. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  1898. if (tav.mode != Addressing_Invalid) {
  1899. if (tav.value.kind != ExactValue_Invalid) {
  1900. ExactValue v = tav.value;
  1901. lbValue init = lb_const_value(m, tav.type, v);
  1902. LLVMSetInitializer(g.value, init.value);
  1903. var.is_initialized = true;
  1904. }
  1905. }
  1906. }
  1907. if (!var.is_initialized && is_type_untyped_nil(tav.type)) {
  1908. var.is_initialized = true;
  1909. }
  1910. }
  1911. array_add(&global_variables, var);
  1912. lb_add_entity(m, e, g);
  1913. lb_add_member(m, name, g);
  1914. if (m->debug_builder) {
  1915. String global_name = e->token.string;
  1916. if (global_name.len != 0 && global_name != "_") {
  1917. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  1918. LLVMMetadataRef llvm_scope = llvm_file;
  1919. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  1920. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  1921. LLVMMetadataRef llvm_decl = nullptr;
  1922. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  1923. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  1924. m->debug_builder, llvm_scope,
  1925. cast(char const *)global_name.text, global_name.len,
  1926. "", 0, // linkage
  1927. llvm_file, e->token.pos.line,
  1928. lb_debug_type(m, e->type),
  1929. local_to_unit,
  1930. llvm_expr,
  1931. llvm_decl,
  1932. align_in_bits
  1933. );
  1934. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  1935. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  1936. }
  1937. }
  1938. }
  1939. TIME_SECTION("LLVM Runtime Type Information Creation");
  1940. gen->startup_type_info = lb_create_startup_type_info(default_module);
  1941. gen->objc_names = lb_create_objc_names(default_module);
  1942. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables & @(init))");
  1943. gen->startup_runtime = lb_create_startup_runtime(default_module, gen->startup_type_info, gen->objc_names, global_variables);
  1944. TIME_SECTION("LLVM Runtime Cleanup Creation & @(fini)");
  1945. gen->cleanup_runtime = lb_create_cleanup_runtime(default_module);
  1946. if (build_context.ODIN_DEBUG) {
  1947. for (auto const &entry : builtin_pkg->scope->elements) {
  1948. Entity *e = entry.value;
  1949. add_debug_info_for_global_constant_from_entity(gen, e);
  1950. }
  1951. }
  1952. if (gen->modules.count <= 1) {
  1953. do_threading = false;
  1954. }
  1955. TIME_SECTION("LLVM Global Procedures and Types");
  1956. lb_create_global_procedures_and_types(gen, info, do_threading);
  1957. TIME_SECTION("LLVM Procedure Generation");
  1958. lb_generate_procedures(gen, do_threading);
  1959. if (build_context.command_kind == Command_test && !already_has_entry_point) {
  1960. TIME_SECTION("LLVM main");
  1961. lb_create_main_procedure(default_module, gen->startup_runtime, gen->cleanup_runtime);
  1962. }
  1963. TIME_SECTION("LLVM Procedure Generation (missing)");
  1964. lb_generate_missing_procedures(gen, do_threading);
  1965. if (gen->objc_names) {
  1966. TIME_SECTION("Finalize objc names");
  1967. lb_finalize_objc_names(gen->objc_names);
  1968. }
  1969. if (build_context.ODIN_DEBUG) {
  1970. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  1971. lb_debug_info_complete_types_and_finalize(gen);
  1972. }
  1973. if (do_threading) {
  1974. isize non_empty_module_count = 0;
  1975. for (auto const &entry : gen->modules) {
  1976. lbModule *m = entry.value;
  1977. if (!lb_is_module_empty(m)) {
  1978. non_empty_module_count += 1;
  1979. }
  1980. }
  1981. if (non_empty_module_count <= 1) {
  1982. do_threading = false;
  1983. }
  1984. }
  1985. TIME_SECTION("LLVM Function Pass");
  1986. lb_llvm_function_passes(gen, do_threading && !build_context.ODIN_DEBUG);
  1987. TIME_SECTION("LLVM Module Pass");
  1988. lb_llvm_module_passes(gen, do_threading);
  1989. TIME_SECTION("LLVM Module Verification");
  1990. if (!lb_llvm_module_verification(gen, do_threading)) {
  1991. return false;
  1992. }
  1993. llvm_error = nullptr;
  1994. defer (LLVMDisposeMessage(llvm_error));
  1995. if (build_context.keep_temp_files ||
  1996. build_context.build_mode == BuildMode_LLVM_IR) {
  1997. TIME_SECTION("LLVM Print Module to File");
  1998. for (auto const &entry : gen->modules) {
  1999. lbModule *m = entry.value;
  2000. if (lb_is_module_empty(m)) {
  2001. continue;
  2002. }
  2003. String filepath_ll = lb_filepath_ll_for_module(m);
  2004. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  2005. gb_printf_err("LLVM Error: %s\n", llvm_error);
  2006. gb_exit(1);
  2007. return false;
  2008. }
  2009. array_add(&gen->output_temp_paths, filepath_ll);
  2010. }
  2011. if (build_context.build_mode == BuildMode_LLVM_IR) {
  2012. return true;
  2013. }
  2014. }
  2015. TIME_SECTION("LLVM Add Foreign Library Paths");
  2016. lb_add_foreign_library_paths(gen);
  2017. TIME_SECTION("LLVM Object Generation");
  2018. if (build_context.ignore_llvm_build) {
  2019. gb_printf_err("LLVM object generation has been ignored!\n");
  2020. return false;
  2021. }
  2022. if (!lb_llvm_object_generation(gen, do_threading)) {
  2023. return false;
  2024. }
  2025. gb_sort_array(gen->foreign_libraries.data, gen->foreign_libraries.count, foreign_library_cmp);
  2026. return true;
  2027. }