llvm_backend.cpp 84 KB

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