llvm_backend.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951
  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. 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_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. 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. 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. 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. 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. lbValue lb_get_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[16] = {};
  132. isize n = gb_snprintf(buf, 16, "__$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. LLVMValueRef x = LLVMGetParam(p->value, 0);
  139. LLVMValueRef y = LLVMGetParam(p->value, 1);
  140. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  141. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  142. lbValue lhs = {x, pt};
  143. lbValue rhs = {y, pt};
  144. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  145. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  146. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  147. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  148. lb_start_block(p, block_same_ptr);
  149. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  150. lb_start_block(p, block_diff_ptr);
  151. if (type->kind == Type_Struct) {
  152. type_set_offsets(type);
  153. lbBlock *block_false = lb_create_block(p, "bfalse");
  154. lbValue res = lb_const_bool(m, t_bool, true);
  155. for_array(i, type->Struct.fields) {
  156. lbBlock *next_block = lb_create_block(p, "btrue");
  157. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  158. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  159. lbValue left = lb_emit_load(p, pleft);
  160. lbValue right = lb_emit_load(p, pright);
  161. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  162. lb_emit_if(p, ok, next_block, block_false);
  163. lb_emit_jump(p, next_block);
  164. lb_start_block(p, next_block);
  165. }
  166. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  167. lb_start_block(p, block_false);
  168. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  169. } else if (type->kind == Type_Union) {
  170. if (is_type_union_maybe_pointer(type)) {
  171. Type *v = type->Union.variants[0];
  172. Type *pv = alloc_type_pointer(v);
  173. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  174. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  175. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  176. ok = lb_emit_conv(p, ok, t_bool);
  177. LLVMBuildRet(p->builder, ok.value);
  178. } else {
  179. lbBlock *block_false = lb_create_block(p, "bfalse");
  180. lbBlock *block_switch = lb_create_block(p, "bswitch");
  181. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  182. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  183. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  184. lb_emit_if(p, tag_eq, block_switch, block_false);
  185. lb_start_block(p, block_switch);
  186. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, cast(unsigned)type->Union.variants.count);
  187. for_array(i, type->Union.variants) {
  188. lbBlock *case_block = lb_create_block(p, "bcase");
  189. lb_start_block(p, case_block);
  190. Type *v = type->Union.variants[i];
  191. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  192. Type *vp = alloc_type_pointer(v);
  193. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  194. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  195. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  196. ok = lb_emit_conv(p, ok, t_bool);
  197. LLVMBuildRet(p->builder, ok.value);
  198. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  199. }
  200. lb_start_block(p, block_false);
  201. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  202. }
  203. } else {
  204. lbValue left = lb_emit_load(p, lhs);
  205. lbValue right = lb_emit_load(p, rhs);
  206. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  207. ok = lb_emit_conv(p, ok, t_bool);
  208. LLVMBuildRet(p->builder, ok.value);
  209. }
  210. lb_end_procedure_body(p);
  211. compare_proc = p;
  212. return {compare_proc->value, compare_proc->type};
  213. }
  214. lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  215. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  216. i64 sz = type_size_of(type);
  217. if (1 <= sz && sz <= 16) {
  218. char name[20] = {};
  219. gb_snprintf(name, 20, "default_hasher%d", cast(i32)sz);
  220. auto args = array_make<lbValue>(permanent_allocator(), 2);
  221. args[0] = data;
  222. args[1] = seed;
  223. return lb_emit_runtime_call(p, name, args);
  224. }
  225. auto args = array_make<lbValue>(permanent_allocator(), 3);
  226. args[0] = data;
  227. args[1] = seed;
  228. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  229. return lb_emit_runtime_call(p, "default_hasher_n", args);
  230. }
  231. lbValue lb_get_hasher_proc_for_type(lbModule *m, Type *type) {
  232. type = core_type(type);
  233. GB_ASSERT(is_type_valid_for_keys(type));
  234. Type *pt = alloc_type_pointer(type);
  235. lbProcedure **found = map_get(&m->hasher_procs, type);
  236. if (found) {
  237. GB_ASSERT(*found != nullptr);
  238. return {(*found)->value, (*found)->type};
  239. }
  240. static u32 proc_index = 0;
  241. char buf[16] = {};
  242. isize n = gb_snprintf(buf, 16, "__$hasher%u", ++proc_index);
  243. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  244. String proc_name = make_string_c(str);
  245. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  246. map_set(&m->hasher_procs, type, p);
  247. lb_begin_procedure_body(p);
  248. defer (lb_end_procedure_body(p));
  249. LLVMValueRef x = LLVMGetParam(p->value, 0);
  250. LLVMValueRef y = LLVMGetParam(p->value, 1);
  251. lbValue data = {x, t_rawptr};
  252. lbValue seed = {y, t_uintptr};
  253. LLVMAttributeRef nonnull_attr = lb_create_enum_attribute(m->ctx, "nonnull");
  254. LLVMAddAttributeAtIndex(p->value, 1+0, nonnull_attr);
  255. if (is_type_simple_compare(type)) {
  256. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  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_get_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_get_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. LLVMBuildRet(p->builder, res.value);
  284. }
  285. lbBlock *end_block = lb_create_block(p, "bend");
  286. data = lb_emit_conv(p, data, pt);
  287. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  288. lbValue tag = lb_emit_load(p, tag_ptr);
  289. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  290. for_array(i, type->Union.variants) {
  291. lbBlock *case_block = lb_create_block(p, "bcase");
  292. lb_start_block(p, case_block);
  293. Type *v = type->Union.variants[i];
  294. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  295. lbValue variant_hasher = lb_get_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_get_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_get_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. LLVMBuildRet(p->builder, res.value);
  340. } else if (is_type_string(type)) {
  341. auto args = array_make<lbValue>(permanent_allocator(), 2);
  342. args[0] = data;
  343. args[1] = seed;
  344. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  345. LLVMBuildRet(p->builder, res.value);
  346. } else {
  347. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  348. }
  349. return {p->value, p->type};
  350. }
  351. lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  352. lbProcedure **found = map_get(&m->gen->anonymous_proc_lits, expr);
  353. if (found) {
  354. return lb_find_procedure_value_from_entity(m, (*found)->entity);
  355. }
  356. ast_node(pl, ProcLit, expr);
  357. // NOTE(bill): Generate a new name
  358. // parent$count
  359. isize name_len = prefix_name.len + 1 + 8 + 1;
  360. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  361. i32 name_id = cast(i32)m->gen->anonymous_proc_lits.entries.count;
  362. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id);
  363. String name = make_string((u8 *)name_text, name_len-1);
  364. Type *type = type_of_expr(expr);
  365. Token token = {};
  366. token.pos = ast_token(expr).pos;
  367. token.kind = Token_Ident;
  368. token.string = name;
  369. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  370. e->file = expr->file();
  371. e->decl_info = pl->decl;
  372. e->code_gen_module = m;
  373. e->flags |= EntityFlag_ProcBodyChecked;
  374. lbProcedure *p = lb_create_procedure(m, e);
  375. lbValue value = {};
  376. value.value = p->value;
  377. value.type = p->type;
  378. array_add(&m->procedures_to_generate, p);
  379. if (parent != nullptr) {
  380. array_add(&parent->children, p);
  381. } else {
  382. string_map_set(&m->members, name, value);
  383. }
  384. map_set(&m->gen->anonymous_proc_lits, expr, p);
  385. return value;
  386. }
  387. lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) {
  388. GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type));
  389. lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later
  390. map_type = base_type(map_type);
  391. GB_ASSERT(map_type->kind == Type_Map);
  392. Type *key_type = map_type->Map.key;
  393. Type *val_type = map_type->Map.value;
  394. gb_unused(val_type);
  395. GB_ASSERT(map_type->Map.entry_type->kind == Type_Struct);
  396. map_type->Map.entry_type->cached_size = -1;
  397. map_type->Map.entry_type->Struct.are_offsets_set = false;
  398. i64 entry_size = type_size_of (map_type->Map.entry_type);
  399. i64 entry_align = type_align_of (map_type->Map.entry_type);
  400. i64 key_offset = type_offset_of(map_type->Map.entry_type, 2);
  401. i64 key_size = type_size_of (map_type->Map.key);
  402. i64 value_offset = type_offset_of(map_type->Map.entry_type, 3);
  403. i64 value_size = type_size_of (map_type->Map.value);
  404. Type *map_header_base = base_type(t_map_header);
  405. GB_ASSERT(map_header_base->Struct.fields.count == 8);
  406. Type *raw_map_ptr_type = map_header_base->Struct.fields[0]->type;
  407. LLVMValueRef const_values[8] = {};
  408. const_values[0] = LLVMConstNull(lb_type(p->module, raw_map_ptr_type));
  409. const_values[1] = lb_get_equal_proc_for_type(p->module, key_type) .value;
  410. const_values[2] = lb_const_int(p->module, t_int, entry_size) .value;
  411. const_values[3] = lb_const_int(p->module, t_int, entry_align) .value;
  412. const_values[4] = lb_const_int(p->module, t_uintptr, key_offset) .value;
  413. const_values[5] = lb_const_int(p->module, t_int, key_size) .value;
  414. const_values[6] = lb_const_int(p->module, t_uintptr, value_offset).value;
  415. const_values[7] = lb_const_int(p->module, t_int, value_size) .value;
  416. LLVMValueRef const_value = llvm_const_named_struct(p->module, t_map_header, const_values, gb_count_of(const_values));
  417. LLVMBuildStore(p->builder, const_value, h.addr.value);
  418. // NOTE(bill): Removes unnecessary allocation if split gep
  419. lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0);
  420. lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type));
  421. lb_emit_store(p, gep0, m);
  422. return lb_addr_load(p, h);
  423. }
  424. lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  425. if (true) {
  426. return {};
  427. }
  428. lbValue hashed_key = {};
  429. #if 0
  430. if (lb_is_const(key)) {
  431. u64 hash = 0xcbf29ce484222325;
  432. if (is_type_cstring(key_type)) {
  433. size_t length = 0;
  434. char const *text = LLVMGetAsString(key.value, &length);
  435. hash = fnv64a(text, cast(isize)length);
  436. } else if (is_type_string(key_type)) {
  437. unsigned data_indices[] = {0};
  438. unsigned len_indices[] = {1};
  439. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  440. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  441. i64 length = LLVMConstIntGetSExtValue(len);
  442. char const *text = nullptr;
  443. if (false && length != 0) {
  444. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  445. return {};
  446. }
  447. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  448. size_t ulength = 0;
  449. text = LLVMGetAsString(data, &ulength);
  450. gb_printf_err("%lld %llu %s\n", length, ulength, text);
  451. length = gb_min(length, cast(i64)ulength);
  452. }
  453. hash = fnv64a(text, cast(isize)length);
  454. } else {
  455. return {};
  456. }
  457. // TODO(bill): other const hash types
  458. if (build_context.word_size == 4) {
  459. hash &= 0xffffffffull;
  460. }
  461. hashed_key = lb_const_int(m, t_uintptr, hash);
  462. }
  463. #endif
  464. return hashed_key;
  465. }
  466. lbValue lb_gen_map_hash(lbProcedure *p, lbValue key, Type *key_type) {
  467. lbAddr v = lb_add_local_generated(p, t_map_hash, true);
  468. lbValue vp = lb_addr_get_ptr(p, v);
  469. key = lb_emit_conv(p, key, key_type);
  470. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  471. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  472. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  473. if (hashed_key.value == nullptr) {
  474. lbValue hasher = lb_get_hasher_proc_for_type(p->module, key_type);
  475. auto args = array_make<lbValue>(permanent_allocator(), 2);
  476. args[0] = key_ptr;
  477. args[1] = lb_const_int(p->module, t_uintptr, 0);
  478. hashed_key = lb_emit_call(p, hasher, args);
  479. }
  480. lb_emit_store(p, lb_emit_struct_ep(p, vp, 0), hashed_key);
  481. lb_emit_store(p, lb_emit_struct_ep(p, vp, 1), key_ptr);
  482. return lb_addr_load(p, v);
  483. }
  484. void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type,
  485. lbValue map_key, lbValue map_value, Ast *node) {
  486. map_type = base_type(map_type);
  487. GB_ASSERT(map_type->kind == Type_Map);
  488. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  489. lbValue key = lb_gen_map_hash(p, map_key, map_type->Map.key);
  490. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  491. lbAddr value_addr = lb_add_local_generated(p, v.type, false);
  492. lb_addr_store(p, value_addr, v);
  493. auto args = array_make<lbValue>(permanent_allocator(), 4);
  494. args[0] = h;
  495. args[1] = key;
  496. args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr);
  497. args[3] = lb_emit_source_code_location(p, node);
  498. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  499. }
  500. struct lbGlobalVariable {
  501. lbValue var;
  502. lbValue init;
  503. DeclInfo *decl;
  504. bool is_initialized;
  505. };
  506. lbProcedure *lb_create_startup_type_info(lbModule *m) {
  507. if (build_context.disallow_rtti) {
  508. return nullptr;
  509. }
  510. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  511. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  512. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  513. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  514. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  515. p->is_startup = true;
  516. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  517. lb_begin_procedure_body(p);
  518. lb_setup_type_info_data(p);
  519. lb_end_procedure_body(p);
  520. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  521. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  522. LLVMDumpValue(p->value);
  523. gb_printf_err("\n\n\n\n");
  524. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  525. }
  526. lb_run_function_pass_manager(default_function_pass_manager, p);
  527. return p;
  528. }
  529. lbProcedure *lb_create_objc_names(lbModule *main_module) {
  530. if (build_context.metrics.os != TargetOs_darwin) {
  531. return nullptr;
  532. }
  533. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  534. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit("__$init_objc_names"), proc_type);
  535. p->is_startup = true;
  536. return p;
  537. }
  538. void lb_finalize_objc_names(lbProcedure *p) {
  539. if (p == nullptr) {
  540. return;
  541. }
  542. lbModule *m = p->module;
  543. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  544. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  545. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  546. auto args = array_make<lbValue>(permanent_allocator(), 1);
  547. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  548. lb_begin_procedure_body(p);
  549. for_array(i, m->objc_classes.entries) {
  550. auto const &entry = m->objc_classes.entries[i];
  551. String name = entry.key.string;
  552. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  553. lbValue ptr = lb_emit_runtime_call(p, "objc_lookUpClass", args);
  554. lb_addr_store(p, entry.value, ptr);
  555. }
  556. for_array(i, m->objc_selectors.entries) {
  557. auto const &entry = m->objc_selectors.entries[i];
  558. String name = entry.key.string;
  559. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  560. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  561. lb_addr_store(p, entry.value, ptr);
  562. }
  563. lb_end_procedure_body(p);
  564. lb_run_function_pass_manager(default_function_pass_manager, p);
  565. }
  566. lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *startup_type_info, lbProcedure *objc_names, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  567. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(main_module->mod);
  568. lb_populate_function_pass_manager(main_module, default_function_pass_manager, false, build_context.optimization_level);
  569. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  570. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  571. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  572. p->is_startup = true;
  573. lb_begin_procedure_body(p);
  574. if (startup_type_info) {
  575. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(main_module, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  576. }
  577. if (objc_names) {
  578. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(main_module, objc_names->type)), objc_names->value, nullptr, 0, "");
  579. }
  580. for_array(i, global_variables) {
  581. auto *var = &global_variables[i];
  582. if (var->is_initialized) {
  583. continue;
  584. }
  585. lbModule *entity_module = main_module;
  586. Entity *e = var->decl->entity;
  587. GB_ASSERT(e->kind == Entity_Variable);
  588. e->code_gen_module = entity_module;
  589. Ast *init_expr = var->decl->init_expr;
  590. if (init_expr != nullptr) {
  591. lbValue init = lb_build_expr(p, init_expr);
  592. if (init.value == nullptr) {
  593. LLVMTypeRef global_type = LLVMGetElementType(LLVMTypeOf(var->var.value));
  594. if (is_type_untyped_undef(init.type)) {
  595. // LLVMSetInitializer(var->var.value, LLVMGetUndef(global_type));
  596. LLVMSetInitializer(var->var.value, LLVMConstNull(global_type));
  597. var->is_initialized = true;
  598. continue;
  599. } else if (is_type_untyped_nil(init.type)) {
  600. LLVMSetInitializer(var->var.value, LLVMConstNull(global_type));
  601. var->is_initialized = true;
  602. continue;
  603. }
  604. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  605. }
  606. if (is_type_any(e->type) || is_type_union(e->type)) {
  607. var->init = init;
  608. } else if (lb_is_const_or_global(init)) {
  609. if (!var->is_initialized) {
  610. LLVMSetInitializer(var->var.value, init.value);
  611. var->is_initialized = true;
  612. continue;
  613. }
  614. } else {
  615. var->init = init;
  616. }
  617. }
  618. if (var->init.value != nullptr) {
  619. GB_ASSERT(!var->is_initialized);
  620. Type *t = type_deref(var->var.type);
  621. if (is_type_any(t)) {
  622. // NOTE(bill): Edge case for 'any' type
  623. Type *var_type = default_type(var->init.type);
  624. lbAddr g = lb_add_global_generated(main_module, var_type, var->init);
  625. lb_addr_store(p, g, var->init);
  626. lbValue gp = lb_addr_get_ptr(p, g);
  627. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  628. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  629. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  630. lb_emit_store(p, ti, lb_type_info(main_module, var_type));
  631. } else {
  632. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  633. LLVMTypeRef vt = LLVMGetElementType(pvt);
  634. lbValue src0 = lb_emit_conv(p, var->init, t);
  635. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  636. LLVMValueRef dst = var->var.value;
  637. LLVMBuildStore(p->builder, src, dst);
  638. }
  639. var->is_initialized = true;
  640. }
  641. }
  642. CheckerInfo *info = main_module->gen->info;
  643. for (Entity *e : info->init_procedures) {
  644. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  645. lb_emit_call(p, value, {}, ProcInlining_none, false);
  646. }
  647. lb_end_procedure_body(p);
  648. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  649. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  650. LLVMDumpValue(p->value);
  651. gb_printf_err("\n\n\n\n");
  652. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  653. }
  654. lb_run_function_pass_manager(default_function_pass_manager, p);
  655. return p;
  656. }
  657. lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime) {
  658. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  659. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  660. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  661. Type *params = alloc_type_tuple();
  662. Type *results = alloc_type_tuple();
  663. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  664. bool call_cleanup = true;
  665. bool has_args = false;
  666. bool is_dll_main = false;
  667. String name = str_lit("main");
  668. if (build_context.metrics.os == TargetOs_windows && build_context.build_mode == BuildMode_DynamicLibrary) {
  669. is_dll_main = true;
  670. name = str_lit("DllMain");
  671. slice_init(&params->Tuple.variables, permanent_allocator(), 3);
  672. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("hinstDLL"), t_rawptr, false, true);
  673. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("fdwReason"), t_u32, false, true);
  674. params->Tuple.variables[2] = alloc_entity_param(nullptr, make_token_ident("lpReserved"), t_rawptr, false, true);
  675. call_cleanup = false;
  676. } else if (build_context.metrics.os == TargetOs_windows && (build_context.metrics.arch == TargetArch_i386 || build_context.no_crt)) {
  677. name = str_lit("mainCRTStartup");
  678. } else if (is_arch_wasm()) {
  679. name = str_lit("_start");
  680. call_cleanup = false;
  681. } else {
  682. has_args = true;
  683. slice_init(&params->Tuple.variables, permanent_allocator(), 2);
  684. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  685. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  686. }
  687. slice_init(&results->Tuple.variables, permanent_allocator(), 1);
  688. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  689. Type *proc_type = alloc_type_proc(nullptr,
  690. params, params->Tuple.variables.count,
  691. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  692. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  693. p->is_startup = true;
  694. lb_begin_procedure_body(p);
  695. if (has_args) { // initialize `runtime.args__`
  696. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  697. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  698. LLVMSetValueName2(argc.value, "argc", 4);
  699. LLVMSetValueName2(argv.value, "argv", 4);
  700. argc = lb_emit_conv(p, argc, t_int);
  701. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  702. lb_fill_slice(p, args, argv, argc);
  703. }
  704. lbValue startup_runtime_value = {startup_runtime->value, startup_runtime->type};
  705. lb_emit_call(p, startup_runtime_value, {}, ProcInlining_none, false);
  706. if (build_context.command_kind == Command_test) {
  707. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  708. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  709. Type *slice_type = alloc_type_slice(t_Internal_Test);
  710. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  711. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  712. LLVMValueRef indices[2] = {};
  713. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  714. for_array(i, m->info->testing_procedures) {
  715. Entity *testing_proc = m->info->testing_procedures[i];
  716. String name = testing_proc->token.string;
  717. String pkg_name = {};
  718. if (testing_proc->pkg != nullptr) {
  719. pkg_name = testing_proc->pkg->name;
  720. }
  721. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  722. lbValue v_name = lb_find_or_add_entity_string(m, name);
  723. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  724. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  725. LLVMValueRef vals[3] = {};
  726. vals[0] = v_pkg.value;
  727. vals[1] = v_name.value;
  728. vals[2] = v_proc.value;
  729. GB_ASSERT(LLVMIsConstant(vals[0]));
  730. GB_ASSERT(LLVMIsConstant(vals[1]));
  731. GB_ASSERT(LLVMIsConstant(vals[2]));
  732. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  733. LLVMValueRef src = llvm_const_named_struct(m, t_Internal_Test, vals, gb_count_of(vals));
  734. LLVMBuildStore(p->builder, src, dst);
  735. }
  736. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  737. lb_fill_slice(p, all_tests_slice,
  738. lb_array_elem(p, all_tests_array),
  739. lb_const_int(m, t_int, m->info->testing_procedures.count));
  740. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  741. auto args = array_make<lbValue>(heap_allocator(), 1);
  742. args[0] = lb_addr_load(p, all_tests_slice);
  743. lb_emit_call(p, runner, args);
  744. } else {
  745. if (m->info->entry_point != nullptr) {
  746. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  747. lb_emit_call(p, entry_point, {}, ProcInlining_no_inline);
  748. }
  749. }
  750. if (call_cleanup) {
  751. lbValue cleanup_runtime_value = lb_find_runtime_value(m, str_lit("_cleanup_runtime"));
  752. lb_emit_call(p, cleanup_runtime_value, {}, ProcInlining_none, false);
  753. }
  754. if (is_dll_main) {
  755. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 1, false));
  756. } else {
  757. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  758. }
  759. lb_end_procedure_body(p);
  760. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  761. if (is_arch_wasm()) {
  762. lb_set_wasm_export_attributes(p->value, p->name);
  763. }
  764. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  765. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  766. LLVMDumpValue(p->value);
  767. gb_printf_err("\n\n\n\n");
  768. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  769. }
  770. lb_run_function_pass_manager(default_function_pass_manager, p);
  771. return p;
  772. }
  773. String lb_filepath_ll_for_module(lbModule *m) {
  774. String path = concatenate3_strings(permanent_allocator(),
  775. build_context.build_paths[BuildPath_Output].basename,
  776. STR_LIT("/"),
  777. build_context.build_paths[BuildPath_Output].name
  778. );
  779. if (m->pkg) {
  780. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  781. } else if (USE_SEPARATE_MODULES) {
  782. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  783. }
  784. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  785. return path;
  786. }
  787. String lb_filepath_obj_for_module(lbModule *m) {
  788. String path = concatenate3_strings(permanent_allocator(),
  789. build_context.build_paths[BuildPath_Output].basename,
  790. STR_LIT("/"),
  791. build_context.build_paths[BuildPath_Output].name
  792. );
  793. if (m->pkg) {
  794. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  795. }
  796. String ext = {};
  797. if (build_context.build_mode == BuildMode_Assembly) {
  798. ext = STR_LIT(".S");
  799. } else {
  800. if (is_arch_wasm()) {
  801. ext = STR_LIT(".wasm.o");
  802. } else {
  803. switch (build_context.metrics.os) {
  804. case TargetOs_windows:
  805. ext = STR_LIT(".obj");
  806. break;
  807. default:
  808. case TargetOs_darwin:
  809. case TargetOs_linux:
  810. case TargetOs_essence:
  811. ext = STR_LIT(".o");
  812. break;
  813. case TargetOs_freestanding:
  814. switch (build_context.metrics.abi) {
  815. default:
  816. case TargetABI_Default:
  817. case TargetABI_SysV:
  818. ext = STR_LIT(".o");
  819. break;
  820. case TargetABI_Win64:
  821. ext = STR_LIT(".obj");
  822. break;
  823. }
  824. break;
  825. }
  826. }
  827. }
  828. return concatenate_strings(permanent_allocator(), path, ext);
  829. }
  830. bool lb_is_module_empty(lbModule *m) {
  831. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  832. LLVMGetFirstGlobal(m->mod) == nullptr) {
  833. return true;
  834. }
  835. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  836. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  837. return false;
  838. }
  839. }
  840. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  841. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  842. continue;
  843. }
  844. if (!LLVMIsExternallyInitialized(g)) {
  845. return false;
  846. }
  847. }
  848. return true;
  849. }
  850. struct lbLLVMEmitWorker {
  851. LLVMTargetMachineRef target_machine;
  852. LLVMCodeGenFileType code_gen_file_type;
  853. String filepath_obj;
  854. lbModule *m;
  855. };
  856. WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  857. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  858. char *llvm_error = nullptr;
  859. auto wd = cast(lbLLVMEmitWorker *)data;
  860. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  861. gb_printf_err("LLVM Error: %s\n", llvm_error);
  862. gb_exit(1);
  863. }
  864. return 0;
  865. }
  866. WORKER_TASK_PROC(lb_llvm_function_pass_worker_proc) {
  867. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  868. auto m = cast(lbModule *)data;
  869. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  870. LLVMPassManagerRef function_pass_manager_minimal = LLVMCreateFunctionPassManagerForModule(m->mod);
  871. LLVMPassManagerRef function_pass_manager_size = LLVMCreateFunctionPassManagerForModule(m->mod);
  872. LLVMPassManagerRef function_pass_manager_speed = LLVMCreateFunctionPassManagerForModule(m->mod);
  873. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  874. LLVMInitializeFunctionPassManager(function_pass_manager_minimal);
  875. LLVMInitializeFunctionPassManager(function_pass_manager_size);
  876. LLVMInitializeFunctionPassManager(function_pass_manager_speed);
  877. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  878. lb_populate_function_pass_manager_specific(m, function_pass_manager_minimal, 0);
  879. lb_populate_function_pass_manager_specific(m, function_pass_manager_size, 1);
  880. lb_populate_function_pass_manager_specific(m, function_pass_manager_speed, 2);
  881. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  882. LLVMFinalizeFunctionPassManager(function_pass_manager_minimal);
  883. LLVMFinalizeFunctionPassManager(function_pass_manager_size);
  884. LLVMFinalizeFunctionPassManager(function_pass_manager_speed);
  885. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(m->mod);
  886. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  887. lb_populate_function_pass_manager(m, default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  888. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  889. for_array(i, m->procedures_to_generate) {
  890. lbProcedure *p = m->procedures_to_generate[i];
  891. if (p->body != nullptr) { // Build Procedure
  892. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  893. lb_run_function_pass_manager(default_function_pass_manager_without_memcpy, p);
  894. } else {
  895. if (p->entity && p->entity->kind == Entity_Procedure) {
  896. switch (p->entity->Procedure.optimization_mode) {
  897. case ProcedureOptimizationMode_None:
  898. case ProcedureOptimizationMode_Minimal:
  899. lb_run_function_pass_manager(function_pass_manager_minimal, p);
  900. break;
  901. case ProcedureOptimizationMode_Size:
  902. lb_run_function_pass_manager(function_pass_manager_size, p);
  903. break;
  904. case ProcedureOptimizationMode_Speed:
  905. lb_run_function_pass_manager(function_pass_manager_speed, p);
  906. break;
  907. default:
  908. lb_run_function_pass_manager(default_function_pass_manager, p);
  909. break;
  910. }
  911. } else {
  912. lb_run_function_pass_manager(default_function_pass_manager, p);
  913. }
  914. }
  915. }
  916. }
  917. for_array(i, m->equal_procs.entries) {
  918. lbProcedure *p = m->equal_procs.entries[i].value;
  919. lb_run_function_pass_manager(default_function_pass_manager, p);
  920. }
  921. for_array(i, m->hasher_procs.entries) {
  922. lbProcedure *p = m->hasher_procs.entries[i].value;
  923. lb_run_function_pass_manager(default_function_pass_manager, p);
  924. }
  925. return 0;
  926. }
  927. struct lbLLVMModulePassWorkerData {
  928. lbModule *m;
  929. LLVMTargetMachineRef target_machine;
  930. };
  931. WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  932. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  933. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  934. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  935. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  936. return 0;
  937. }
  938. void lb_generate_procedure(lbModule *m, lbProcedure *p) {
  939. if (p->is_done) {
  940. return;
  941. }
  942. if (p->body != nullptr) { // Build Procedure
  943. m->curr_procedure = p;
  944. lb_begin_procedure_body(p);
  945. lb_build_stmt(p, p->body);
  946. lb_end_procedure_body(p);
  947. p->is_done = true;
  948. m->curr_procedure = nullptr;
  949. }
  950. lb_end_procedure(p);
  951. // Add Flags
  952. if (p->body != nullptr) {
  953. if (p->name == "memcpy" || p->name == "memmove" ||
  954. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  955. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  956. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  957. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  958. }
  959. }
  960. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  961. char *llvm_error = nullptr;
  962. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  963. LLVMDumpValue(p->value);
  964. gb_printf_err("\n\n\n\n");
  965. String filepath_ll = lb_filepath_ll_for_module(m);
  966. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  967. gb_printf_err("LLVM Error: %s\n", llvm_error);
  968. }
  969. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  970. gb_exit(1);
  971. }
  972. }
  973. void lb_generate_code(lbGenerator *gen) {
  974. TIME_SECTION("LLVM Initializtion");
  975. isize thread_count = gb_max(build_context.thread_count, 1);
  976. isize worker_count = thread_count-1;
  977. LLVMBool do_threading = (LLVMIsMultithreaded() && USE_SEPARATE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  978. lbModule *default_module = &gen->default_module;
  979. CheckerInfo *info = gen->info;
  980. auto *min_dep_set = &info->minimum_dependency_set;
  981. switch (build_context.metrics.arch) {
  982. case TargetArch_amd64:
  983. case TargetArch_i386:
  984. LLVMInitializeX86TargetInfo();
  985. LLVMInitializeX86Target();
  986. LLVMInitializeX86TargetMC();
  987. LLVMInitializeX86AsmPrinter();
  988. LLVMInitializeX86AsmParser();
  989. LLVMInitializeX86Disassembler();
  990. break;
  991. case TargetArch_arm64:
  992. LLVMInitializeAArch64TargetInfo();
  993. LLVMInitializeAArch64Target();
  994. LLVMInitializeAArch64TargetMC();
  995. LLVMInitializeAArch64AsmPrinter();
  996. LLVMInitializeAArch64AsmParser();
  997. LLVMInitializeAArch64Disassembler();
  998. break;
  999. case TargetArch_wasm32:
  1000. case TargetArch_wasm64:
  1001. LLVMInitializeWebAssemblyTargetInfo();
  1002. LLVMInitializeWebAssemblyTarget();
  1003. LLVMInitializeWebAssemblyTargetMC();
  1004. LLVMInitializeWebAssemblyAsmPrinter();
  1005. LLVMInitializeWebAssemblyAsmParser();
  1006. LLVMInitializeWebAssemblyDisassembler();
  1007. break;
  1008. default:
  1009. LLVMInitializeAllTargetInfos();
  1010. LLVMInitializeAllTargets();
  1011. LLVMInitializeAllTargetMCs();
  1012. LLVMInitializeAllAsmPrinters();
  1013. LLVMInitializeAllAsmParsers();
  1014. LLVMInitializeAllDisassemblers();
  1015. break;
  1016. }
  1017. if (build_context.microarch == "native") {
  1018. LLVMInitializeNativeTarget();
  1019. }
  1020. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  1021. for_array(i, gen->modules.entries) {
  1022. LLVMSetTarget(gen->modules.entries[i].value->mod, target_triple);
  1023. }
  1024. LLVMTargetRef target = {};
  1025. char *llvm_error = nullptr;
  1026. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  1027. GB_ASSERT(target != nullptr);
  1028. TIME_SECTION("LLVM Create Target Machine");
  1029. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  1030. if (is_arch_wasm()) {
  1031. code_mode = LLVMCodeModelJITDefault;
  1032. } else if (build_context.metrics.os == TargetOs_freestanding) {
  1033. code_mode = LLVMCodeModelKernel;
  1034. }
  1035. char const *host_cpu_name = LLVMGetHostCPUName();
  1036. char const *llvm_cpu = "generic";
  1037. char const *llvm_features = "";
  1038. if (build_context.microarch.len != 0) {
  1039. if (build_context.microarch == "native") {
  1040. llvm_cpu = host_cpu_name;
  1041. } else {
  1042. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  1043. }
  1044. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  1045. llvm_features = LLVMGetHostCPUFeatures();
  1046. }
  1047. } else if (build_context.metrics.arch == TargetArch_amd64) {
  1048. // NOTE(bill): x86-64-v2 is more than enough for everyone
  1049. //
  1050. // x86-64: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
  1051. // x86-64-v2: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
  1052. // x86-64-v3: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
  1053. // x86-64-v4: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
  1054. if (ODIN_LLVM_MINIMUM_VERSION_12) {
  1055. if (build_context.metrics.os == TargetOs_freestanding) {
  1056. llvm_cpu = "x86-64";
  1057. } else {
  1058. llvm_cpu = "x86-64-v2";
  1059. }
  1060. }
  1061. }
  1062. if (build_context.target_features_set.entries.count != 0) {
  1063. llvm_features = target_features_set_to_cstring(permanent_allocator(), false);
  1064. }
  1065. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  1066. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  1067. switch (build_context.optimization_level) {
  1068. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  1069. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  1070. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  1071. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  1072. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  1073. }
  1074. // NOTE(bill): Target Machine Creation
  1075. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  1076. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), gen->modules.entries.count);
  1077. // NOTE(dweiler): Dynamic libraries require position-independent code.
  1078. LLVMRelocMode reloc_mode = LLVMRelocDefault;
  1079. if (build_context.build_mode == BuildMode_DynamicLibrary) {
  1080. reloc_mode = LLVMRelocPIC;
  1081. }
  1082. switch (build_context.reloc_mode) {
  1083. case RelocMode_Default:
  1084. if (build_context.metrics.os == TargetOs_openbsd) {
  1085. // Always use PIC for OpenBSD: it defaults to PIE
  1086. reloc_mode = LLVMRelocPIC;
  1087. }
  1088. break;
  1089. case RelocMode_Static:
  1090. reloc_mode = LLVMRelocStatic;
  1091. break;
  1092. case RelocMode_PIC:
  1093. reloc_mode = LLVMRelocPIC;
  1094. break;
  1095. case RelocMode_DynamicNoPIC:
  1096. reloc_mode = LLVMRelocDynamicNoPic;
  1097. break;
  1098. }
  1099. for_array(i, gen->modules.entries) {
  1100. target_machines[i] = LLVMCreateTargetMachine(
  1101. target, target_triple, llvm_cpu,
  1102. llvm_features,
  1103. code_gen_level,
  1104. reloc_mode,
  1105. code_mode);
  1106. LLVMSetModuleDataLayout(gen->modules.entries[i].value->mod, LLVMCreateTargetDataLayout(target_machines[i]));
  1107. }
  1108. for_array(i, gen->modules.entries) {
  1109. lbModule *m = gen->modules.entries[i].value;
  1110. if (m->debug_builder) { // Debug Info
  1111. for_array(i, info->files.entries) {
  1112. AstFile *f = info->files.entries[i].value;
  1113. String fullpath = f->fullpath;
  1114. String filename = remove_directory_from_path(fullpath);
  1115. String directory = directory_from_path(fullpath);
  1116. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  1117. cast(char const *)filename.text, filename.len,
  1118. cast(char const *)directory.text, directory.len);
  1119. lb_set_llvm_metadata(m, f, res);
  1120. }
  1121. gbString producer = gb_string_make(heap_allocator(), "odin");
  1122. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  1123. // #ifdef NIGHTLY
  1124. // producer = gb_string_appendc(producer, "-nightly");
  1125. // #endif
  1126. // #ifdef GIT_SHA
  1127. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  1128. // #endif
  1129. gbString split_name = gb_string_make(heap_allocator(), "");
  1130. LLVMBool is_optimized = build_context.optimization_level > 0;
  1131. AstFile *init_file = m->info->init_package->files[0];
  1132. if (Entity *entry_point = m->info->entry_point) {
  1133. if (Ast *ident = entry_point->identifier.load()) {
  1134. if (ident->file_id) {
  1135. init_file = ident->file();
  1136. }
  1137. }
  1138. }
  1139. LLVMBool split_debug_inlining = false;
  1140. LLVMBool debug_info_for_profiling = false;
  1141. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  1142. lb_get_llvm_metadata(m, init_file),
  1143. producer, gb_string_length(producer),
  1144. is_optimized, "", 0,
  1145. 1, split_name, gb_string_length(split_name),
  1146. LLVMDWARFEmissionFull,
  1147. 0, split_debug_inlining,
  1148. debug_info_for_profiling,
  1149. "", 0, // sys_root
  1150. "", 0 // SDK
  1151. );
  1152. GB_ASSERT(m->debug_compile_unit != nullptr);
  1153. }
  1154. }
  1155. TIME_SECTION("LLVM Global Variables");
  1156. if (!build_context.disallow_rtti) {
  1157. lbModule *m = default_module;
  1158. { // Add type info data
  1159. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  1160. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  1161. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  1162. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  1163. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1164. if (!USE_SEPARATE_MODULES) {
  1165. LLVMSetLinkage(g, LLVMInternalLinkage);
  1166. }
  1167. lbValue value = {};
  1168. value.value = g;
  1169. value.type = alloc_type_pointer(t);
  1170. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  1171. lb_add_entity(m, lb_global_type_info_data_entity, value);
  1172. }
  1173. { // Type info member buffer
  1174. // NOTE(bill): Removes need for heap allocation by making it global memory
  1175. isize count = 0;
  1176. for_array(entry_index, m->info->type_info_types) {
  1177. Type *t = m->info->type_info_types[entry_index];
  1178. isize index = lb_type_info_index(m->info, t, false);
  1179. if (index < 0) {
  1180. continue;
  1181. }
  1182. switch (t->kind) {
  1183. case Type_Union:
  1184. count += t->Union.variants.count;
  1185. break;
  1186. case Type_Struct:
  1187. count += t->Struct.fields.count;
  1188. break;
  1189. case Type_Tuple:
  1190. count += t->Tuple.variables.count;
  1191. break;
  1192. }
  1193. }
  1194. if (count > 0) {
  1195. {
  1196. char const *name = LB_TYPE_INFO_TYPES_NAME;
  1197. Type *t = alloc_type_array(t_type_info_ptr, count);
  1198. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1199. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1200. LLVMSetLinkage(g, LLVMInternalLinkage);
  1201. lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)});
  1202. }
  1203. {
  1204. char const *name = LB_TYPE_INFO_NAMES_NAME;
  1205. Type *t = alloc_type_array(t_string, count);
  1206. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1207. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1208. LLVMSetLinkage(g, LLVMInternalLinkage);
  1209. lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)});
  1210. }
  1211. {
  1212. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  1213. Type *t = alloc_type_array(t_uintptr, count);
  1214. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1215. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1216. LLVMSetLinkage(g, LLVMInternalLinkage);
  1217. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  1218. }
  1219. {
  1220. char const *name = LB_TYPE_INFO_USINGS_NAME;
  1221. Type *t = alloc_type_array(t_bool, count);
  1222. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1223. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1224. LLVMSetLinkage(g, LLVMInternalLinkage);
  1225. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  1226. }
  1227. {
  1228. char const *name = LB_TYPE_INFO_TAGS_NAME;
  1229. Type *t = alloc_type_array(t_string, count);
  1230. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1231. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1232. LLVMSetLinkage(g, LLVMInternalLinkage);
  1233. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  1234. }
  1235. }
  1236. }
  1237. }
  1238. isize global_variable_max_count = 0;
  1239. bool already_has_entry_point = false;
  1240. for_array(i, info->entities) {
  1241. Entity *e = info->entities[i];
  1242. String name = e->token.string;
  1243. if (e->kind == Entity_Variable) {
  1244. global_variable_max_count++;
  1245. } else if (e->kind == Entity_Procedure) {
  1246. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  1247. GB_ASSERT(e == info->entry_point);
  1248. }
  1249. if (build_context.command_kind == Command_test &&
  1250. (e->Procedure.is_export || e->Procedure.link_name.len > 0)) {
  1251. String link_name = e->Procedure.link_name;
  1252. if (e->pkg->kind == Package_Runtime) {
  1253. if (link_name == "main" ||
  1254. link_name == "DllMain" ||
  1255. link_name == "WinMain" ||
  1256. link_name == "wWinMain" ||
  1257. link_name == "mainCRTStartup" ||
  1258. link_name == "_start") {
  1259. already_has_entry_point = true;
  1260. }
  1261. }
  1262. }
  1263. }
  1264. }
  1265. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  1266. for_array(i, info->variable_init_order) {
  1267. DeclInfo *d = info->variable_init_order[i];
  1268. Entity *e = d->entity;
  1269. if ((e->scope->flags & ScopeFlag_File) == 0) {
  1270. continue;
  1271. }
  1272. if (!ptr_set_exists(min_dep_set, e)) {
  1273. continue;
  1274. }
  1275. DeclInfo *decl = decl_info_of_entity(e);
  1276. if (decl == nullptr) {
  1277. continue;
  1278. }
  1279. GB_ASSERT(e->kind == Entity_Variable);
  1280. bool is_foreign = e->Variable.is_foreign;
  1281. bool is_export = e->Variable.is_export;
  1282. lbModule *m = &gen->default_module;
  1283. String name = lb_get_entity_name(m, e);
  1284. lbValue g = {};
  1285. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  1286. g.type = alloc_type_pointer(e->type);
  1287. if (e->Variable.thread_local_model != "") {
  1288. LLVMSetThreadLocal(g.value, true);
  1289. String m = e->Variable.thread_local_model;
  1290. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  1291. if (m == "default") {
  1292. mode = LLVMGeneralDynamicTLSModel;
  1293. } else if (m == "localdynamic") {
  1294. mode = LLVMLocalDynamicTLSModel;
  1295. } else if (m == "initialexec") {
  1296. mode = LLVMInitialExecTLSModel;
  1297. } else if (m == "localexec") {
  1298. mode = LLVMLocalExecTLSModel;
  1299. } else {
  1300. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  1301. }
  1302. LLVMSetThreadLocalMode(g.value, mode);
  1303. }
  1304. if (is_foreign) {
  1305. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1306. LLVMSetExternallyInitialized(g.value, true);
  1307. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  1308. lb_set_wasm_import_attributes(g.value, e, name);
  1309. } else {
  1310. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  1311. }
  1312. if (is_export) {
  1313. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  1314. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  1315. } else if (!is_foreign) {
  1316. if (USE_SEPARATE_MODULES) {
  1317. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1318. } else {
  1319. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  1320. }
  1321. }
  1322. lb_set_linkage_from_entity_flags(m, g.value, e->flags);
  1323. if (e->Variable.link_section.len > 0) {
  1324. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  1325. }
  1326. lbGlobalVariable var = {};
  1327. var.var = g;
  1328. var.decl = decl;
  1329. if (decl->init_expr != nullptr) {
  1330. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  1331. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  1332. if (tav.mode != Addressing_Invalid) {
  1333. if (tav.value.kind != ExactValue_Invalid) {
  1334. ExactValue v = tav.value;
  1335. lbValue init = lb_const_value(m, tav.type, v);
  1336. LLVMSetInitializer(g.value, init.value);
  1337. var.is_initialized = true;
  1338. }
  1339. }
  1340. }
  1341. if (!var.is_initialized &&
  1342. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  1343. var.is_initialized = true;
  1344. }
  1345. }
  1346. array_add(&global_variables, var);
  1347. lb_add_entity(m, e, g);
  1348. lb_add_member(m, name, g);
  1349. if (m->debug_builder) {
  1350. String global_name = e->token.string;
  1351. if (global_name.len != 0 && global_name != "_") {
  1352. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  1353. LLVMMetadataRef llvm_scope = llvm_file;
  1354. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  1355. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  1356. LLVMMetadataRef llvm_decl = nullptr;
  1357. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  1358. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  1359. m->debug_builder, llvm_scope,
  1360. cast(char const *)global_name.text, global_name.len,
  1361. "", 0, // linkage
  1362. llvm_file, e->token.pos.line,
  1363. lb_debug_type(m, e->type),
  1364. local_to_unit,
  1365. llvm_expr,
  1366. llvm_decl,
  1367. align_in_bits
  1368. );
  1369. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  1370. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  1371. }
  1372. }
  1373. }
  1374. TIME_SECTION("LLVM Runtime Type Information Creation");
  1375. lbProcedure *startup_type_info = lb_create_startup_type_info(default_module);
  1376. lbProcedure *objc_names = lb_create_objc_names(default_module);
  1377. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  1378. lbProcedure *startup_runtime = lb_create_startup_runtime(default_module, startup_type_info, objc_names, global_variables);
  1379. gb_unused(startup_runtime);
  1380. TIME_SECTION("LLVM Global Procedures and Types");
  1381. for_array(i, info->entities) {
  1382. Entity *e = info->entities[i];
  1383. String name = e->token.string;
  1384. Scope * scope = e->scope;
  1385. if ((scope->flags & ScopeFlag_File) == 0) {
  1386. continue;
  1387. }
  1388. Scope *package_scope = scope->parent;
  1389. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  1390. switch (e->kind) {
  1391. case Entity_Variable:
  1392. // NOTE(bill): Handled above as it requires a specific load order
  1393. continue;
  1394. case Entity_ProcGroup:
  1395. continue;
  1396. case Entity_TypeName:
  1397. case Entity_Procedure:
  1398. break;
  1399. }
  1400. bool polymorphic_struct = false;
  1401. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1402. Type *bt = base_type(e->type);
  1403. if (bt->kind == Type_Struct) {
  1404. polymorphic_struct = is_type_polymorphic(bt);
  1405. }
  1406. }
  1407. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1408. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1409. continue;
  1410. }
  1411. lbModule *m = &gen->default_module;
  1412. if (USE_SEPARATE_MODULES) {
  1413. m = lb_pkg_module(gen, e->pkg);
  1414. }
  1415. String mangled_name = lb_get_entity_name(m, e);
  1416. switch (e->kind) {
  1417. case Entity_TypeName:
  1418. lb_type(m, e->type);
  1419. break;
  1420. case Entity_Procedure:
  1421. {
  1422. lbProcedure *p = lb_create_procedure(m, e);
  1423. array_add(&m->procedures_to_generate, p);
  1424. }
  1425. break;
  1426. }
  1427. }
  1428. TIME_SECTION("LLVM Procedure Generation");
  1429. for_array(j, gen->modules.entries) {
  1430. lbModule *m = gen->modules.entries[j].value;
  1431. for_array(i, m->procedures_to_generate) {
  1432. lbProcedure *p = m->procedures_to_generate[i];
  1433. lb_generate_procedure(m, p);
  1434. }
  1435. }
  1436. if (build_context.command_kind == Command_test && !already_has_entry_point) {
  1437. TIME_SECTION("LLVM main");
  1438. lb_create_main_procedure(default_module, startup_runtime);
  1439. }
  1440. for_array(j, gen->modules.entries) {
  1441. lbModule *m = gen->modules.entries[j].value;
  1442. for_array(i, m->missing_procedures_to_check) {
  1443. lbProcedure *p = m->missing_procedures_to_check[i];
  1444. debugf("Generate missing procedure: %.*s\n", LIT(p->name));
  1445. lb_generate_procedure(m, p);
  1446. }
  1447. }
  1448. lb_finalize_objc_names(objc_names);
  1449. if (build_context.ODIN_DEBUG) {
  1450. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  1451. for_array(j, gen->modules.entries) {
  1452. lbModule *m = gen->modules.entries[j].value;
  1453. if (m->debug_builder != nullptr) {
  1454. lb_debug_complete_types(m);
  1455. LLVMDIBuilderFinalize(m->debug_builder);
  1456. }
  1457. }
  1458. }
  1459. TIME_SECTION("LLVM Function Pass");
  1460. for_array(i, gen->modules.entries) {
  1461. lbModule *m = gen->modules.entries[i].value;
  1462. lb_llvm_function_pass_worker_proc(m);
  1463. }
  1464. TIME_SECTION("LLVM Module Pass");
  1465. for_array(i, gen->modules.entries) {
  1466. lbModule *m = gen->modules.entries[i].value;
  1467. lb_run_remove_unused_function_pass(m);
  1468. lb_run_remove_unused_globals_pass(m);
  1469. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  1470. wd->m = m;
  1471. wd->target_machine = target_machines[i];
  1472. lb_llvm_module_pass_worker_proc(wd);
  1473. }
  1474. llvm_error = nullptr;
  1475. defer (LLVMDisposeMessage(llvm_error));
  1476. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  1477. if (build_context.build_mode == BuildMode_Assembly) {
  1478. code_gen_file_type = LLVMAssemblyFile;
  1479. }
  1480. for_array(j, gen->modules.entries) {
  1481. lbModule *m = gen->modules.entries[j].value;
  1482. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  1483. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1484. if (build_context.keep_temp_files) {
  1485. TIME_SECTION("LLVM Print Module to File");
  1486. String filepath_ll = lb_filepath_ll_for_module(m);
  1487. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1488. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1489. gb_exit(1);
  1490. return;
  1491. }
  1492. }
  1493. gb_exit(1);
  1494. return;
  1495. }
  1496. }
  1497. llvm_error = nullptr;
  1498. if (build_context.keep_temp_files ||
  1499. build_context.build_mode == BuildMode_LLVM_IR) {
  1500. TIME_SECTION("LLVM Print Module to File");
  1501. for_array(j, gen->modules.entries) {
  1502. lbModule *m = gen->modules.entries[j].value;
  1503. if (lb_is_module_empty(m)) {
  1504. continue;
  1505. }
  1506. String filepath_ll = lb_filepath_ll_for_module(m);
  1507. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1508. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1509. gb_exit(1);
  1510. return;
  1511. }
  1512. array_add(&gen->output_temp_paths, filepath_ll);
  1513. }
  1514. if (build_context.build_mode == BuildMode_LLVM_IR) {
  1515. gb_exit(0);
  1516. return;
  1517. }
  1518. }
  1519. TIME_SECTION("LLVM Add Foreign Library Paths");
  1520. for_array(j, gen->modules.entries) {
  1521. lbModule *m = gen->modules.entries[j].value;
  1522. for_array(i, m->info->required_foreign_imports_through_force) {
  1523. Entity *e = m->info->required_foreign_imports_through_force[i];
  1524. lb_add_foreign_library_path(m, e);
  1525. }
  1526. if (lb_is_module_empty(m)) {
  1527. continue;
  1528. }
  1529. }
  1530. TIME_SECTION("LLVM Object Generation");
  1531. isize non_empty_module_count = 0;
  1532. for_array(j, gen->modules.entries) {
  1533. lbModule *m = gen->modules.entries[j].value;
  1534. if (!lb_is_module_empty(m)) {
  1535. non_empty_module_count += 1;
  1536. }
  1537. }
  1538. if (do_threading && non_empty_module_count > 1) {
  1539. for_array(j, gen->modules.entries) {
  1540. lbModule *m = gen->modules.entries[j].value;
  1541. if (lb_is_module_empty(m)) {
  1542. continue;
  1543. }
  1544. String filepath_ll = lb_filepath_ll_for_module(m);
  1545. String filepath_obj = lb_filepath_obj_for_module(m);
  1546. array_add(&gen->output_object_paths, filepath_obj);
  1547. array_add(&gen->output_temp_paths, filepath_ll);
  1548. auto *wd = gb_alloc_item(permanent_allocator(), lbLLVMEmitWorker);
  1549. wd->target_machine = target_machines[j];
  1550. wd->code_gen_file_type = code_gen_file_type;
  1551. wd->filepath_obj = filepath_obj;
  1552. wd->m = m;
  1553. global_thread_pool_add_task(lb_llvm_emit_worker_proc, wd);
  1554. }
  1555. thread_pool_wait(&global_thread_pool);
  1556. } else {
  1557. for_array(j, gen->modules.entries) {
  1558. lbModule *m = gen->modules.entries[j].value;
  1559. if (lb_is_module_empty(m)) {
  1560. continue;
  1561. }
  1562. String filepath_obj = lb_filepath_obj_for_module(m);
  1563. array_add(&gen->output_object_paths, filepath_obj);
  1564. String short_name = remove_directory_from_path(filepath_obj);
  1565. gbString section_name = gb_string_make(heap_allocator(), "LLVM Generate Object: ");
  1566. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  1567. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  1568. if (LLVMTargetMachineEmitToFile(target_machines[j], m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  1569. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1570. gb_exit(1);
  1571. return;
  1572. }
  1573. }
  1574. }
  1575. gb_sort_array(gen->foreign_libraries.data, gen->foreign_libraries.count, foreign_library_cmp);
  1576. }