llvm_backend.cpp 60 KB

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