llvm_backend.cpp 77 KB

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