llvm_backend.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925
  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. if (build_context.disallow_rtti) {
  487. return nullptr;
  488. }
  489. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  490. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  491. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  492. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  493. lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type);
  494. p->is_startup = true;
  495. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  496. lb_begin_procedure_body(p);
  497. lb_setup_type_info_data(p);
  498. lb_end_procedure_body(p);
  499. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  500. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  501. LLVMDumpValue(p->value);
  502. gb_printf_err("\n\n\n\n");
  503. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  504. }
  505. lb_run_function_pass_manager(default_function_pass_manager, p);
  506. return p;
  507. }
  508. lbProcedure *lb_create_objc_names(lbModule *main_module) {
  509. if (build_context.metrics.os != TargetOs_darwin) {
  510. return nullptr;
  511. }
  512. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  513. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit("__$init_objc_names"), proc_type);
  514. p->is_startup = true;
  515. return p;
  516. }
  517. void lb_finalize_objc_names(lbProcedure *p) {
  518. if (p == nullptr) {
  519. return;
  520. }
  521. lbModule *m = p->module;
  522. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  523. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  524. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  525. auto args = array_make<lbValue>(permanent_allocator(), 1);
  526. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  527. lb_begin_procedure_body(p);
  528. for_array(i, m->objc_classes.entries) {
  529. auto const &entry = m->objc_classes.entries[i];
  530. String name = entry.key.string;
  531. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  532. lbValue ptr = lb_emit_runtime_call(p, "objc_lookUpClass", args);
  533. lb_addr_store(p, entry.value, ptr);
  534. }
  535. for_array(i, m->objc_selectors.entries) {
  536. auto const &entry = m->objc_selectors.entries[i];
  537. String name = entry.key.string;
  538. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  539. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  540. lb_addr_store(p, entry.value, ptr);
  541. }
  542. lb_end_procedure_body(p);
  543. lb_run_function_pass_manager(default_function_pass_manager, p);
  544. }
  545. lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *startup_type_info, lbProcedure *objc_names, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  546. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(main_module->mod);
  547. lb_populate_function_pass_manager(main_module, default_function_pass_manager, false, build_context.optimization_level);
  548. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  549. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  550. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  551. p->is_startup = true;
  552. lb_begin_procedure_body(p);
  553. if (startup_type_info) {
  554. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(main_module, startup_type_info->type)), startup_type_info->value, nullptr, 0, "");
  555. }
  556. if (objc_names) {
  557. LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(main_module, objc_names->type)), objc_names->value, nullptr, 0, "");
  558. }
  559. for_array(i, global_variables) {
  560. auto *var = &global_variables[i];
  561. if (var->is_initialized) {
  562. continue;
  563. }
  564. lbModule *entity_module = main_module;
  565. Entity *e = var->decl->entity;
  566. GB_ASSERT(e->kind == Entity_Variable);
  567. e->code_gen_module = entity_module;
  568. Ast *init_expr = var->decl->init_expr;
  569. if (init_expr != nullptr) {
  570. lbValue init = lb_build_expr(p, init_expr);
  571. if (init.value == nullptr) {
  572. LLVMTypeRef global_type = LLVMGetElementType(LLVMTypeOf(var->var.value));
  573. if (is_type_untyped_undef(init.type)) {
  574. // LLVMSetInitializer(var->var.value, LLVMGetUndef(global_type));
  575. LLVMSetInitializer(var->var.value, LLVMConstNull(global_type));
  576. var->is_initialized = true;
  577. continue;
  578. } else if (is_type_untyped_nil(init.type)) {
  579. LLVMSetInitializer(var->var.value, LLVMConstNull(global_type));
  580. var->is_initialized = true;
  581. continue;
  582. }
  583. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  584. }
  585. if (is_type_any(e->type) || is_type_union(e->type)) {
  586. var->init = init;
  587. } else if (lb_is_const_or_global(init)) {
  588. if (!var->is_initialized) {
  589. LLVMSetInitializer(var->var.value, init.value);
  590. var->is_initialized = true;
  591. continue;
  592. }
  593. } else {
  594. var->init = init;
  595. }
  596. }
  597. if (var->init.value != nullptr) {
  598. GB_ASSERT(!var->is_initialized);
  599. Type *t = type_deref(var->var.type);
  600. if (is_type_any(t)) {
  601. // NOTE(bill): Edge case for 'any' type
  602. Type *var_type = default_type(var->init.type);
  603. lbAddr g = lb_add_global_generated(main_module, var_type, var->init);
  604. lb_addr_store(p, g, var->init);
  605. lbValue gp = lb_addr_get_ptr(p, g);
  606. lbValue data = lb_emit_struct_ep(p, var->var, 0);
  607. lbValue ti = lb_emit_struct_ep(p, var->var, 1);
  608. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  609. lb_emit_store(p, ti, lb_type_info(main_module, var_type));
  610. } else {
  611. LLVMTypeRef pvt = LLVMTypeOf(var->var.value);
  612. LLVMTypeRef vt = LLVMGetElementType(pvt);
  613. lbValue src0 = lb_emit_conv(p, var->init, t);
  614. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  615. LLVMValueRef dst = var->var.value;
  616. LLVMBuildStore(p->builder, src, dst);
  617. }
  618. var->is_initialized = true;
  619. }
  620. }
  621. CheckerInfo *info = main_module->gen->info;
  622. for (Entity *e : info->init_procedures) {
  623. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  624. lb_emit_call(p, value, {}, ProcInlining_none, false);
  625. }
  626. lb_end_procedure_body(p);
  627. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  628. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  629. LLVMDumpValue(p->value);
  630. gb_printf_err("\n\n\n\n");
  631. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  632. }
  633. lb_run_function_pass_manager(default_function_pass_manager, p);
  634. return p;
  635. }
  636. lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime) {
  637. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  638. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  639. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  640. Type *params = alloc_type_tuple();
  641. Type *results = alloc_type_tuple();
  642. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  643. bool call_cleanup = true;
  644. bool has_args = false;
  645. bool is_dll_main = false;
  646. String name = str_lit("main");
  647. if (build_context.metrics.os == TargetOs_windows && build_context.build_mode == BuildMode_DynamicLibrary) {
  648. is_dll_main = true;
  649. name = str_lit("DllMain");
  650. slice_init(&params->Tuple.variables, permanent_allocator(), 3);
  651. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("hinstDLL"), t_rawptr, false, true);
  652. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("fdwReason"), t_u32, false, true);
  653. params->Tuple.variables[2] = alloc_entity_param(nullptr, make_token_ident("lpReserved"), t_rawptr, false, true);
  654. call_cleanup = false;
  655. } else if (build_context.metrics.os == TargetOs_windows && (build_context.metrics.arch == TargetArch_i386 || build_context.no_crt)) {
  656. name = str_lit("mainCRTStartup");
  657. } else if (is_arch_wasm()) {
  658. name = str_lit("_start");
  659. call_cleanup = false;
  660. } else {
  661. has_args = true;
  662. slice_init(&params->Tuple.variables, permanent_allocator(), 2);
  663. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  664. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  665. }
  666. slice_init(&results->Tuple.variables, permanent_allocator(), 1);
  667. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  668. Type *proc_type = alloc_type_proc(nullptr,
  669. params, params->Tuple.variables.count,
  670. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  671. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  672. p->is_startup = true;
  673. lb_begin_procedure_body(p);
  674. if (has_args) { // initialize `runtime.args__`
  675. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  676. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  677. LLVMSetValueName2(argc.value, "argc", 4);
  678. LLVMSetValueName2(argv.value, "argv", 4);
  679. argc = lb_emit_conv(p, argc, t_int);
  680. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  681. lb_fill_slice(p, args, argv, argc);
  682. }
  683. lbValue startup_runtime_value = {startup_runtime->value, startup_runtime->type};
  684. lb_emit_call(p, startup_runtime_value, {}, ProcInlining_none, false);
  685. if (build_context.command_kind == Command_test) {
  686. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  687. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  688. Type *slice_type = alloc_type_slice(t_Internal_Test);
  689. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  690. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  691. LLVMValueRef indices[2] = {};
  692. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  693. for_array(i, m->info->testing_procedures) {
  694. Entity *testing_proc = m->info->testing_procedures[i];
  695. String name = testing_proc->token.string;
  696. String pkg_name = {};
  697. if (testing_proc->pkg != nullptr) {
  698. pkg_name = testing_proc->pkg->name;
  699. }
  700. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  701. lbValue v_name = lb_find_or_add_entity_string(m, name);
  702. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  703. indices[1] = LLVMConstInt(lb_type(m, t_int), i, false);
  704. LLVMValueRef vals[3] = {};
  705. vals[0] = v_pkg.value;
  706. vals[1] = v_name.value;
  707. vals[2] = v_proc.value;
  708. GB_ASSERT(LLVMIsConstant(vals[0]));
  709. GB_ASSERT(LLVMIsConstant(vals[1]));
  710. GB_ASSERT(LLVMIsConstant(vals[2]));
  711. LLVMValueRef dst = LLVMConstInBoundsGEP(all_tests_array.value, indices, gb_count_of(indices));
  712. LLVMValueRef src = llvm_const_named_struct(m, t_Internal_Test, vals, gb_count_of(vals));
  713. LLVMBuildStore(p->builder, src, dst);
  714. }
  715. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  716. lb_fill_slice(p, all_tests_slice,
  717. lb_array_elem(p, all_tests_array),
  718. lb_const_int(m, t_int, m->info->testing_procedures.count));
  719. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  720. auto args = array_make<lbValue>(heap_allocator(), 1);
  721. args[0] = lb_addr_load(p, all_tests_slice);
  722. lb_emit_call(p, runner, args);
  723. } else {
  724. if (m->info->entry_point != nullptr) {
  725. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  726. lb_emit_call(p, entry_point, {}, ProcInlining_no_inline);
  727. }
  728. }
  729. if (call_cleanup) {
  730. lbValue cleanup_runtime_value = lb_find_runtime_value(m, str_lit("_cleanup_runtime"));
  731. lb_emit_call(p, cleanup_runtime_value, {}, ProcInlining_none, false);
  732. }
  733. if (is_dll_main) {
  734. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 1, false));
  735. } else {
  736. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  737. }
  738. lb_end_procedure_body(p);
  739. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  740. if (is_arch_wasm()) {
  741. lb_set_wasm_export_attributes(p->value, p->name);
  742. }
  743. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  744. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  745. LLVMDumpValue(p->value);
  746. gb_printf_err("\n\n\n\n");
  747. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  748. }
  749. lb_run_function_pass_manager(default_function_pass_manager, p);
  750. return p;
  751. }
  752. String lb_filepath_ll_for_module(lbModule *m) {
  753. String path = concatenate3_strings(permanent_allocator(),
  754. build_context.build_paths[BuildPath_Output].basename,
  755. STR_LIT("/"),
  756. build_context.build_paths[BuildPath_Output].name
  757. );
  758. if (m->pkg) {
  759. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  760. } else if (USE_SEPARATE_MODULES) {
  761. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  762. }
  763. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  764. return path;
  765. }
  766. String lb_filepath_obj_for_module(lbModule *m) {
  767. String path = concatenate3_strings(permanent_allocator(),
  768. build_context.build_paths[BuildPath_Output].basename,
  769. STR_LIT("/"),
  770. build_context.build_paths[BuildPath_Output].name
  771. );
  772. if (m->pkg) {
  773. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  774. }
  775. String ext = {};
  776. if (build_context.build_mode == BuildMode_Assembly) {
  777. ext = STR_LIT(".S");
  778. } else {
  779. if (is_arch_wasm()) {
  780. ext = STR_LIT(".wasm.o");
  781. } else {
  782. switch (build_context.metrics.os) {
  783. case TargetOs_windows:
  784. ext = STR_LIT(".obj");
  785. break;
  786. default:
  787. case TargetOs_darwin:
  788. case TargetOs_linux:
  789. case TargetOs_essence:
  790. ext = STR_LIT(".o");
  791. break;
  792. case TargetOs_freestanding:
  793. switch (build_context.metrics.abi) {
  794. default:
  795. case TargetABI_Default:
  796. case TargetABI_SysV:
  797. ext = STR_LIT(".o");
  798. break;
  799. case TargetABI_Win64:
  800. ext = STR_LIT(".obj");
  801. break;
  802. }
  803. break;
  804. }
  805. }
  806. }
  807. return concatenate_strings(permanent_allocator(), path, ext);
  808. }
  809. bool lb_is_module_empty(lbModule *m) {
  810. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  811. LLVMGetFirstGlobal(m->mod) == nullptr) {
  812. return true;
  813. }
  814. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  815. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  816. return false;
  817. }
  818. }
  819. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  820. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  821. continue;
  822. }
  823. if (!LLVMIsExternallyInitialized(g)) {
  824. return false;
  825. }
  826. }
  827. return true;
  828. }
  829. struct lbLLVMEmitWorker {
  830. LLVMTargetMachineRef target_machine;
  831. LLVMCodeGenFileType code_gen_file_type;
  832. String filepath_obj;
  833. lbModule *m;
  834. };
  835. WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  836. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  837. char *llvm_error = nullptr;
  838. auto wd = cast(lbLLVMEmitWorker *)data;
  839. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  840. gb_printf_err("LLVM Error: %s\n", llvm_error);
  841. gb_exit(1);
  842. }
  843. return 0;
  844. }
  845. WORKER_TASK_PROC(lb_llvm_function_pass_worker_proc) {
  846. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  847. auto m = cast(lbModule *)data;
  848. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  849. LLVMPassManagerRef function_pass_manager_minimal = LLVMCreateFunctionPassManagerForModule(m->mod);
  850. LLVMPassManagerRef function_pass_manager_size = LLVMCreateFunctionPassManagerForModule(m->mod);
  851. LLVMPassManagerRef function_pass_manager_speed = LLVMCreateFunctionPassManagerForModule(m->mod);
  852. LLVMInitializeFunctionPassManager(default_function_pass_manager);
  853. LLVMInitializeFunctionPassManager(function_pass_manager_minimal);
  854. LLVMInitializeFunctionPassManager(function_pass_manager_size);
  855. LLVMInitializeFunctionPassManager(function_pass_manager_speed);
  856. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  857. lb_populate_function_pass_manager_specific(m, function_pass_manager_minimal, 0);
  858. lb_populate_function_pass_manager_specific(m, function_pass_manager_size, 1);
  859. lb_populate_function_pass_manager_specific(m, function_pass_manager_speed, 2);
  860. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  861. LLVMFinalizeFunctionPassManager(function_pass_manager_minimal);
  862. LLVMFinalizeFunctionPassManager(function_pass_manager_size);
  863. LLVMFinalizeFunctionPassManager(function_pass_manager_speed);
  864. LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(m->mod);
  865. LLVMInitializeFunctionPassManager(default_function_pass_manager_without_memcpy);
  866. lb_populate_function_pass_manager(m, default_function_pass_manager_without_memcpy, true, build_context.optimization_level);
  867. LLVMFinalizeFunctionPassManager(default_function_pass_manager_without_memcpy);
  868. for_array(i, m->procedures_to_generate) {
  869. lbProcedure *p = m->procedures_to_generate[i];
  870. if (p->body != nullptr) { // Build Procedure
  871. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  872. lb_run_function_pass_manager(default_function_pass_manager_without_memcpy, p);
  873. } else {
  874. if (p->entity && p->entity->kind == Entity_Procedure) {
  875. switch (p->entity->Procedure.optimization_mode) {
  876. case ProcedureOptimizationMode_None:
  877. case ProcedureOptimizationMode_Minimal:
  878. lb_run_function_pass_manager(function_pass_manager_minimal, p);
  879. break;
  880. case ProcedureOptimizationMode_Size:
  881. lb_run_function_pass_manager(function_pass_manager_size, p);
  882. break;
  883. case ProcedureOptimizationMode_Speed:
  884. lb_run_function_pass_manager(function_pass_manager_speed, p);
  885. break;
  886. default:
  887. lb_run_function_pass_manager(default_function_pass_manager, p);
  888. break;
  889. }
  890. } else {
  891. lb_run_function_pass_manager(default_function_pass_manager, p);
  892. }
  893. }
  894. }
  895. }
  896. for_array(i, m->equal_procs.entries) {
  897. lbProcedure *p = m->equal_procs.entries[i].value;
  898. lb_run_function_pass_manager(default_function_pass_manager, p);
  899. }
  900. for_array(i, m->hasher_procs.entries) {
  901. lbProcedure *p = m->hasher_procs.entries[i].value;
  902. lb_run_function_pass_manager(default_function_pass_manager, p);
  903. }
  904. return 0;
  905. }
  906. struct lbLLVMModulePassWorkerData {
  907. lbModule *m;
  908. LLVMTargetMachineRef target_machine;
  909. };
  910. WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  911. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  912. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  913. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  914. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  915. return 0;
  916. }
  917. void lb_generate_procedure(lbModule *m, lbProcedure *p) {
  918. if (p->is_done) {
  919. return;
  920. }
  921. if (p->body != nullptr) { // Build Procedure
  922. m->curr_procedure = p;
  923. lb_begin_procedure_body(p);
  924. lb_build_stmt(p, p->body);
  925. lb_end_procedure_body(p);
  926. p->is_done = true;
  927. m->curr_procedure = nullptr;
  928. }
  929. lb_end_procedure(p);
  930. // Add Flags
  931. if (p->body != nullptr) {
  932. if (p->name == "memcpy" || p->name == "memmove" ||
  933. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  934. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  935. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  936. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  937. }
  938. }
  939. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  940. char *llvm_error = nullptr;
  941. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  942. LLVMDumpValue(p->value);
  943. gb_printf_err("\n\n\n\n");
  944. String filepath_ll = lb_filepath_ll_for_module(m);
  945. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  946. gb_printf_err("LLVM Error: %s\n", llvm_error);
  947. }
  948. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  949. gb_exit(1);
  950. }
  951. }
  952. void lb_generate_code(lbGenerator *gen) {
  953. TIME_SECTION("LLVM Initializtion");
  954. isize thread_count = gb_max(build_context.thread_count, 1);
  955. isize worker_count = thread_count-1;
  956. LLVMBool do_threading = (LLVMIsMultithreaded() && USE_SEPARATE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  957. lbModule *default_module = &gen->default_module;
  958. CheckerInfo *info = gen->info;
  959. auto *min_dep_set = &info->minimum_dependency_set;
  960. switch (build_context.metrics.arch) {
  961. case TargetArch_amd64:
  962. case TargetArch_i386:
  963. LLVMInitializeX86TargetInfo();
  964. LLVMInitializeX86Target();
  965. LLVMInitializeX86TargetMC();
  966. LLVMInitializeX86AsmPrinter();
  967. LLVMInitializeX86AsmParser();
  968. LLVMInitializeX86Disassembler();
  969. break;
  970. case TargetArch_arm64:
  971. LLVMInitializeAArch64TargetInfo();
  972. LLVMInitializeAArch64Target();
  973. LLVMInitializeAArch64TargetMC();
  974. LLVMInitializeAArch64AsmPrinter();
  975. LLVMInitializeAArch64AsmParser();
  976. LLVMInitializeAArch64Disassembler();
  977. break;
  978. case TargetArch_wasm32:
  979. case TargetArch_wasm64:
  980. LLVMInitializeWebAssemblyTargetInfo();
  981. LLVMInitializeWebAssemblyTarget();
  982. LLVMInitializeWebAssemblyTargetMC();
  983. LLVMInitializeWebAssemblyAsmPrinter();
  984. LLVMInitializeWebAssemblyAsmParser();
  985. LLVMInitializeWebAssemblyDisassembler();
  986. break;
  987. default:
  988. LLVMInitializeAllTargetInfos();
  989. LLVMInitializeAllTargets();
  990. LLVMInitializeAllTargetMCs();
  991. LLVMInitializeAllAsmPrinters();
  992. LLVMInitializeAllAsmParsers();
  993. LLVMInitializeAllDisassemblers();
  994. break;
  995. }
  996. if (build_context.microarch == "native") {
  997. LLVMInitializeNativeTarget();
  998. }
  999. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  1000. for_array(i, gen->modules.entries) {
  1001. LLVMSetTarget(gen->modules.entries[i].value->mod, target_triple);
  1002. }
  1003. LLVMTargetRef target = {};
  1004. char *llvm_error = nullptr;
  1005. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  1006. GB_ASSERT(target != nullptr);
  1007. TIME_SECTION("LLVM Create Target Machine");
  1008. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  1009. if (is_arch_wasm()) {
  1010. code_mode = LLVMCodeModelJITDefault;
  1011. } else if (build_context.metrics.os == TargetOs_freestanding) {
  1012. code_mode = LLVMCodeModelKernel;
  1013. }
  1014. char const *host_cpu_name = LLVMGetHostCPUName();
  1015. char const *llvm_cpu = "generic";
  1016. char const *llvm_features = "";
  1017. if (build_context.microarch.len != 0) {
  1018. if (build_context.microarch == "native") {
  1019. llvm_cpu = host_cpu_name;
  1020. } else {
  1021. llvm_cpu = alloc_cstring(permanent_allocator(), build_context.microarch);
  1022. }
  1023. if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) {
  1024. llvm_features = LLVMGetHostCPUFeatures();
  1025. }
  1026. } else if (build_context.metrics.arch == TargetArch_amd64) {
  1027. // NOTE(bill): x86-64-v2 is more than enough for everyone
  1028. //
  1029. // x86-64: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
  1030. // x86-64-v2: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
  1031. // x86-64-v3: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
  1032. // x86-64-v4: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
  1033. if (ODIN_LLVM_MINIMUM_VERSION_12) {
  1034. if (build_context.metrics.os == TargetOs_freestanding) {
  1035. llvm_cpu = "x86-64";
  1036. } else {
  1037. llvm_cpu = "x86-64-v2";
  1038. }
  1039. }
  1040. }
  1041. if (build_context.target_features.len != 0) {
  1042. llvm_features = alloc_cstring(permanent_allocator(), build_context.target_features);
  1043. }
  1044. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  1045. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  1046. switch (build_context.optimization_level) {
  1047. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  1048. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  1049. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  1050. case 3: code_gen_level = LLVMCodeGenLevelDefault; break; // NOTE(bill): force -opt:3 to be the same as -opt:2
  1051. // case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  1052. }
  1053. // NOTE(bill): Target Machine Creation
  1054. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  1055. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), gen->modules.entries.count);
  1056. // NOTE(dweiler): Dynamic libraries require position-independent code.
  1057. LLVMRelocMode reloc_mode = LLVMRelocDefault;
  1058. if (build_context.build_mode == BuildMode_DynamicLibrary) {
  1059. reloc_mode = LLVMRelocPIC;
  1060. }
  1061. switch (build_context.reloc_mode) {
  1062. case RelocMode_Default:
  1063. if (build_context.metrics.os == TargetOs_openbsd) {
  1064. // Always use PIC for OpenBSD: it defaults to PIE
  1065. reloc_mode = LLVMRelocPIC;
  1066. }
  1067. break;
  1068. case RelocMode_Static:
  1069. reloc_mode = LLVMRelocStatic;
  1070. break;
  1071. case RelocMode_PIC:
  1072. reloc_mode = LLVMRelocPIC;
  1073. break;
  1074. case RelocMode_DynamicNoPIC:
  1075. reloc_mode = LLVMRelocDynamicNoPic;
  1076. break;
  1077. }
  1078. for_array(i, gen->modules.entries) {
  1079. target_machines[i] = LLVMCreateTargetMachine(
  1080. target, target_triple, llvm_cpu,
  1081. llvm_features,
  1082. code_gen_level,
  1083. reloc_mode,
  1084. code_mode);
  1085. LLVMSetModuleDataLayout(gen->modules.entries[i].value->mod, LLVMCreateTargetDataLayout(target_machines[i]));
  1086. }
  1087. for_array(i, gen->modules.entries) {
  1088. lbModule *m = gen->modules.entries[i].value;
  1089. if (m->debug_builder) { // Debug Info
  1090. for_array(i, info->files.entries) {
  1091. AstFile *f = info->files.entries[i].value;
  1092. String fullpath = f->fullpath;
  1093. String filename = remove_directory_from_path(fullpath);
  1094. String directory = directory_from_path(fullpath);
  1095. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  1096. cast(char const *)filename.text, filename.len,
  1097. cast(char const *)directory.text, directory.len);
  1098. lb_set_llvm_metadata(m, f, res);
  1099. }
  1100. gbString producer = gb_string_make(heap_allocator(), "odin");
  1101. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  1102. // #ifdef NIGHTLY
  1103. // producer = gb_string_appendc(producer, "-nightly");
  1104. // #endif
  1105. // #ifdef GIT_SHA
  1106. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  1107. // #endif
  1108. gbString split_name = gb_string_make(heap_allocator(), "");
  1109. LLVMBool is_optimized = build_context.optimization_level > 0;
  1110. AstFile *init_file = m->info->init_package->files[0];
  1111. if (Entity *entry_point = m->info->entry_point) {
  1112. if (Ast *ident = entry_point->identifier.load()) {
  1113. if (ident->file_id) {
  1114. init_file = ident->file();
  1115. }
  1116. }
  1117. }
  1118. LLVMBool split_debug_inlining = false;
  1119. LLVMBool debug_info_for_profiling = false;
  1120. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  1121. lb_get_llvm_metadata(m, init_file),
  1122. producer, gb_string_length(producer),
  1123. is_optimized, "", 0,
  1124. 1, split_name, gb_string_length(split_name),
  1125. LLVMDWARFEmissionFull,
  1126. 0, split_debug_inlining,
  1127. debug_info_for_profiling,
  1128. "", 0, // sys_root
  1129. "", 0 // SDK
  1130. );
  1131. GB_ASSERT(m->debug_compile_unit != nullptr);
  1132. }
  1133. }
  1134. TIME_SECTION("LLVM Global Variables");
  1135. if (!build_context.disallow_rtti) {
  1136. lbModule *m = default_module;
  1137. { // Add type info data
  1138. isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1;
  1139. // gb_printf_err("max_type_info_count: %td\n", max_type_info_count);
  1140. Type *t = alloc_type_array(t_type_info, max_type_info_count);
  1141. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME);
  1142. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1143. if (!USE_SEPARATE_MODULES) {
  1144. LLVMSetLinkage(g, LLVMInternalLinkage);
  1145. }
  1146. lbValue value = {};
  1147. value.value = g;
  1148. value.type = alloc_type_pointer(t);
  1149. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  1150. lb_add_entity(m, lb_global_type_info_data_entity, value);
  1151. }
  1152. { // Type info member buffer
  1153. // NOTE(bill): Removes need for heap allocation by making it global memory
  1154. isize count = 0;
  1155. for_array(entry_index, m->info->type_info_types) {
  1156. Type *t = m->info->type_info_types[entry_index];
  1157. isize index = lb_type_info_index(m->info, t, false);
  1158. if (index < 0) {
  1159. continue;
  1160. }
  1161. switch (t->kind) {
  1162. case Type_Union:
  1163. count += t->Union.variants.count;
  1164. break;
  1165. case Type_Struct:
  1166. count += t->Struct.fields.count;
  1167. break;
  1168. case Type_Tuple:
  1169. count += t->Tuple.variables.count;
  1170. break;
  1171. }
  1172. }
  1173. if (count > 0) {
  1174. {
  1175. char const *name = LB_TYPE_INFO_TYPES_NAME;
  1176. Type *t = alloc_type_array(t_type_info_ptr, 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_types = lb_addr({g, alloc_type_pointer(t)});
  1181. }
  1182. {
  1183. char const *name = LB_TYPE_INFO_NAMES_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_names = lb_addr({g, alloc_type_pointer(t)});
  1189. }
  1190. {
  1191. char const *name = LB_TYPE_INFO_OFFSETS_NAME;
  1192. Type *t = alloc_type_array(t_uintptr, count);
  1193. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1194. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1195. LLVMSetLinkage(g, LLVMInternalLinkage);
  1196. lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)});
  1197. }
  1198. {
  1199. char const *name = LB_TYPE_INFO_USINGS_NAME;
  1200. Type *t = alloc_type_array(t_bool, count);
  1201. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1202. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1203. LLVMSetLinkage(g, LLVMInternalLinkage);
  1204. lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)});
  1205. }
  1206. {
  1207. char const *name = LB_TYPE_INFO_TAGS_NAME;
  1208. Type *t = alloc_type_array(t_string, count);
  1209. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  1210. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  1211. LLVMSetLinkage(g, LLVMInternalLinkage);
  1212. lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)});
  1213. }
  1214. }
  1215. }
  1216. }
  1217. isize global_variable_max_count = 0;
  1218. bool already_has_entry_point = false;
  1219. for_array(i, info->entities) {
  1220. Entity *e = info->entities[i];
  1221. String name = e->token.string;
  1222. if (e->kind == Entity_Variable) {
  1223. global_variable_max_count++;
  1224. } else if (e->kind == Entity_Procedure) {
  1225. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  1226. GB_ASSERT(e == info->entry_point);
  1227. }
  1228. if (build_context.command_kind == Command_test &&
  1229. (e->Procedure.is_export || e->Procedure.link_name.len > 0)) {
  1230. String link_name = e->Procedure.link_name;
  1231. if (e->pkg->kind == Package_Runtime) {
  1232. if (link_name == "main" ||
  1233. link_name == "DllMain" ||
  1234. link_name == "WinMain" ||
  1235. link_name == "wWinMain" ||
  1236. link_name == "mainCRTStartup" ||
  1237. link_name == "_start") {
  1238. already_has_entry_point = true;
  1239. }
  1240. }
  1241. }
  1242. }
  1243. }
  1244. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  1245. for_array(i, info->variable_init_order) {
  1246. DeclInfo *d = info->variable_init_order[i];
  1247. Entity *e = d->entity;
  1248. if ((e->scope->flags & ScopeFlag_File) == 0) {
  1249. continue;
  1250. }
  1251. if (!ptr_set_exists(min_dep_set, e)) {
  1252. continue;
  1253. }
  1254. DeclInfo *decl = decl_info_of_entity(e);
  1255. if (decl == nullptr) {
  1256. continue;
  1257. }
  1258. GB_ASSERT(e->kind == Entity_Variable);
  1259. bool is_foreign = e->Variable.is_foreign;
  1260. bool is_export = e->Variable.is_export;
  1261. lbModule *m = &gen->default_module;
  1262. String name = lb_get_entity_name(m, e);
  1263. lbValue g = {};
  1264. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  1265. g.type = alloc_type_pointer(e->type);
  1266. if (e->Variable.thread_local_model != "") {
  1267. LLVMSetThreadLocal(g.value, true);
  1268. String m = e->Variable.thread_local_model;
  1269. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  1270. if (m == "default") {
  1271. mode = LLVMGeneralDynamicTLSModel;
  1272. } else if (m == "localdynamic") {
  1273. mode = LLVMLocalDynamicTLSModel;
  1274. } else if (m == "initialexec") {
  1275. mode = LLVMInitialExecTLSModel;
  1276. } else if (m == "localexec") {
  1277. mode = LLVMLocalExecTLSModel;
  1278. } else {
  1279. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  1280. }
  1281. LLVMSetThreadLocalMode(g.value, mode);
  1282. }
  1283. if (is_foreign) {
  1284. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1285. LLVMSetExternallyInitialized(g.value, true);
  1286. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  1287. lb_set_wasm_import_attributes(g.value, e, name);
  1288. } else {
  1289. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  1290. }
  1291. if (is_export) {
  1292. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  1293. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  1294. } else if (!is_foreign) {
  1295. if (USE_SEPARATE_MODULES) {
  1296. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1297. } else {
  1298. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  1299. }
  1300. }
  1301. lb_set_linkage_from_entity_flags(m, g.value, e->flags);
  1302. if (e->Variable.link_section.len > 0) {
  1303. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  1304. }
  1305. lbGlobalVariable var = {};
  1306. var.var = g;
  1307. var.decl = decl;
  1308. if (decl->init_expr != nullptr) {
  1309. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  1310. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  1311. if (tav.mode != Addressing_Invalid) {
  1312. if (tav.value.kind != ExactValue_Invalid) {
  1313. ExactValue v = tav.value;
  1314. lbValue init = lb_const_value(m, tav.type, v);
  1315. LLVMSetInitializer(g.value, init.value);
  1316. var.is_initialized = true;
  1317. }
  1318. }
  1319. }
  1320. if (!var.is_initialized &&
  1321. (is_type_untyped_nil(tav.type) || is_type_untyped_undef(tav.type))) {
  1322. var.is_initialized = true;
  1323. }
  1324. }
  1325. array_add(&global_variables, var);
  1326. lb_add_entity(m, e, g);
  1327. lb_add_member(m, name, g);
  1328. if (m->debug_builder) {
  1329. String global_name = e->token.string;
  1330. if (global_name.len != 0 && global_name != "_") {
  1331. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  1332. LLVMMetadataRef llvm_scope = llvm_file;
  1333. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  1334. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  1335. LLVMMetadataRef llvm_decl = nullptr;
  1336. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  1337. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  1338. m->debug_builder, llvm_scope,
  1339. cast(char const *)global_name.text, global_name.len,
  1340. "", 0, // linkage
  1341. llvm_file, e->token.pos.line,
  1342. lb_debug_type(m, e->type),
  1343. local_to_unit,
  1344. llvm_expr,
  1345. llvm_decl,
  1346. align_in_bits
  1347. );
  1348. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  1349. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  1350. }
  1351. }
  1352. }
  1353. TIME_SECTION("LLVM Runtime Type Information Creation");
  1354. lbProcedure *startup_type_info = lb_create_startup_type_info(default_module);
  1355. lbProcedure *objc_names = lb_create_objc_names(default_module);
  1356. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables)");
  1357. lbProcedure *startup_runtime = lb_create_startup_runtime(default_module, startup_type_info, objc_names, global_variables);
  1358. gb_unused(startup_runtime);
  1359. TIME_SECTION("LLVM Global Procedures and Types");
  1360. for_array(i, info->entities) {
  1361. Entity *e = info->entities[i];
  1362. String name = e->token.string;
  1363. Scope * scope = e->scope;
  1364. if ((scope->flags & ScopeFlag_File) == 0) {
  1365. continue;
  1366. }
  1367. Scope *package_scope = scope->parent;
  1368. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  1369. switch (e->kind) {
  1370. case Entity_Variable:
  1371. // NOTE(bill): Handled above as it requires a specific load order
  1372. continue;
  1373. case Entity_ProcGroup:
  1374. continue;
  1375. case Entity_TypeName:
  1376. case Entity_Procedure:
  1377. break;
  1378. }
  1379. bool polymorphic_struct = false;
  1380. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1381. Type *bt = base_type(e->type);
  1382. if (bt->kind == Type_Struct) {
  1383. polymorphic_struct = is_type_polymorphic(bt);
  1384. }
  1385. }
  1386. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1387. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1388. continue;
  1389. }
  1390. lbModule *m = &gen->default_module;
  1391. if (USE_SEPARATE_MODULES) {
  1392. m = lb_pkg_module(gen, e->pkg);
  1393. }
  1394. String mangled_name = lb_get_entity_name(m, e);
  1395. switch (e->kind) {
  1396. case Entity_TypeName:
  1397. lb_type(m, e->type);
  1398. break;
  1399. case Entity_Procedure:
  1400. {
  1401. lbProcedure *p = lb_create_procedure(m, e);
  1402. array_add(&m->procedures_to_generate, p);
  1403. }
  1404. break;
  1405. }
  1406. }
  1407. TIME_SECTION("LLVM Procedure Generation");
  1408. for_array(j, gen->modules.entries) {
  1409. lbModule *m = gen->modules.entries[j].value;
  1410. for_array(i, m->procedures_to_generate) {
  1411. lbProcedure *p = m->procedures_to_generate[i];
  1412. lb_generate_procedure(m, p);
  1413. }
  1414. }
  1415. if (build_context.command_kind == Command_test && !already_has_entry_point) {
  1416. TIME_SECTION("LLVM main");
  1417. lb_create_main_procedure(default_module, startup_runtime);
  1418. }
  1419. for_array(j, gen->modules.entries) {
  1420. lbModule *m = gen->modules.entries[j].value;
  1421. for_array(i, m->missing_procedures_to_check) {
  1422. lbProcedure *p = m->missing_procedures_to_check[i];
  1423. debugf("Generate missing procedure: %.*s\n", LIT(p->name));
  1424. lb_generate_procedure(m, p);
  1425. }
  1426. }
  1427. lb_finalize_objc_names(objc_names);
  1428. if (build_context.ODIN_DEBUG) {
  1429. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  1430. for_array(j, gen->modules.entries) {
  1431. lbModule *m = gen->modules.entries[j].value;
  1432. if (m->debug_builder != nullptr) {
  1433. lb_debug_complete_types(m);
  1434. LLVMDIBuilderFinalize(m->debug_builder);
  1435. }
  1436. }
  1437. }
  1438. TIME_SECTION("LLVM Function Pass");
  1439. for_array(i, gen->modules.entries) {
  1440. lbModule *m = gen->modules.entries[i].value;
  1441. lb_llvm_function_pass_worker_proc(m);
  1442. }
  1443. TIME_SECTION("LLVM Module Pass");
  1444. for_array(i, gen->modules.entries) {
  1445. lbModule *m = gen->modules.entries[i].value;
  1446. lb_run_remove_unused_function_pass(m);
  1447. lb_run_remove_unused_globals_pass(m);
  1448. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  1449. wd->m = m;
  1450. wd->target_machine = target_machines[i];
  1451. lb_llvm_module_pass_worker_proc(wd);
  1452. }
  1453. llvm_error = nullptr;
  1454. defer (LLVMDisposeMessage(llvm_error));
  1455. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  1456. if (build_context.build_mode == BuildMode_Assembly) {
  1457. code_gen_file_type = LLVMAssemblyFile;
  1458. }
  1459. for_array(j, gen->modules.entries) {
  1460. lbModule *m = gen->modules.entries[j].value;
  1461. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  1462. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1463. if (build_context.keep_temp_files) {
  1464. TIME_SECTION("LLVM Print Module to File");
  1465. String filepath_ll = lb_filepath_ll_for_module(m);
  1466. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1467. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1468. gb_exit(1);
  1469. return;
  1470. }
  1471. }
  1472. gb_exit(1);
  1473. return;
  1474. }
  1475. }
  1476. llvm_error = nullptr;
  1477. if (build_context.keep_temp_files ||
  1478. build_context.build_mode == BuildMode_LLVM_IR) {
  1479. TIME_SECTION("LLVM Print Module to File");
  1480. for_array(j, gen->modules.entries) {
  1481. lbModule *m = gen->modules.entries[j].value;
  1482. if (lb_is_module_empty(m)) {
  1483. continue;
  1484. }
  1485. String filepath_ll = lb_filepath_ll_for_module(m);
  1486. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1487. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1488. gb_exit(1);
  1489. return;
  1490. }
  1491. array_add(&gen->output_temp_paths, filepath_ll);
  1492. }
  1493. if (build_context.build_mode == BuildMode_LLVM_IR) {
  1494. gb_exit(0);
  1495. return;
  1496. }
  1497. }
  1498. TIME_SECTION("LLVM Add Foreign Library Paths");
  1499. for_array(j, gen->modules.entries) {
  1500. lbModule *m = gen->modules.entries[j].value;
  1501. for_array(i, m->info->required_foreign_imports_through_force) {
  1502. Entity *e = m->info->required_foreign_imports_through_force[i];
  1503. lb_add_foreign_library_path(m, e);
  1504. }
  1505. if (lb_is_module_empty(m)) {
  1506. continue;
  1507. }
  1508. }
  1509. TIME_SECTION("LLVM Object Generation");
  1510. isize non_empty_module_count = 0;
  1511. for_array(j, gen->modules.entries) {
  1512. lbModule *m = gen->modules.entries[j].value;
  1513. if (!lb_is_module_empty(m)) {
  1514. non_empty_module_count += 1;
  1515. }
  1516. }
  1517. if (do_threading && non_empty_module_count > 1) {
  1518. for_array(j, gen->modules.entries) {
  1519. lbModule *m = gen->modules.entries[j].value;
  1520. if (lb_is_module_empty(m)) {
  1521. continue;
  1522. }
  1523. String filepath_ll = lb_filepath_ll_for_module(m);
  1524. String filepath_obj = lb_filepath_obj_for_module(m);
  1525. array_add(&gen->output_object_paths, filepath_obj);
  1526. array_add(&gen->output_temp_paths, filepath_ll);
  1527. auto *wd = gb_alloc_item(permanent_allocator(), lbLLVMEmitWorker);
  1528. wd->target_machine = target_machines[j];
  1529. wd->code_gen_file_type = code_gen_file_type;
  1530. wd->filepath_obj = filepath_obj;
  1531. wd->m = m;
  1532. global_thread_pool_add_task(lb_llvm_emit_worker_proc, wd);
  1533. }
  1534. thread_pool_wait(&global_thread_pool);
  1535. } else {
  1536. for_array(j, gen->modules.entries) {
  1537. lbModule *m = gen->modules.entries[j].value;
  1538. if (lb_is_module_empty(m)) {
  1539. continue;
  1540. }
  1541. String filepath_obj = lb_filepath_obj_for_module(m);
  1542. array_add(&gen->output_object_paths, filepath_obj);
  1543. String short_name = remove_directory_from_path(filepath_obj);
  1544. gbString section_name = gb_string_make(heap_allocator(), "LLVM Generate Object: ");
  1545. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  1546. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  1547. if (LLVMTargetMachineEmitToFile(target_machines[j], m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  1548. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1549. gb_exit(1);
  1550. return;
  1551. }
  1552. }
  1553. }
  1554. }