llvm_backend.cpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007
  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. String get_default_microarchitecture() {
  20. String default_march = str_lit("generic");
  21. if (build_context.metrics.arch == TargetArch_amd64) {
  22. // NOTE(bill): x86-64-v2 is more than enough for everyone
  23. //
  24. // x86-64: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
  25. // x86-64-v2: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
  26. // x86-64-v3: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
  27. // x86-64-v4: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
  28. if (ODIN_LLVM_MINIMUM_VERSION_12) {
  29. if (build_context.metrics.os == TargetOs_freestanding) {
  30. default_march = str_lit("x86-64");
  31. } else {
  32. default_march = str_lit("x86-64-v2");
  33. }
  34. }
  35. }
  36. return default_march;
  37. }
  38. String get_final_microarchitecture() {
  39. BuildContext *bc = &build_context;
  40. String microarch = bc->microarch;
  41. if (microarch.len == 0) {
  42. microarch = get_default_microarchitecture();
  43. } else if (microarch == str_lit("native")) {
  44. microarch = make_string_c(LLVMGetHostCPUName());
  45. }
  46. return microarch;
  47. }
  48. gb_internal String get_default_features() {
  49. BuildContext *bc = &build_context;
  50. int off = 0;
  51. for (int i = 0; i < bc->metrics.arch; i += 1) {
  52. off += target_microarch_counts[i];
  53. }
  54. String microarch = get_final_microarchitecture();
  55. for (int i = off; i < off+target_microarch_counts[bc->metrics.arch]; i += 1) {
  56. if (microarch_features_list[i].microarch == microarch) {
  57. return microarch_features_list[i].features;
  58. }
  59. }
  60. GB_PANIC("unknown microarch");
  61. return {};
  62. }
  63. gb_internal void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  64. if (e == nullptr) {
  65. return;
  66. }
  67. GB_ASSERT(e->kind == Entity_LibraryName);
  68. GB_ASSERT(e->flags & EntityFlag_Used);
  69. mutex_lock(&m->gen->foreign_mutex);
  70. if (!ptr_set_update(&m->gen->foreign_libraries_set, e)) {
  71. array_add(&m->gen->foreign_libraries, e);
  72. }
  73. mutex_unlock(&m->gen->foreign_mutex);
  74. }
  75. gb_internal GB_COMPARE_PROC(foreign_library_cmp) {
  76. int cmp = 0;
  77. Entity *x = *(Entity **)a;
  78. Entity *y = *(Entity **)b;
  79. if (x == y) {
  80. return 0;
  81. }
  82. GB_ASSERT(x->kind == Entity_LibraryName);
  83. GB_ASSERT(y->kind == Entity_LibraryName);
  84. cmp = i64_cmp(x->LibraryName.priority_index, y->LibraryName.priority_index);
  85. if (cmp) {
  86. return cmp;
  87. }
  88. if (x->pkg != y->pkg) {
  89. isize order_x = x->pkg ? x->pkg->order : 0;
  90. isize order_y = y->pkg ? y->pkg->order : 0;
  91. cmp = isize_cmp(order_x, order_y);
  92. if (cmp) {
  93. return cmp;
  94. }
  95. }
  96. if (x->file != y->file) {
  97. String fullpath_x = x->file ? x->file->fullpath : (String{});
  98. String fullpath_y = y->file ? y->file->fullpath : (String{});
  99. String file_x = filename_from_path(fullpath_x);
  100. String file_y = filename_from_path(fullpath_y);
  101. cmp = string_compare(file_x, file_y);
  102. if (cmp) {
  103. return cmp;
  104. }
  105. }
  106. cmp = u64_cmp(x->order_in_src, y->order_in_src);
  107. if (cmp) {
  108. return cmp;
  109. }
  110. return i32_cmp(x->token.pos.offset, y->token.pos.offset);
  111. }
  112. gb_internal void lb_set_entity_from_other_modules_linkage_correctly(lbModule *other_module, Entity *e, String const &name) {
  113. if (other_module == nullptr) {
  114. return;
  115. }
  116. char const *cname = alloc_cstring(temporary_allocator(), name);
  117. LLVMValueRef other_global = nullptr;
  118. if (e->kind == Entity_Variable) {
  119. other_global = LLVMGetNamedGlobal(other_module->mod, cname);
  120. } else if (e->kind == Entity_Procedure) {
  121. other_global = LLVMGetNamedFunction(other_module->mod, cname);
  122. }
  123. if (other_global) {
  124. LLVMSetLinkage(other_global, LLVMExternalLinkage);
  125. }
  126. }
  127. gb_internal void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  128. TEMPORARY_ALLOCATOR_GUARD();
  129. GB_ASSERT(addr.kind == lbAddr_Context);
  130. GB_ASSERT(addr.ctx.sel.index.count == 0);
  131. auto args = array_make<lbValue>(temporary_allocator(), 1);
  132. args[0] = addr.addr;
  133. lb_emit_runtime_call(p, "__init_context", args);
  134. }
  135. gb_internal lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  136. Type *pt = base_type(p->type);
  137. GB_ASSERT(pt->kind == Type_Proc);
  138. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  139. String name = str_lit("__.context_ptr");
  140. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  141. e->flags |= EntityFlag_NoAlias;
  142. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  143. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  144. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  145. lbValue param = {context_ptr, e->type};
  146. lb_add_entity(p->module, e, param);
  147. lbAddr ctx_addr = {};
  148. ctx_addr.kind = lbAddr_Context;
  149. ctx_addr.addr = param;
  150. lbContextData *cd = array_add_and_get(&p->context_stack);
  151. cd->ctx = ctx_addr;
  152. cd->scope_index = -1;
  153. cd->uses = +1; // make sure it has been used already
  154. return cd;
  155. }
  156. gb_internal lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  157. ctx.kind = lbAddr_Context;
  158. lbContextData *cd = array_add_and_get(&p->context_stack);
  159. cd->ctx = ctx;
  160. cd->scope_index = p->scope_index;
  161. return cd;
  162. }
  163. gb_internal lbValue lb_equal_proc_for_type(lbModule *m, Type *type) {
  164. type = base_type(type);
  165. GB_ASSERT(is_type_comparable(type));
  166. Type *pt = alloc_type_pointer(type);
  167. LLVMTypeRef ptr_type = lb_type(m, pt);
  168. lbProcedure **found = map_get(&m->equal_procs, type);
  169. lbProcedure *compare_proc = nullptr;
  170. if (found) {
  171. compare_proc = *found;
  172. GB_ASSERT(compare_proc != nullptr);
  173. return {compare_proc->value, compare_proc->type};
  174. }
  175. static std::atomic<u32> proc_index;
  176. char buf[32] = {};
  177. isize n = gb_snprintf(buf, 32, "__$equal%u", 1+proc_index.fetch_add(1));
  178. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  179. String proc_name = make_string_c(str);
  180. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  181. map_set(&m->equal_procs, type, p);
  182. lb_begin_procedure_body(p);
  183. // lb_add_attribute_to_proc(m, p->value, "readonly");
  184. lb_add_attribute_to_proc(m, p->value, "nounwind");
  185. LLVMValueRef x = LLVMGetParam(p->value, 0);
  186. LLVMValueRef y = LLVMGetParam(p->value, 1);
  187. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  188. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  189. lbValue lhs = {x, pt};
  190. lbValue rhs = {y, pt};
  191. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  192. lb_add_proc_attribute_at_index(p, 1+1, "nonnull");
  193. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  194. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  195. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  196. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  197. lb_start_block(p, block_same_ptr);
  198. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  199. lb_start_block(p, block_diff_ptr);
  200. if (type->kind == Type_Struct) {
  201. type_set_offsets(type);
  202. lbBlock *block_false = lb_create_block(p, "bfalse");
  203. lbValue res = lb_const_bool(m, t_bool, true);
  204. for_array(i, type->Struct.fields) {
  205. lbBlock *next_block = lb_create_block(p, "btrue");
  206. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  207. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  208. lbValue left = lb_emit_load(p, pleft);
  209. lbValue right = lb_emit_load(p, pright);
  210. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  211. lb_emit_if(p, ok, next_block, block_false);
  212. lb_emit_jump(p, next_block);
  213. lb_start_block(p, next_block);
  214. }
  215. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  216. lb_start_block(p, block_false);
  217. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  218. } else if (type->kind == Type_Union) {
  219. if (type_size_of(type) == 0) {
  220. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  221. } else if (is_type_union_maybe_pointer(type)) {
  222. Type *v = type->Union.variants[0];
  223. Type *pv = alloc_type_pointer(v);
  224. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  225. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  226. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  227. ok = lb_emit_conv(p, ok, t_bool);
  228. LLVMBuildRet(p->builder, ok.value);
  229. } else {
  230. lbBlock *block_false = lb_create_block(p, "bfalse");
  231. lbBlock *block_switch = lb_create_block(p, "bswitch");
  232. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  233. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  234. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  235. lb_emit_if(p, tag_eq, block_switch, block_false);
  236. lb_start_block(p, block_switch);
  237. unsigned variant_count = cast(unsigned)type->Union.variants.count;
  238. if (type->Union.kind != UnionType_no_nil) {
  239. variant_count += 1;
  240. }
  241. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, variant_count);
  242. if (type->Union.kind != UnionType_no_nil) {
  243. lbBlock *case_block = lb_create_block(p, "bcase");
  244. lb_start_block(p, case_block);
  245. lbValue case_tag = lb_const_int(p->module, union_tag_type(type), 0);
  246. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  247. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  248. }
  249. for (Type *v : type->Union.variants) {
  250. lbBlock *case_block = lb_create_block(p, "bcase");
  251. lb_start_block(p, case_block);
  252. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  253. Type *vp = alloc_type_pointer(v);
  254. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  255. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  256. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  257. ok = lb_emit_conv(p, ok, t_bool);
  258. LLVMBuildRet(p->builder, ok.value);
  259. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  260. }
  261. lb_start_block(p, block_false);
  262. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  263. }
  264. } else {
  265. lbValue left = lb_emit_load(p, lhs);
  266. lbValue right = lb_emit_load(p, rhs);
  267. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  268. ok = lb_emit_conv(p, ok, t_bool);
  269. LLVMBuildRet(p->builder, ok.value);
  270. }
  271. lb_end_procedure_body(p);
  272. compare_proc = p;
  273. return {compare_proc->value, compare_proc->type};
  274. }
  275. gb_internal lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  276. TEMPORARY_ALLOCATOR_GUARD();
  277. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  278. auto args = array_make<lbValue>(temporary_allocator(), 3);
  279. args[0] = data;
  280. args[1] = seed;
  281. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  282. return lb_emit_runtime_call(p, "default_hasher", args);
  283. }
  284. gb_internal void lb_add_callsite_force_inline(lbProcedure *p, lbValue ret_value) {
  285. LLVMAddCallSiteAttribute(ret_value.value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  286. }
  287. gb_internal lbValue lb_hasher_proc_for_type(lbModule *m, Type *type) {
  288. type = core_type(type);
  289. GB_ASSERT_MSG(is_type_comparable(type), "%s", type_to_string(type));
  290. Type *pt = alloc_type_pointer(type);
  291. lbProcedure **found = map_get(&m->hasher_procs, type);
  292. if (found) {
  293. GB_ASSERT(*found != nullptr);
  294. return {(*found)->value, (*found)->type};
  295. }
  296. static std::atomic<u32> proc_index;
  297. char buf[32] = {};
  298. isize n = gb_snprintf(buf, 32, "__$hasher%u", 1+proc_index.fetch_add(1));
  299. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  300. String proc_name = make_string_c(str);
  301. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  302. map_set(&m->hasher_procs, type, p);
  303. lb_begin_procedure_body(p);
  304. defer (lb_end_procedure_body(p));
  305. // lb_add_attribute_to_proc(m, p->value, "readonly");
  306. lb_add_attribute_to_proc(m, p->value, "nounwind");
  307. LLVMValueRef x = LLVMGetParam(p->value, 0);
  308. LLVMValueRef y = LLVMGetParam(p->value, 1);
  309. lbValue data = {x, t_rawptr};
  310. lbValue seed = {y, t_uintptr};
  311. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  312. // lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  313. if (is_type_simple_compare(type)) {
  314. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  315. lb_add_callsite_force_inline(p, res);
  316. LLVMBuildRet(p->builder, res.value);
  317. return {p->value, p->type};
  318. }
  319. TEMPORARY_ALLOCATOR_GUARD();
  320. if (type->kind == Type_Struct) {
  321. type_set_offsets(type);
  322. data = lb_emit_conv(p, data, t_u8_ptr);
  323. auto args = array_make<lbValue>(temporary_allocator(), 2);
  324. for_array(i, type->Struct.fields) {
  325. GB_ASSERT(type->Struct.offsets != nullptr);
  326. i64 offset = type->Struct.offsets[i];
  327. Entity *field = type->Struct.fields[i];
  328. lbValue field_hasher = lb_hasher_proc_for_type(m, field->type);
  329. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  330. args[0] = ptr;
  331. args[1] = seed;
  332. seed = lb_emit_call(p, field_hasher, args);
  333. }
  334. LLVMBuildRet(p->builder, seed.value);
  335. } else if (type->kind == Type_Union) {
  336. auto args = array_make<lbValue>(temporary_allocator(), 2);
  337. if (is_type_union_maybe_pointer(type)) {
  338. Type *v = type->Union.variants[0];
  339. lbValue variant_hasher = lb_hasher_proc_for_type(m, v);
  340. args[0] = data;
  341. args[1] = seed;
  342. lbValue res = lb_emit_call(p, variant_hasher, args);
  343. lb_add_callsite_force_inline(p, res);
  344. LLVMBuildRet(p->builder, res.value);
  345. }
  346. lbBlock *end_block = lb_create_block(p, "bend");
  347. data = lb_emit_conv(p, data, pt);
  348. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  349. lbValue tag = lb_emit_load(p, tag_ptr);
  350. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  351. for (Type *v : type->Union.variants) {
  352. lbBlock *case_block = lb_create_block(p, "bcase");
  353. lb_start_block(p, case_block);
  354. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  355. lbValue variant_hasher = lb_hasher_proc_for_type(m, v);
  356. args[0] = data;
  357. args[1] = seed;
  358. lbValue res = lb_emit_call(p, variant_hasher, args);
  359. LLVMBuildRet(p->builder, res.value);
  360. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  361. }
  362. lb_start_block(p, end_block);
  363. LLVMBuildRet(p->builder, seed.value);
  364. } else if (type->kind == Type_Array) {
  365. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  366. lb_addr_store(p, pres, seed);
  367. auto args = array_make<lbValue>(temporary_allocator(), 2);
  368. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->Array.elem);
  369. auto loop_data = lb_loop_start(p, cast(isize)type->Array.count, t_i32);
  370. data = lb_emit_conv(p, data, pt);
  371. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  372. args[0] = ptr;
  373. args[1] = lb_addr_load(p, pres);
  374. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  375. lb_addr_store(p, pres, new_seed);
  376. lb_loop_end(p, loop_data);
  377. lbValue res = lb_addr_load(p, pres);
  378. LLVMBuildRet(p->builder, res.value);
  379. } else if (type->kind == Type_EnumeratedArray) {
  380. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  381. lb_addr_store(p, res, seed);
  382. auto args = array_make<lbValue>(temporary_allocator(), 2);
  383. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  384. auto loop_data = lb_loop_start(p, cast(isize)type->EnumeratedArray.count, t_i32);
  385. data = lb_emit_conv(p, data, pt);
  386. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  387. args[0] = ptr;
  388. args[1] = lb_addr_load(p, res);
  389. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  390. lb_addr_store(p, res, new_seed);
  391. lb_loop_end(p, loop_data);
  392. lbValue vres = lb_addr_load(p, res);
  393. LLVMBuildRet(p->builder, vres.value);
  394. } else if (is_type_cstring(type)) {
  395. auto args = array_make<lbValue>(temporary_allocator(), 2);
  396. args[0] = data;
  397. args[1] = seed;
  398. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  399. lb_add_callsite_force_inline(p, res);
  400. LLVMBuildRet(p->builder, res.value);
  401. } else if (is_type_string(type)) {
  402. auto args = array_make<lbValue>(temporary_allocator(), 2);
  403. args[0] = data;
  404. args[1] = seed;
  405. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  406. lb_add_callsite_force_inline(p, res);
  407. LLVMBuildRet(p->builder, res.value);
  408. } else {
  409. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  410. }
  411. return {p->value, p->type};
  412. }
  413. #define LLVM_SET_VALUE_NAME(value, name) LLVMSetValueName2((value), (name), gb_count_of((name))-1);
  414. gb_internal lbValue lb_map_get_proc_for_type(lbModule *m, Type *type) {
  415. GB_ASSERT(!build_context.dynamic_map_calls);
  416. type = base_type(type);
  417. GB_ASSERT(type->kind == Type_Map);
  418. lbProcedure **found = map_get(&m->map_get_procs, type);
  419. if (found) {
  420. GB_ASSERT(*found != nullptr);
  421. return {(*found)->value, (*found)->type};
  422. }
  423. static std::atomic<u32> proc_index;
  424. char buf[32] = {};
  425. isize n = gb_snprintf(buf, 32, "__$map_get-%u", 1+proc_index.fetch_add(1));
  426. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  427. String proc_name = make_string_c(str);
  428. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_get_proc);
  429. map_set(&m->map_get_procs, type, p);
  430. lb_begin_procedure_body(p);
  431. defer (lb_end_procedure_body(p));
  432. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  433. lb_add_attribute_to_proc(m, p->value, "nounwind");
  434. if (build_context.ODIN_DEBUG) {
  435. lb_add_attribute_to_proc(m, p->value, "noinline");
  436. }
  437. LLVMValueRef x = LLVMGetParam(p->value, 0);
  438. LLVMValueRef y = LLVMGetParam(p->value, 1);
  439. LLVMValueRef z = LLVMGetParam(p->value, 2);
  440. lbValue map_ptr = {x, t_rawptr};
  441. lbValue h = {y, t_uintptr};
  442. lbValue key_ptr = {z, t_rawptr};
  443. LLVM_SET_VALUE_NAME(h.value, "hash");
  444. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  445. lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  446. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  447. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  448. lbBlock *loop_block = lb_create_block(p, "loop");
  449. lbBlock *hash_block = lb_create_block(p, "hash");
  450. lbBlock *probe_block = lb_create_block(p, "probe");
  451. lbBlock *increment_block = lb_create_block(p, "increment");
  452. lbBlock *hash_compare_block = lb_create_block(p, "hash_compare");
  453. lbBlock *key_compare_block = lb_create_block(p, "key_compare");
  454. lbBlock *value_block = lb_create_block(p, "value");
  455. lbBlock *nil_block = lb_create_block(p, "nil");
  456. map_ptr = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  457. LLVM_SET_VALUE_NAME(map_ptr.value, "map_ptr");
  458. lbValue map = lb_emit_load(p, map_ptr);
  459. LLVM_SET_VALUE_NAME(map.value, "map");
  460. lbValue length = lb_map_len(p, map);
  461. LLVM_SET_VALUE_NAME(length.value, "length");
  462. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, length, lb_const_nil(m, t_int)), nil_block, hash_block);
  463. lb_start_block(p, hash_block);
  464. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  465. LLVM_SET_VALUE_NAME(key_ptr.value, "key_ptr");
  466. lbValue key = lb_emit_load(p, key_ptr);
  467. LLVM_SET_VALUE_NAME(key.value, "key");
  468. lbAddr pos = lb_add_local_generated(p, t_uintptr, false);
  469. lbAddr distance = lb_add_local_generated(p, t_uintptr, true);
  470. LLVM_SET_VALUE_NAME(pos.addr.value, "pos");
  471. LLVM_SET_VALUE_NAME(distance.addr.value, "distance");
  472. lbValue capacity = lb_map_cap(p, map);
  473. LLVM_SET_VALUE_NAME(capacity.value, "capacity");
  474. lbValue cap_minus_1 = lb_emit_arith(p, Token_Sub, capacity, lb_const_int(m, t_int, 1), t_int);
  475. lbValue mask = lb_emit_conv(p, cap_minus_1, t_uintptr);
  476. LLVM_SET_VALUE_NAME(mask.value, "mask");
  477. {
  478. // map_desired_position inlined
  479. lbValue the_pos = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  480. the_pos = lb_emit_conv(p, the_pos, t_uintptr);
  481. lb_addr_store(p, pos, the_pos);
  482. }
  483. lbValue zero_uintptr = lb_const_int(m, t_uintptr, 0);
  484. lbValue one_uintptr = lb_const_int(m, t_uintptr, 1);
  485. lbValue ks = lb_map_data_uintptr(p, map);
  486. lbValue vs = lb_map_cell_index_static(p, type->Map.key, ks, capacity);
  487. lbValue hs = lb_map_cell_index_static(p, type->Map.value, vs, capacity);
  488. ks = lb_emit_conv(p, ks, alloc_type_pointer(type->Map.key));
  489. vs = lb_emit_conv(p, vs, alloc_type_pointer(type->Map.value));
  490. hs = lb_emit_conv(p, hs, alloc_type_pointer(t_uintptr));
  491. LLVM_SET_VALUE_NAME(ks.value, "ks");
  492. LLVM_SET_VALUE_NAME(vs.value, "vs");
  493. LLVM_SET_VALUE_NAME(hs.value, "hs");
  494. lb_emit_jump(p, loop_block);
  495. lb_start_block(p, loop_block);
  496. lbValue element_hash = lb_emit_load(p, lb_emit_ptr_offset(p, hs, lb_addr_load(p, pos)));
  497. LLVM_SET_VALUE_NAME(element_hash.value, "element_hash");
  498. {
  499. // if element_hash == 0 { return nil }
  500. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, zero_uintptr), nil_block, probe_block);
  501. }
  502. lb_start_block(p, probe_block);
  503. {
  504. // map_probe_distance inlined
  505. lbValue probe_distance = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  506. probe_distance = lb_emit_conv(p, probe_distance, t_uintptr);
  507. lbValue cap = lb_emit_conv(p, capacity, t_uintptr);
  508. lbValue base = lb_emit_arith(p, Token_Add, lb_addr_load(p, pos), cap, t_uintptr);
  509. probe_distance = lb_emit_arith(p, Token_Sub, base, probe_distance, t_uintptr);
  510. probe_distance = lb_emit_arith(p, Token_And, probe_distance, mask, t_uintptr);
  511. LLVM_SET_VALUE_NAME(probe_distance.value, "probe_distance");
  512. lbValue cond = lb_emit_comp(p, Token_Gt, lb_addr_load(p, distance), probe_distance);
  513. lb_emit_if(p, cond, nil_block, hash_compare_block);
  514. }
  515. lb_start_block(p, hash_compare_block);
  516. {
  517. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, h), key_compare_block, increment_block);
  518. }
  519. lb_start_block(p, key_compare_block);
  520. {
  521. lbValue element_key = lb_map_cell_index_static(p, type->Map.key, ks, lb_addr_load(p, pos));
  522. element_key = lb_emit_conv(p, element_key, ks.type);
  523. LLVM_SET_VALUE_NAME(element_key.value, "element_key_ptr");
  524. lbValue cond = lb_emit_comp(p, Token_CmpEq, lb_emit_load(p, element_key), key);
  525. lb_emit_if(p, cond, value_block, increment_block);
  526. }
  527. lb_start_block(p, value_block);
  528. {
  529. lbValue element_value = lb_map_cell_index_static(p, type->Map.value, vs, lb_addr_load(p, pos));
  530. LLVM_SET_VALUE_NAME(element_value.value, "element_value_ptr");
  531. element_value = lb_emit_conv(p, element_value, t_rawptr);
  532. LLVMBuildRet(p->builder, element_value.value);
  533. }
  534. lb_start_block(p, increment_block);
  535. {
  536. lbValue pp = lb_addr_load(p, pos);
  537. pp = lb_emit_arith(p, Token_Add, pp, one_uintptr, t_uintptr);
  538. pp = lb_emit_arith(p, Token_And, pp, mask, t_uintptr);
  539. lb_addr_store(p, pos, pp);
  540. lb_emit_increment(p, distance.addr);
  541. }
  542. lb_emit_jump(p, loop_block);
  543. lb_start_block(p, nil_block);
  544. {
  545. lbValue res = lb_const_nil(m, t_rawptr);
  546. LLVMBuildRet(p->builder, res.value);
  547. }
  548. // gb_printf_err("%s\n", LLVMPrintValueToString(p->value));
  549. return {p->value, p->type};
  550. }
  551. // gb_internal void lb_debug_print(lbProcedure *p, String const &str) {
  552. // auto args = array_make<lbValue>(heap_allocator(), 1);
  553. // args[0] = lb_const_string(p->module, str);
  554. // lb_emit_runtime_call(p, "print_string", args);
  555. // }
  556. gb_internal lbValue lb_map_set_proc_for_type(lbModule *m, Type *type) {
  557. TEMPORARY_ALLOCATOR_GUARD();
  558. GB_ASSERT(!build_context.dynamic_map_calls);
  559. type = base_type(type);
  560. GB_ASSERT(type->kind == Type_Map);
  561. lbProcedure **found = map_get(&m->map_set_procs, type);
  562. if (found) {
  563. GB_ASSERT(*found != nullptr);
  564. return {(*found)->value, (*found)->type};
  565. }
  566. static std::atomic<u32> proc_index;
  567. char buf[32] = {};
  568. isize n = gb_snprintf(buf, 32, "__$map_set-%u", 1+proc_index.fetch_add(1));
  569. char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1);
  570. String proc_name = make_string_c(str);
  571. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_set_proc);
  572. map_set(&m->map_set_procs, type, p);
  573. lb_begin_procedure_body(p);
  574. defer (lb_end_procedure_body(p));
  575. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  576. lb_add_attribute_to_proc(m, p->value, "nounwind");
  577. if (build_context.ODIN_DEBUG) {
  578. lb_add_attribute_to_proc(m, p->value, "noinline");
  579. }
  580. lbValue map_ptr = {LLVMGetParam(p->value, 0), t_rawptr};
  581. lbValue hash_param = {LLVMGetParam(p->value, 1), t_uintptr};
  582. lbValue key_ptr = {LLVMGetParam(p->value, 2), t_rawptr};
  583. lbValue value_ptr = {LLVMGetParam(p->value, 3), t_rawptr};
  584. lbValue location_ptr = {LLVMGetParam(p->value, 4), t_source_code_location_ptr};
  585. map_ptr = lb_emit_conv(p, map_ptr, alloc_type_pointer(type));
  586. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  587. LLVM_SET_VALUE_NAME(map_ptr.value, "map_ptr");
  588. LLVM_SET_VALUE_NAME(hash_param.value, "hash_param");
  589. LLVM_SET_VALUE_NAME(key_ptr.value, "key_ptr");
  590. LLVM_SET_VALUE_NAME(value_ptr.value, "value_ptr");
  591. LLVM_SET_VALUE_NAME(location_ptr.value, "location");
  592. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  593. lb_add_proc_attribute_at_index(p, 1+0, "noalias");
  594. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  595. if (!are_types_identical(type->Map.key, type->Map.value)) {
  596. lb_add_proc_attribute_at_index(p, 1+2, "noalias");
  597. }
  598. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  599. lb_add_proc_attribute_at_index(p, 1+3, "nonnull");
  600. if (!are_types_identical(type->Map.key, type->Map.value)) {
  601. lb_add_proc_attribute_at_index(p, 1+3, "noalias");
  602. }
  603. lb_add_proc_attribute_at_index(p, 1+3, "readonly");
  604. lb_add_proc_attribute_at_index(p, 1+4, "nonnull");
  605. lb_add_proc_attribute_at_index(p, 1+4, "noalias");
  606. lb_add_proc_attribute_at_index(p, 1+4, "readonly");
  607. lbAddr hash_addr = lb_add_local_generated(p, t_uintptr, false);
  608. lb_addr_store(p, hash_addr, hash_param);
  609. LLVM_SET_VALUE_NAME(hash_addr.addr.value, "hash");
  610. ////
  611. lbValue found_ptr = {};
  612. {
  613. lbValue map_get_proc = lb_map_get_proc_for_type(m, type);
  614. auto args = array_make<lbValue>(temporary_allocator(), 3);
  615. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  616. args[1] = lb_addr_load(p, hash_addr);
  617. args[2] = key_ptr;
  618. found_ptr = lb_emit_call(p, map_get_proc, args);
  619. }
  620. LLVM_SET_VALUE_NAME(found_ptr.value, "found_ptr");
  621. lbBlock *found_block = lb_create_block(p, "found");
  622. lbBlock *check_grow_block = lb_create_block(p, "check-grow");
  623. lbBlock *grow_fail_block = lb_create_block(p, "grow-fail");
  624. lbBlock *insert_block = lb_create_block(p, "insert");
  625. lbBlock *check_has_grown_block = lb_create_block(p, "check-has-grown");
  626. lbBlock *rehash_block = lb_create_block(p, "rehash");
  627. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, found_ptr), found_block, check_grow_block);
  628. lb_start_block(p, found_block);
  629. {
  630. lb_mem_copy_non_overlapping(p, found_ptr, value_ptr, lb_const_int(m, t_int, type_size_of(type->Map.value)));
  631. LLVMBuildRet(p->builder, lb_emit_conv(p, found_ptr, t_rawptr).value);
  632. }
  633. lb_start_block(p, check_grow_block);
  634. lbValue map_info = lb_gen_map_info_ptr(p->module, type);
  635. LLVM_SET_VALUE_NAME(map_info.value, "map_info");
  636. {
  637. auto args = array_make<lbValue>(temporary_allocator(), 3);
  638. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  639. args[1] = map_info;
  640. args[2] = lb_emit_load(p, location_ptr);
  641. lbValue grow_err_and_has_grown = lb_emit_runtime_call(p, "__dynamic_map_check_grow", args);
  642. lbValue grow_err = lb_emit_struct_ev(p, grow_err_and_has_grown, 0);
  643. lbValue has_grown = lb_emit_struct_ev(p, grow_err_and_has_grown, 1);
  644. LLVM_SET_VALUE_NAME(grow_err.value, "grow_err");
  645. LLVM_SET_VALUE_NAME(has_grown.value, "has_grown");
  646. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, grow_err), grow_fail_block, check_has_grown_block);
  647. lb_start_block(p, grow_fail_block);
  648. LLVMBuildRet(p->builder, LLVMConstNull(lb_type(m, t_rawptr)));
  649. lb_start_block(p, check_has_grown_block);
  650. lb_emit_if(p, has_grown, rehash_block, insert_block);
  651. lb_start_block(p, rehash_block);
  652. lbValue key = lb_emit_load(p, key_ptr);
  653. lbValue new_hash = lb_gen_map_key_hash(p, map_ptr, key, nullptr);
  654. LLVM_SET_VALUE_NAME(new_hash.value, "new_hash");
  655. lb_addr_store(p, hash_addr, new_hash);
  656. lb_emit_jump(p, insert_block);
  657. }
  658. lb_start_block(p, insert_block);
  659. {
  660. auto args = array_make<lbValue>(temporary_allocator(), 5);
  661. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  662. args[1] = map_info;
  663. args[2] = lb_addr_load(p, hash_addr);
  664. args[3] = lb_emit_conv(p, key_ptr, t_uintptr);
  665. args[4] = lb_emit_conv(p, value_ptr, t_uintptr);
  666. lbValue result = lb_emit_runtime_call(p, "map_insert_hash_dynamic", args);
  667. lb_emit_increment(p, lb_map_len_ptr(p, map_ptr));
  668. LLVMBuildRet(p->builder, lb_emit_conv(p, result, t_rawptr).value);
  669. }
  670. return {p->value, p->type};
  671. }
  672. gb_internal lbValue lb_gen_map_cell_info_ptr(lbModule *m, Type *type) {
  673. lbAddr *found = map_get(&m->map_cell_info_map, type);
  674. if (found) {
  675. return found->addr;
  676. }
  677. i64 size = 0, len = 0;
  678. map_cell_size_and_len(type, &size, &len);
  679. LLVMValueRef const_values[4] = {};
  680. const_values[0] = lb_const_int(m, t_uintptr, type_size_of(type)).value;
  681. const_values[1] = lb_const_int(m, t_uintptr, type_align_of(type)).value;
  682. const_values[2] = lb_const_int(m, t_uintptr, size).value;
  683. const_values[3] = lb_const_int(m, t_uintptr, len).value;
  684. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_cell_info, const_values, gb_count_of(const_values));
  685. lbValue res = {llvm_res, t_map_cell_info};
  686. lbAddr addr = lb_add_global_generated(m, t_map_cell_info, res, nullptr);
  687. lb_make_global_private_const(addr);
  688. map_set(&m->map_cell_info_map, type, addr);
  689. return addr.addr;
  690. }
  691. gb_internal lbValue lb_gen_map_info_ptr(lbModule *m, Type *map_type) {
  692. map_type = base_type(map_type);
  693. GB_ASSERT(map_type->kind == Type_Map);
  694. lbAddr *found = map_get(&m->map_info_map, map_type);
  695. if (found) {
  696. return found->addr;
  697. }
  698. GB_ASSERT(t_map_info != nullptr);
  699. GB_ASSERT(t_map_cell_info != nullptr);
  700. LLVMValueRef key_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.key).value;
  701. LLVMValueRef value_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.value).value;
  702. LLVMValueRef const_values[4] = {};
  703. const_values[0] = key_cell_info;
  704. const_values[1] = value_cell_info;
  705. const_values[2] = lb_hasher_proc_for_type(m, map_type->Map.key).value;
  706. const_values[3] = lb_equal_proc_for_type(m, map_type->Map.key).value;
  707. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_info, const_values, gb_count_of(const_values));
  708. lbValue res = {llvm_res, t_map_info};
  709. lbAddr addr = lb_add_global_generated(m, t_map_info, res, nullptr);
  710. lb_make_global_private_const(addr);
  711. map_set(&m->map_info_map, map_type, addr);
  712. return addr.addr;
  713. }
  714. gb_internal lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  715. if (true) {
  716. return {};
  717. }
  718. lbValue hashed_key = {};
  719. #if 0
  720. if (lb_is_const(key)) {
  721. u64 hash = 0xcbf29ce484222325;
  722. if (is_type_cstring(key_type)) {
  723. size_t length = 0;
  724. char const *text = LLVMGetAsString(key.value, &length);
  725. hash = fnv64a(text, cast(isize)length);
  726. } else if (is_type_string(key_type)) {
  727. unsigned data_indices[] = {0};
  728. unsigned len_indices[] = {1};
  729. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  730. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  731. i64 length = LLVMConstIntGetSExtValue(len);
  732. char const *text = nullptr;
  733. if (false && length != 0) {
  734. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  735. return {};
  736. }
  737. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  738. size_t ulength = 0;
  739. text = LLVMGetAsString(data, &ulength);
  740. gb_printf_err("%lld %llu %s\n", length, ulength, text);
  741. length = gb_min(length, cast(i64)ulength);
  742. }
  743. hash = fnv64a(text, cast(isize)length);
  744. } else {
  745. return {};
  746. }
  747. // TODO(bill): other const hash types
  748. if (build_context.word_size == 4) {
  749. hash &= 0xffffffffull;
  750. }
  751. hashed_key = lb_const_int(m, t_uintptr, hash);
  752. }
  753. #endif
  754. return hashed_key;
  755. }
  756. gb_internal lbValue lb_gen_map_key_hash(lbProcedure *p, lbValue const &map_ptr, lbValue key, lbValue *key_ptr_) {
  757. TEMPORARY_ALLOCATOR_GUARD();
  758. lbValue key_ptr = lb_address_from_load_or_generate_local(p, key);
  759. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  760. if (key_ptr_) *key_ptr_ = key_ptr;
  761. Type* key_type = base_type(type_deref(map_ptr.type))->Map.key;
  762. lbValue hashed_key = lb_const_hash(p->module, key, key_type);
  763. if (hashed_key.value == nullptr) {
  764. lbValue hasher = lb_hasher_proc_for_type(p->module, key_type);
  765. lbValue seed = {};
  766. {
  767. auto args = array_make<lbValue>(temporary_allocator(), 1);
  768. args[0] = lb_map_data_uintptr(p, lb_emit_load(p, map_ptr));
  769. seed = lb_emit_runtime_call(p, "map_seed_from_map_data", args);
  770. }
  771. auto args = array_make<lbValue>(temporary_allocator(), 2);
  772. args[0] = key_ptr;
  773. args[1] = seed;
  774. hashed_key = lb_emit_call(p, hasher, args);
  775. }
  776. return hashed_key;
  777. }
  778. gb_internal lbValue lb_internal_dynamic_map_get_ptr(lbProcedure *p, lbValue const &map_ptr, lbValue const &key) {
  779. TEMPORARY_ALLOCATOR_GUARD();
  780. Type *map_type = base_type(type_deref(map_ptr.type));
  781. GB_ASSERT(map_type->kind == Type_Map);
  782. lbValue ptr = {};
  783. lbValue key_ptr = {};
  784. lbValue hash = lb_gen_map_key_hash(p, map_ptr, key, &key_ptr);
  785. if (build_context.dynamic_map_calls) {
  786. auto args = array_make<lbValue>(temporary_allocator(), 4);
  787. args[0] = lb_emit_transmute(p, map_ptr, t_raw_map_ptr);
  788. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  789. args[2] = hash;
  790. args[3] = key_ptr;
  791. ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  792. } else {
  793. lbValue map_get_proc = lb_map_get_proc_for_type(p->module, map_type);
  794. auto args = array_make<lbValue>(temporary_allocator(), 3);
  795. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  796. args[1] = hash;
  797. args[2] = key_ptr;
  798. ptr = lb_emit_call(p, map_get_proc, args);
  799. }
  800. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  801. }
  802. gb_internal void lb_internal_dynamic_map_set(lbProcedure *p, lbValue const &map_ptr, Type *map_type,
  803. lbValue const &map_key, lbValue const &map_value, Ast *node) {
  804. TEMPORARY_ALLOCATOR_GUARD();
  805. map_type = base_type(map_type);
  806. GB_ASSERT(map_type->kind == Type_Map);
  807. lbValue key_ptr = {};
  808. lbValue hash = lb_gen_map_key_hash(p, map_ptr, map_key, &key_ptr);
  809. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  810. lbValue value_ptr = lb_address_from_load_or_generate_local(p, v);
  811. if (build_context.dynamic_map_calls) {
  812. auto args = array_make<lbValue>(temporary_allocator(), 6);
  813. args[0] = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  814. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  815. args[2] = hash;
  816. args[3] = lb_emit_conv(p, key_ptr, t_rawptr);
  817. args[4] = lb_emit_conv(p, value_ptr, t_rawptr);
  818. args[5] = lb_emit_source_code_location_as_global(p, node);
  819. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  820. } else {
  821. lbValue map_set_proc = lb_map_set_proc_for_type(p->module, map_type);
  822. auto args = array_make<lbValue>(temporary_allocator(), 5);
  823. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  824. args[1] = hash;
  825. args[2] = lb_emit_conv(p, key_ptr, t_rawptr);
  826. args[3] = lb_emit_conv(p, value_ptr, t_rawptr);
  827. args[4] = lb_emit_source_code_location_as_global(p, node);
  828. lb_emit_call(p, map_set_proc, args);
  829. }
  830. }
  831. gb_internal lbValue lb_dynamic_map_reserve(lbProcedure *p, lbValue const &map_ptr, isize const capacity, TokenPos const &pos) {
  832. GB_ASSERT(!build_context.no_dynamic_literals);
  833. TEMPORARY_ALLOCATOR_GUARD();
  834. String proc_name = {};
  835. if (p->entity) {
  836. proc_name = p->entity->token.string;
  837. }
  838. auto args = array_make<lbValue>(temporary_allocator(), 4);
  839. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  840. args[1] = lb_gen_map_info_ptr(p->module, type_deref(map_ptr.type));
  841. args[2] = lb_const_int(p->module, t_uint, capacity);
  842. args[3] = lb_emit_source_code_location_as_global(p, proc_name, pos);
  843. return lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  844. }
  845. struct lbGlobalVariable {
  846. lbValue var;
  847. lbValue init;
  848. DeclInfo *decl;
  849. bool is_initialized;
  850. };
  851. gb_internal lbProcedure *lb_create_objc_names(lbModule *main_module) {
  852. if (build_context.metrics.os != TargetOs_darwin) {
  853. return nullptr;
  854. }
  855. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  856. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit("__$init_objc_names"), proc_type);
  857. lb_add_attribute_to_proc(p->module, p->value, "nounwind");
  858. p->is_startup = true;
  859. return p;
  860. }
  861. gb_internal void lb_finalize_objc_names(lbProcedure *p) {
  862. if (p == nullptr) {
  863. return;
  864. }
  865. lbModule *m = p->module;
  866. TEMPORARY_ALLOCATOR_GUARD();
  867. auto args = array_make<lbValue>(temporary_allocator(), 1);
  868. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  869. lb_begin_procedure_body(p);
  870. for (auto const &entry : m->objc_classes) {
  871. String name = entry.key;
  872. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  873. lbValue ptr = lb_emit_runtime_call(p, "objc_lookUpClass", args);
  874. lb_addr_store(p, entry.value, ptr);
  875. }
  876. for (auto const &entry : m->objc_selectors) {
  877. String name = entry.key;
  878. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  879. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  880. lb_addr_store(p, entry.value, ptr);
  881. }
  882. lb_end_procedure_body(p);
  883. }
  884. gb_internal lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *objc_names, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  885. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  886. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  887. p->is_startup = true;
  888. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  889. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  890. lb_begin_procedure_body(p);
  891. lb_setup_type_info_data(main_module);
  892. if (objc_names) {
  893. LLVMBuildCall2(p->builder, lb_type_internal_for_procedures_raw(main_module, objc_names->type), objc_names->value, nullptr, 0, "");
  894. }
  895. for (auto &var : global_variables) {
  896. if (var.is_initialized) {
  897. continue;
  898. }
  899. lbModule *entity_module = main_module;
  900. Entity *e = var.decl->entity;
  901. GB_ASSERT(e->kind == Entity_Variable);
  902. e->code_gen_module = entity_module;
  903. Ast *init_expr = var.decl->init_expr;
  904. if (init_expr != nullptr) {
  905. lbValue init = lb_build_expr(p, init_expr);
  906. if (init.value == nullptr) {
  907. LLVMTypeRef global_type = llvm_addr_type(p->module, var.var);
  908. if (is_type_untyped_nil(init.type)) {
  909. LLVMSetInitializer(var.var.value, LLVMConstNull(global_type));
  910. var.is_initialized = true;
  911. continue;
  912. }
  913. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  914. }
  915. if (is_type_any(e->type) || is_type_union(e->type)) {
  916. var.init = init;
  917. } else if (lb_is_const_or_global(init)) {
  918. if (!var.is_initialized) {
  919. if (is_type_proc(init.type)) {
  920. init.value = LLVMConstPointerCast(init.value, lb_type(p->module, init.type));
  921. }
  922. LLVMSetInitializer(var.var.value, init.value);
  923. var.is_initialized = true;
  924. continue;
  925. }
  926. } else {
  927. var.init = init;
  928. }
  929. }
  930. if (var.init.value != nullptr) {
  931. GB_ASSERT(!var.is_initialized);
  932. Type *t = type_deref(var.var.type);
  933. if (is_type_any(t)) {
  934. // NOTE(bill): Edge case for 'any' type
  935. Type *var_type = default_type(var.init.type);
  936. lbAddr g = lb_add_global_generated(main_module, var_type, var.init);
  937. lb_addr_store(p, g, var.init);
  938. lbValue gp = lb_addr_get_ptr(p, g);
  939. lbValue data = lb_emit_struct_ep(p, var.var, 0);
  940. lbValue ti = lb_emit_struct_ep(p, var.var, 1);
  941. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  942. lb_emit_store(p, ti, lb_type_info(p, var_type));
  943. } else {
  944. LLVMTypeRef vt = llvm_addr_type(p->module, var.var);
  945. lbValue src0 = lb_emit_conv(p, var.init, t);
  946. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  947. LLVMValueRef dst = var.var.value;
  948. LLVMBuildStore(p->builder, src, dst);
  949. }
  950. var.is_initialized = true;
  951. }
  952. }
  953. CheckerInfo *info = main_module->gen->info;
  954. for (Entity *e : info->init_procedures) {
  955. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  956. lb_emit_call(p, value, {}, ProcInlining_none);
  957. }
  958. lb_end_procedure_body(p);
  959. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  960. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  961. LLVMDumpValue(p->value);
  962. gb_printf_err("\n\n\n\n");
  963. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  964. }
  965. return p;
  966. }
  967. gb_internal lbProcedure *lb_create_cleanup_runtime(lbModule *main_module) { // Cleanup Runtime
  968. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  969. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_CLEANUP_RUNTIME_PROC_NAME), proc_type);
  970. p->is_startup = true;
  971. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  972. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  973. lb_begin_procedure_body(p);
  974. CheckerInfo *info = main_module->gen->info;
  975. for (Entity *e : info->fini_procedures) {
  976. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  977. lb_emit_call(p, value, {}, ProcInlining_none);
  978. }
  979. lb_end_procedure_body(p);
  980. if (!main_module->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  981. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  982. LLVMDumpValue(p->value);
  983. gb_printf_err("\n\n\n\n");
  984. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  985. }
  986. return p;
  987. }
  988. gb_internal WORKER_TASK_PROC(lb_generate_procedures_and_types_per_module) {
  989. lbModule *m = cast(lbModule *)data;
  990. for (Entity *e : m->global_procedures_and_types_to_create) {
  991. if (e->kind == Entity_TypeName) {
  992. (void)lb_get_entity_name(m, e);
  993. lb_type(m, e->type);
  994. }
  995. }
  996. for (Entity *e : m->global_procedures_and_types_to_create) {
  997. if (e->kind == Entity_Procedure) {
  998. (void)lb_get_entity_name(m, e);
  999. array_add(&m->procedures_to_generate, lb_create_procedure(m, e));
  1000. }
  1001. }
  1002. return 0;
  1003. }
  1004. gb_internal void lb_create_global_procedures_and_types(lbGenerator *gen, CheckerInfo *info, bool do_threading) {
  1005. auto *min_dep_set = &info->minimum_dependency_set;
  1006. for (Entity *e : info->entities) {
  1007. String name = e->token.string;
  1008. Scope * scope = e->scope;
  1009. if ((scope->flags & ScopeFlag_File) == 0) {
  1010. continue;
  1011. }
  1012. Scope *package_scope = scope->parent;
  1013. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  1014. switch (e->kind) {
  1015. case Entity_Variable:
  1016. // NOTE(bill): Handled above as it requires a specific load order
  1017. continue;
  1018. case Entity_ProcGroup:
  1019. continue;
  1020. case Entity_TypeName:
  1021. case Entity_Procedure:
  1022. break;
  1023. case Entity_Constant:
  1024. if (build_context.ODIN_DEBUG) {
  1025. add_debug_info_for_global_constant_from_entity(gen, e);
  1026. }
  1027. break;
  1028. }
  1029. bool polymorphic_struct = false;
  1030. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1031. Type *bt = base_type(e->type);
  1032. if (bt->kind == Type_Struct) {
  1033. polymorphic_struct = is_type_polymorphic(bt);
  1034. }
  1035. }
  1036. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1037. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1038. continue;
  1039. }
  1040. lbModule *m = &gen->default_module;
  1041. if (USE_SEPARATE_MODULES) {
  1042. m = lb_module_of_entity(gen, e);
  1043. }
  1044. array_add(&m->global_procedures_and_types_to_create, e);
  1045. }
  1046. for (auto const &entry : gen->modules) {
  1047. lbModule *m = entry.value;
  1048. if (do_threading) {
  1049. thread_pool_add_task(lb_generate_procedures_and_types_per_module, m);
  1050. } else {
  1051. lb_generate_procedures_and_types_per_module(m);
  1052. }
  1053. }
  1054. thread_pool_wait();
  1055. }
  1056. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p);
  1057. gb_internal bool lb_is_module_empty(lbModule *m) {
  1058. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  1059. LLVMGetFirstGlobal(m->mod) == nullptr) {
  1060. return true;
  1061. }
  1062. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  1063. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  1064. return false;
  1065. }
  1066. }
  1067. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  1068. if (LLVMGetLinkage(g) == LLVMExternalLinkage) {
  1069. continue;
  1070. }
  1071. if (!LLVMIsExternallyInitialized(g)) {
  1072. return false;
  1073. }
  1074. }
  1075. return true;
  1076. }
  1077. struct lbLLVMEmitWorker {
  1078. LLVMTargetMachineRef target_machine;
  1079. LLVMCodeGenFileType code_gen_file_type;
  1080. String filepath_obj;
  1081. lbModule *m;
  1082. };
  1083. gb_internal WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  1084. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  1085. char *llvm_error = nullptr;
  1086. auto wd = cast(lbLLVMEmitWorker *)data;
  1087. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  1088. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1089. exit_with_errors();
  1090. }
  1091. debugf("Generated File: %.*s\n", LIT(wd->filepath_obj));
  1092. return 0;
  1093. }
  1094. gb_internal void lb_llvm_function_pass_per_function_internal(lbModule *module, lbProcedure *p, lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default) {
  1095. LLVMPassManagerRef pass_manager = module->function_pass_managers[pass_manager_kind];
  1096. lb_run_function_pass_manager(pass_manager, p, pass_manager_kind);
  1097. }
  1098. gb_internal WORKER_TASK_PROC(lb_llvm_function_pass_per_module) {
  1099. lbModule *m = cast(lbModule *)data;
  1100. {
  1101. GB_ASSERT(m->function_pass_managers[lbFunctionPassManager_default] == nullptr);
  1102. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1103. m->function_pass_managers[i] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1104. }
  1105. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1106. LLVMInitializeFunctionPassManager(m->function_pass_managers[i]);
  1107. }
  1108. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default], false, build_context.optimization_level);
  1109. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default_without_memcpy], true, build_context.optimization_level);
  1110. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_none], -1);
  1111. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_minimal], 0);
  1112. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_size], 1);
  1113. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_speed], 2);
  1114. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_aggressive], 3);
  1115. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1116. LLVMFinalizeFunctionPassManager(m->function_pass_managers[i]);
  1117. }
  1118. }
  1119. if (m == &m->gen->default_module) {
  1120. lb_llvm_function_pass_per_function_internal(m, m->gen->startup_runtime);
  1121. lb_llvm_function_pass_per_function_internal(m, m->gen->cleanup_runtime);
  1122. lb_llvm_function_pass_per_function_internal(m, m->gen->objc_names);
  1123. }
  1124. for (lbProcedure *p : m->procedures_to_generate) {
  1125. if (p->body != nullptr) { // Build Procedure
  1126. lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default;
  1127. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  1128. pass_manager_kind = lbFunctionPassManager_default_without_memcpy;
  1129. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  1130. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  1131. } else {
  1132. if (p->entity && p->entity->kind == Entity_Procedure) {
  1133. switch (p->entity->Procedure.optimization_mode) {
  1134. case ProcedureOptimizationMode_None:
  1135. case ProcedureOptimizationMode_Minimal:
  1136. pass_manager_kind = lbFunctionPassManager_minimal;
  1137. break;
  1138. case ProcedureOptimizationMode_Size:
  1139. pass_manager_kind = lbFunctionPassManager_size;
  1140. lb_add_attribute_to_proc(p->module, p->value, "optsize");
  1141. break;
  1142. case ProcedureOptimizationMode_Speed:
  1143. pass_manager_kind = lbFunctionPassManager_speed;
  1144. break;
  1145. }
  1146. }
  1147. }
  1148. lb_llvm_function_pass_per_function_internal(m, p, pass_manager_kind);
  1149. }
  1150. }
  1151. for (auto const &entry : m->equal_procs) {
  1152. lbProcedure *p = entry.value;
  1153. lb_llvm_function_pass_per_function_internal(m, p);
  1154. }
  1155. for (auto const &entry : m->hasher_procs) {
  1156. lbProcedure *p = entry.value;
  1157. lb_llvm_function_pass_per_function_internal(m, p);
  1158. }
  1159. for (auto const &entry : m->map_get_procs) {
  1160. lbProcedure *p = entry.value;
  1161. lb_llvm_function_pass_per_function_internal(m, p, lbFunctionPassManager_none);
  1162. }
  1163. for (auto const &entry : m->map_set_procs) {
  1164. lbProcedure *p = entry.value;
  1165. lb_llvm_function_pass_per_function_internal(m, p, lbFunctionPassManager_none);
  1166. }
  1167. return 0;
  1168. }
  1169. struct lbLLVMModulePassWorkerData {
  1170. lbModule *m;
  1171. LLVMTargetMachineRef target_machine;
  1172. };
  1173. gb_internal WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  1174. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  1175. lb_run_remove_unused_function_pass(wd->m);
  1176. lb_run_remove_unused_globals_pass(wd->m);
  1177. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  1178. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  1179. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  1180. #if LB_USE_NEW_PASS_SYSTEM
  1181. auto passes = array_make<char const *>(heap_allocator(), 0, 64);
  1182. defer (array_free(&passes));
  1183. LLVMPassBuilderOptionsRef pb_options = LLVMCreatePassBuilderOptions();
  1184. defer (LLVMDisposePassBuilderOptions(pb_options));
  1185. switch (build_context.optimization_level) {
  1186. case -1:
  1187. break;
  1188. case 0:
  1189. array_add(&passes, "always-inline");
  1190. array_add(&passes, "function(annotation-remarks)");
  1191. break;
  1192. case 1:
  1193. // default<Os>
  1194. // Passes removed: coro, openmp, sroa
  1195. array_add(&passes, u8R"(
  1196. annotation2metadata,
  1197. forceattrs,
  1198. inferattrs,
  1199. function<eager-inv>(
  1200. lower-expect,
  1201. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;no-switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1202. early-cse<>
  1203. ),
  1204. ipsccp,
  1205. called-value-propagation,
  1206. globalopt,
  1207. function<eager-inv>(
  1208. mem2reg,
  1209. instcombine<max-iterations=1000;no-use-loop-info>,
  1210. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>),
  1211. require<globals-aa>,
  1212. function(
  1213. invalidate<aa>
  1214. ),
  1215. require<profile-summary>,
  1216. cgscc(
  1217. devirt<4>(
  1218. inline<only-mandatory>,
  1219. inline,
  1220. function-attrs<skip-non-recursive>,
  1221. function<eager-inv;no-rerun>(
  1222. early-cse<memssa>,
  1223. speculative-execution,
  1224. jump-threading,
  1225. correlated-propagation,
  1226. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1227. instcombine<max-iterations=1000;no-use-loop-info>,
  1228. aggressive-instcombine,
  1229. constraint-elimination,
  1230. tailcallelim,
  1231. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1232. reassociate,
  1233. loop-mssa(
  1234. loop-instsimplify,
  1235. loop-simplifycfg,
  1236. licm<no-allowspeculation>,
  1237. loop-rotate<header-duplication;no-prepare-for-lto>,
  1238. licm<allowspeculation>,
  1239. simple-loop-unswitch<no-nontrivial;trivial>
  1240. ),
  1241. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1242. instcombine<max-iterations=1000;no-use-loop-info>,
  1243. loop(
  1244. loop-idiom,
  1245. indvars,
  1246. loop-deletion,
  1247. loop-unroll-full
  1248. ),
  1249. vector-combine,
  1250. mldst-motion<no-split-footer-bb>,
  1251. gvn<>,
  1252. sccp,
  1253. bdce,
  1254. instcombine<max-iterations=1000;no-use-loop-info>,
  1255. jump-threading,
  1256. correlated-propagation,
  1257. adce,
  1258. memcpyopt,
  1259. dse,
  1260. move-auto-init,
  1261. loop-mssa(
  1262. licm<allowspeculation>
  1263. ),
  1264. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1265. instcombine<max-iterations=1000;no-use-loop-info>
  1266. ),
  1267. function-attrs,
  1268. function(
  1269. require<should-not-run-function-passes>
  1270. )
  1271. )
  1272. ),
  1273. deadargelim,
  1274. globalopt,
  1275. globaldce,
  1276. elim-avail-extern,
  1277. rpo-function-attrs,
  1278. recompute-globalsaa,
  1279. function<eager-inv>(
  1280. float2int,
  1281. lower-constant-intrinsics,
  1282. loop(
  1283. loop-rotate<header-duplication;no-prepare-for-lto>,
  1284. loop-deletion
  1285. ),
  1286. loop-distribute,
  1287. inject-tli-mappings,
  1288. loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,
  1289. loop-load-elim,
  1290. instcombine<max-iterations=1000;no-use-loop-info>,
  1291. simplifycfg<bonus-inst-threshold=1;forward-switch-cond;switch-range-to-icmp;switch-to-lookup;no-keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1292. slp-vectorizer,
  1293. vector-combine,
  1294. instcombine<max-iterations=1000;no-use-loop-info>,
  1295. loop-unroll<O2>,
  1296. transform-warning,
  1297. instcombine<max-iterations=1000;no-use-loop-info>,
  1298. loop-mssa(
  1299. licm<allowspeculation>
  1300. ),
  1301. alignment-from-assumptions,
  1302. loop-sink,
  1303. instsimplify,
  1304. div-rem-pairs,
  1305. tailcallelim,
  1306. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1307. ),
  1308. globaldce,
  1309. constmerge,
  1310. cg-profile,
  1311. rel-lookup-table-converter,
  1312. function(
  1313. annotation-remarks
  1314. ),
  1315. verify
  1316. )");
  1317. break;
  1318. // default<O2>
  1319. // Passes removed: coro, openmp, sroa
  1320. case 2:
  1321. array_add(&passes, u8R"(
  1322. annotation2metadata,
  1323. forceattrs,
  1324. inferattrs,
  1325. function<eager-inv>(
  1326. lower-expect,
  1327. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;no-switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1328. early-cse<>
  1329. ),
  1330. ipsccp,
  1331. called-value-propagation,
  1332. globalopt,
  1333. function<eager-inv>(
  1334. mem2reg,
  1335. instcombine<max-iterations=1000;no-use-loop-info>,
  1336. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1337. ),
  1338. require<globals-aa>,
  1339. function(
  1340. invalidate<aa>
  1341. ),
  1342. require<profile-summary>,
  1343. cgscc(
  1344. devirt<4>(
  1345. inline<only-mandatory>,
  1346. inline,
  1347. function-attrs<skip-non-recursive>,
  1348. function<eager-inv;no-rerun>(
  1349. early-cse<memssa>,
  1350. speculative-execution,
  1351. jump-threading,
  1352. correlated-propagation,
  1353. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1354. instcombine<max-iterations=1000;no-use-loop-info>,
  1355. aggressive-instcombine,
  1356. constraint-elimination,
  1357. libcalls-shrinkwrap,
  1358. tailcallelim,
  1359. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1360. reassociate,
  1361. loop-mssa(
  1362. loop-instsimplify,
  1363. loop-simplifycfg,
  1364. licm<no-allowspeculation>,
  1365. loop-rotate<header-duplication;no-prepare-for-lto>,
  1366. licm<allowspeculation>,
  1367. simple-loop-unswitch<no-nontrivial;trivial>
  1368. ),
  1369. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1370. instcombine<max-iterations=1000;no-use-loop-info>,
  1371. loop(
  1372. loop-idiom,
  1373. indvars,
  1374. loop-deletion,
  1375. loop-unroll-full
  1376. ),
  1377. vector-combine,
  1378. mldst-motion<no-split-footer-bb>,
  1379. gvn<>,
  1380. sccp,
  1381. bdce,
  1382. instcombine<max-iterations=1000;no-use-loop-info>,
  1383. jump-threading,
  1384. correlated-propagation,
  1385. adce,
  1386. memcpyopt,
  1387. dse,
  1388. move-auto-init,
  1389. loop-mssa(
  1390. licm<allowspeculation>
  1391. ),
  1392. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1393. instcombine<max-iterations=1000;no-use-loop-info>
  1394. ),
  1395. function-attrs,
  1396. function(
  1397. require<should-not-run-function-passes>
  1398. )
  1399. )
  1400. ),
  1401. deadargelim,
  1402. globalopt,
  1403. globaldce,
  1404. elim-avail-extern,
  1405. rpo-function-attrs,
  1406. recompute-globalsaa,
  1407. function<eager-inv>(
  1408. float2int,
  1409. lower-constant-intrinsics,
  1410. loop(
  1411. loop-rotate<header-duplication;no-prepare-for-lto>,
  1412. loop-deletion
  1413. ),
  1414. loop-distribute,
  1415. inject-tli-mappings,
  1416. loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,
  1417. loop-load-elim,
  1418. instcombine<max-iterations=1000;no-use-loop-info>,
  1419. simplifycfg<bonus-inst-threshold=1;forward-switch-cond;switch-range-to-icmp;switch-to-lookup;no-keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1420. slp-vectorizer,
  1421. vector-combine,
  1422. instcombine<max-iterations=1000;no-use-loop-info>,
  1423. loop-unroll<O2>,
  1424. transform-warning,
  1425. instcombine<max-iterations=1000;no-use-loop-info>,
  1426. loop-mssa(
  1427. licm<allowspeculation>
  1428. ),
  1429. alignment-from-assumptions,
  1430. loop-sink,
  1431. instsimplify,
  1432. div-rem-pairs,
  1433. tailcallelim,
  1434. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1435. ),
  1436. globaldce,
  1437. constmerge,
  1438. cg-profile,
  1439. rel-lookup-table-converter,
  1440. function(
  1441. annotation-remarks
  1442. ),
  1443. verify
  1444. )");
  1445. break;
  1446. case 3:
  1447. // default<O3>
  1448. // Passes removed: coro, openmp, sroa
  1449. array_add(&passes, u8R"(
  1450. annotation2metadata,
  1451. forceattrs,
  1452. inferattrs,
  1453. function<eager-inv>(
  1454. lower-expect,
  1455. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;no-switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1456. early-cse<>,
  1457. callsite-splitting
  1458. ),
  1459. ipsccp,
  1460. called-value-propagation,
  1461. globalopt,
  1462. function<eager-inv>(
  1463. mem2reg,
  1464. instcombine<max-iterations=1000;no-use-loop-info>,
  1465. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1466. ),
  1467. require<globals-aa>,
  1468. function(
  1469. invalidate<aa>
  1470. ),
  1471. require<profile-summary>,
  1472. cgscc(
  1473. devirt<4>(
  1474. inline<only-mandatory>,
  1475. inline,
  1476. function-attrs<skip-non-recursive>,
  1477. argpromotion,
  1478. function<eager-inv;no-rerun>(
  1479. early-cse<memssa>,
  1480. speculative-execution,
  1481. jump-threading,
  1482. correlated-propagation,
  1483. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1484. instcombine<max-iterations=1000;no-use-loop-info>,
  1485. aggressive-instcombine,
  1486. constraint-elimination,
  1487. libcalls-shrinkwrap,
  1488. tailcallelim,
  1489. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1490. reassociate,
  1491. loop-mssa(
  1492. loop-instsimplify,
  1493. loop-simplifycfg,
  1494. licm<no-allowspeculation>,
  1495. loop-rotate<header-duplication;no-prepare-for-lto>,
  1496. licm<allowspeculation>,
  1497. simple-loop-unswitch<nontrivial;trivial>
  1498. ),
  1499. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1500. instcombine<max-iterations=1000;no-use-loop-info>,
  1501. loop(
  1502. loop-idiom,
  1503. indvars,
  1504. loop-deletion,
  1505. loop-unroll-full
  1506. ),
  1507. vector-combine,
  1508. mldst-motion<no-split-footer-bb>,
  1509. gvn<>,
  1510. sccp,
  1511. bdce,
  1512. instcombine<max-iterations=1000;no-use-loop-info>,
  1513. jump-threading,
  1514. correlated-propagation,
  1515. adce,
  1516. memcpyopt,
  1517. dse,
  1518. move-auto-init,
  1519. loop-mssa(
  1520. licm<allowspeculation>
  1521. ),
  1522. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1523. instcombine<max-iterations=1000;no-use-loop-info>
  1524. ),
  1525. function-attrs,
  1526. function(
  1527. require<should-not-run-function-passes>
  1528. )
  1529. )
  1530. ),
  1531. deadargelim,
  1532. globalopt,
  1533. globaldce,
  1534. elim-avail-extern,
  1535. rpo-function-attrs,
  1536. recompute-globalsaa,
  1537. function<eager-inv>(
  1538. float2int,
  1539. lower-constant-intrinsics,
  1540. chr,
  1541. loop(
  1542. loop-rotate<header-duplication;no-prepare-for-lto>,
  1543. loop-deletion
  1544. ),
  1545. loop-distribute,
  1546. inject-tli-mappings,
  1547. loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,
  1548. loop-load-elim,
  1549. instcombine<max-iterations=1000;no-use-loop-info>,
  1550. simplifycfg<bonus-inst-threshold=1;forward-switch-cond;switch-range-to-icmp;switch-to-lookup;no-keep-loops;hoist-common-insts;sink-common-insts;speculate-blocks;simplify-cond-branch>,
  1551. slp-vectorizer,
  1552. vector-combine,
  1553. instcombine<max-iterations=1000;no-use-loop-info>,
  1554. loop-unroll<O3>,
  1555. transform-warning,
  1556. instcombine<max-iterations=1000;no-use-loop-info>,
  1557. loop-mssa(
  1558. licm<allowspeculation>
  1559. ),
  1560. alignment-from-assumptions,
  1561. loop-sink,
  1562. instsimplify,
  1563. div-rem-pairs,
  1564. tailcallelim,
  1565. simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;no-sink-common-insts;speculate-blocks;simplify-cond-branch>
  1566. ),
  1567. globaldce,
  1568. constmerge,
  1569. cg-profile,
  1570. rel-lookup-table-converter,
  1571. function(
  1572. annotation-remarks
  1573. ),
  1574. verify
  1575. )");
  1576. break;
  1577. }
  1578. // asan - Linux, Darwin, Windows
  1579. // msan - linux
  1580. // tsan - Linux, Darwin
  1581. // ubsan - Linux, Darwin, Windows (NOT SUPPORTED WITH LLVM C-API)
  1582. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  1583. array_add(&passes, "asan");
  1584. }
  1585. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  1586. array_add(&passes, "msan");
  1587. }
  1588. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  1589. array_add(&passes, "tsan");
  1590. }
  1591. if (passes.count == 0) {
  1592. array_add(&passes, "verify");
  1593. }
  1594. gbString passes_str = gb_string_make_reserve(heap_allocator(), 1024);
  1595. defer (gb_string_free(passes_str));
  1596. for_array(i, passes) {
  1597. if (i != 0) {
  1598. passes_str = gb_string_appendc(passes_str, ",");
  1599. }
  1600. passes_str = gb_string_appendc(passes_str, passes[i]);
  1601. }
  1602. for (isize i = 0; i < gb_string_length(passes_str); /**/) {
  1603. switch (passes_str[i]) {
  1604. case ' ':
  1605. case '\n':
  1606. case '\t':
  1607. gb_memmove(&passes_str[i], &passes_str[i+1], gb_string_length(passes_str)-i);
  1608. GB_STRING_HEADER(passes_str)->length -= 1;
  1609. continue;
  1610. default:
  1611. i += 1;
  1612. break;
  1613. }
  1614. }
  1615. LLVMErrorRef llvm_err = LLVMRunPasses(wd->m->mod, passes_str, wd->target_machine, pb_options);
  1616. defer (LLVMConsumeError(llvm_err));
  1617. if (llvm_err != nullptr) {
  1618. char *llvm_error = LLVMGetErrorMessage(llvm_err);
  1619. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1620. LLVMDisposeErrorMessage(llvm_error);
  1621. llvm_error = nullptr;
  1622. if (build_context.keep_temp_files) {
  1623. TIME_SECTION("LLVM Print Module to File");
  1624. String filepath_ll = lb_filepath_ll_for_module(wd->m);
  1625. if (LLVMPrintModuleToFile(wd->m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1626. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1627. }
  1628. }
  1629. exit_with_errors();
  1630. return 1;
  1631. }
  1632. #endif
  1633. return 0;
  1634. }
  1635. gb_internal WORKER_TASK_PROC(lb_generate_procedures_worker_proc) {
  1636. lbModule *m = cast(lbModule *)data;
  1637. for (isize i = 0; i < m->procedures_to_generate.count; i++) {
  1638. lbProcedure *p = m->procedures_to_generate[i];
  1639. lb_generate_procedure(p->module, p);
  1640. }
  1641. return 0;
  1642. }
  1643. gb_internal void lb_generate_procedures(lbGenerator *gen, bool do_threading) {
  1644. for (auto const &entry : gen->modules) {
  1645. lbModule *m = entry.value;
  1646. if (do_threading) {
  1647. thread_pool_add_task(lb_generate_procedures_worker_proc, m);
  1648. } else {
  1649. lb_generate_procedures_worker_proc(m);
  1650. }
  1651. }
  1652. thread_pool_wait();
  1653. }
  1654. gb_internal WORKER_TASK_PROC(lb_generate_missing_procedures_to_check_worker_proc) {
  1655. lbModule *m = cast(lbModule *)data;
  1656. for (isize i = 0; i < m->missing_procedures_to_check.count; i++) {
  1657. lbProcedure *p = m->missing_procedures_to_check[i];
  1658. debugf("Generate missing procedure: %.*s module %p\n", LIT(p->name), m);
  1659. lb_generate_procedure(m, p);
  1660. }
  1661. return 0;
  1662. }
  1663. gb_internal void lb_generate_missing_procedures(lbGenerator *gen, bool do_threading) {
  1664. for (auto const &entry : gen->modules) {
  1665. lbModule *m = entry.value;
  1666. // NOTE(bill): procedures may be added during generation
  1667. if (do_threading) {
  1668. thread_pool_add_task(lb_generate_missing_procedures_to_check_worker_proc, m);
  1669. } else {
  1670. lb_generate_missing_procedures_to_check_worker_proc(m);
  1671. }
  1672. }
  1673. thread_pool_wait();
  1674. }
  1675. gb_internal void lb_debug_info_complete_types_and_finalize(lbGenerator *gen) {
  1676. for (auto const &entry : gen->modules) {
  1677. lbModule *m = entry.value;
  1678. if (m->debug_builder != nullptr) {
  1679. LLVMDIBuilderFinalize(m->debug_builder);
  1680. }
  1681. }
  1682. }
  1683. gb_internal void lb_llvm_function_passes(lbGenerator *gen, bool do_threading) {
  1684. for (auto const &entry : gen->modules) {
  1685. lbModule *m = entry.value;
  1686. if (do_threading) {
  1687. thread_pool_add_task(lb_llvm_function_pass_per_module, m);
  1688. } else {
  1689. lb_llvm_function_pass_per_module(m);
  1690. }
  1691. }
  1692. thread_pool_wait();
  1693. }
  1694. gb_internal void lb_llvm_module_passes(lbGenerator *gen, bool do_threading) {
  1695. for (auto const &entry : gen->modules) {
  1696. lbModule *m = entry.value;
  1697. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  1698. wd->m = m;
  1699. wd->target_machine = m->target_machine;
  1700. if (do_threading) {
  1701. thread_pool_add_task(lb_llvm_module_pass_worker_proc, wd);
  1702. } else {
  1703. lb_llvm_module_pass_worker_proc(wd);
  1704. }
  1705. }
  1706. thread_pool_wait();
  1707. }
  1708. gb_internal String lb_filepath_ll_for_module(lbModule *m) {
  1709. String path = concatenate3_strings(permanent_allocator(),
  1710. build_context.build_paths[BuildPath_Output].basename,
  1711. STR_LIT("/"),
  1712. build_context.build_paths[BuildPath_Output].name
  1713. );
  1714. if (m->file) {
  1715. char buf[32] = {};
  1716. isize n = gb_snprintf(buf, gb_size_of(buf), "-%u", m->file->id);
  1717. String suffix = make_string((u8 *)buf, n-1);
  1718. path = concatenate_strings(permanent_allocator(), path, suffix);
  1719. } else if (m->pkg) {
  1720. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  1721. } else if (USE_SEPARATE_MODULES) {
  1722. path = concatenate_strings(permanent_allocator(), path, STR_LIT("-builtin"));
  1723. }
  1724. path = concatenate_strings(permanent_allocator(), path, STR_LIT(".ll"));
  1725. return path;
  1726. }
  1727. gb_internal String lb_filepath_obj_for_module(lbModule *m) {
  1728. String path = concatenate3_strings(permanent_allocator(),
  1729. build_context.build_paths[BuildPath_Output].basename,
  1730. STR_LIT("/"),
  1731. build_context.build_paths[BuildPath_Output].name
  1732. );
  1733. if (m->file) {
  1734. char buf[32] = {};
  1735. isize n = gb_snprintf(buf, gb_size_of(buf), "-%u", m->file->id);
  1736. String suffix = make_string((u8 *)buf, n-1);
  1737. path = concatenate_strings(permanent_allocator(), path, suffix);
  1738. } else if (m->pkg) {
  1739. path = concatenate3_strings(permanent_allocator(), path, STR_LIT("-"), m->pkg->name);
  1740. }
  1741. String ext = {};
  1742. if (build_context.build_mode == BuildMode_Assembly) {
  1743. ext = STR_LIT(".S");
  1744. } else {
  1745. if (is_arch_wasm()) {
  1746. ext = STR_LIT(".wasm.o");
  1747. } else {
  1748. switch (build_context.metrics.os) {
  1749. case TargetOs_windows:
  1750. ext = STR_LIT(".obj");
  1751. break;
  1752. default:
  1753. case TargetOs_darwin:
  1754. case TargetOs_linux:
  1755. case TargetOs_essence:
  1756. ext = STR_LIT(".o");
  1757. break;
  1758. case TargetOs_freestanding:
  1759. switch (build_context.metrics.abi) {
  1760. default:
  1761. case TargetABI_Default:
  1762. case TargetABI_SysV:
  1763. ext = STR_LIT(".o");
  1764. break;
  1765. case TargetABI_Win64:
  1766. ext = STR_LIT(".obj");
  1767. break;
  1768. }
  1769. break;
  1770. }
  1771. }
  1772. }
  1773. return concatenate_strings(permanent_allocator(), path, ext);
  1774. }
  1775. gb_internal WORKER_TASK_PROC(lb_llvm_module_verification_worker_proc) {
  1776. char *llvm_error = nullptr;
  1777. defer (LLVMDisposeMessage(llvm_error));
  1778. lbModule *m = cast(lbModule *)data;
  1779. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  1780. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1781. if (build_context.keep_temp_files) {
  1782. TIME_SECTION("LLVM Print Module to File");
  1783. String filepath_ll = lb_filepath_ll_for_module(m);
  1784. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1785. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1786. exit_with_errors();
  1787. return false;
  1788. }
  1789. }
  1790. exit_with_errors();
  1791. return 1;
  1792. }
  1793. return 0;
  1794. }
  1795. gb_internal bool lb_llvm_module_verification(lbGenerator *gen, bool do_threading) {
  1796. for (auto const &entry : gen->modules) {
  1797. lbModule *m = entry.value;
  1798. if (do_threading) {
  1799. thread_pool_add_task(lb_llvm_module_verification_worker_proc, m);
  1800. } else {
  1801. if (lb_llvm_module_verification_worker_proc(m)) {
  1802. return false;
  1803. }
  1804. }
  1805. }
  1806. thread_pool_wait();
  1807. return true;
  1808. }
  1809. gb_internal void lb_add_foreign_library_paths(lbGenerator *gen) {
  1810. for (auto const &entry : gen->modules) {
  1811. lbModule *m = entry.value;
  1812. for (Entity *e : m->info->required_foreign_imports_through_force) {
  1813. lb_add_foreign_library_path(m, e);
  1814. }
  1815. if (lb_is_module_empty(m)) {
  1816. continue;
  1817. }
  1818. }
  1819. }
  1820. gb_internal bool lb_llvm_object_generation(lbGenerator *gen, bool do_threading) {
  1821. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  1822. if (build_context.build_mode == BuildMode_Assembly) {
  1823. code_gen_file_type = LLVMAssemblyFile;
  1824. }
  1825. char *llvm_error = nullptr;
  1826. defer (LLVMDisposeMessage(llvm_error));
  1827. if (do_threading) {
  1828. for (auto const &entry : gen->modules) {
  1829. lbModule *m = entry.value;
  1830. if (lb_is_module_empty(m)) {
  1831. continue;
  1832. }
  1833. String filepath_ll = lb_filepath_ll_for_module(m);
  1834. String filepath_obj = lb_filepath_obj_for_module(m);
  1835. // gb_printf_err("%.*s\n", LIT(filepath_obj));
  1836. array_add(&gen->output_object_paths, filepath_obj);
  1837. array_add(&gen->output_temp_paths, filepath_ll);
  1838. auto *wd = gb_alloc_item(permanent_allocator(), lbLLVMEmitWorker);
  1839. wd->target_machine = m->target_machine;
  1840. wd->code_gen_file_type = code_gen_file_type;
  1841. wd->filepath_obj = filepath_obj;
  1842. wd->m = m;
  1843. thread_pool_add_task(lb_llvm_emit_worker_proc, wd);
  1844. }
  1845. thread_pool_wait(&global_thread_pool);
  1846. } else {
  1847. for (auto const &entry : gen->modules) {
  1848. lbModule *m = entry.value;
  1849. if (lb_is_module_empty(m)) {
  1850. continue;
  1851. }
  1852. String filepath_obj = lb_filepath_obj_for_module(m);
  1853. array_add(&gen->output_object_paths, filepath_obj);
  1854. String short_name = remove_directory_from_path(filepath_obj);
  1855. gbString section_name = gb_string_make(permanent_allocator(), "LLVM Generate Object: ");
  1856. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  1857. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  1858. if (LLVMTargetMachineEmitToFile(m->target_machine, m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  1859. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1860. exit_with_errors();
  1861. return false;
  1862. }
  1863. debugf("Generated File: %.*s\n", LIT(filepath_obj));
  1864. }
  1865. }
  1866. return true;
  1867. }
  1868. gb_internal lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime, lbProcedure *cleanup_runtime) {
  1869. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  1870. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  1871. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  1872. Type *params = alloc_type_tuple();
  1873. Type *results = alloc_type_tuple();
  1874. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  1875. bool call_cleanup = true;
  1876. bool has_args = false;
  1877. bool is_dll_main = false;
  1878. String name = str_lit("main");
  1879. if (build_context.metrics.os == TargetOs_windows && build_context.build_mode == BuildMode_DynamicLibrary) {
  1880. is_dll_main = true;
  1881. name = str_lit("DllMain");
  1882. slice_init(&params->Tuple.variables, permanent_allocator(), 3);
  1883. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("hinstDLL"), t_rawptr, false, true);
  1884. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("fdwReason"), t_u32, false, true);
  1885. params->Tuple.variables[2] = alloc_entity_param(nullptr, make_token_ident("lpReserved"), t_rawptr, false, true);
  1886. call_cleanup = false;
  1887. } else if (build_context.metrics.os == TargetOs_windows && (build_context.metrics.arch == TargetArch_i386 || build_context.no_crt)) {
  1888. name = str_lit("mainCRTStartup");
  1889. } else if (is_arch_wasm()) {
  1890. name = str_lit("_start");
  1891. call_cleanup = false;
  1892. } else {
  1893. has_args = true;
  1894. slice_init(&params->Tuple.variables, permanent_allocator(), 2);
  1895. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  1896. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  1897. }
  1898. slice_init(&results->Tuple.variables, permanent_allocator(), 1);
  1899. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  1900. Type *proc_type = alloc_type_proc(nullptr,
  1901. params, params->Tuple.variables.count,
  1902. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  1903. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  1904. p->is_startup = true;
  1905. lb_begin_procedure_body(p);
  1906. if (has_args) { // initialize `runtime.args__`
  1907. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  1908. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  1909. LLVMSetValueName2(argc.value, "argc", 4);
  1910. LLVMSetValueName2(argv.value, "argv", 4);
  1911. argc = lb_emit_conv(p, argc, t_int);
  1912. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  1913. lb_fill_slice(p, args, argv, argc);
  1914. }
  1915. lbValue startup_runtime_value = {startup_runtime->value, startup_runtime->type};
  1916. lb_emit_call(p, startup_runtime_value, {}, ProcInlining_none);
  1917. if (build_context.command_kind == Command_test) {
  1918. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  1919. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  1920. Type *slice_type = alloc_type_slice(t_Internal_Test);
  1921. lbAddr all_tests_array_addr = lb_add_global_generated(p->module, array_type, {});
  1922. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  1923. LLVMValueRef indices[2] = {};
  1924. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  1925. isize testing_proc_index = 0;
  1926. for (Entity *testing_proc : m->info->testing_procedures) {
  1927. String name = testing_proc->token.string;
  1928. String pkg_name = {};
  1929. if (testing_proc->pkg != nullptr) {
  1930. pkg_name = testing_proc->pkg->name;
  1931. }
  1932. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name);
  1933. lbValue v_name = lb_find_or_add_entity_string(m, name);
  1934. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  1935. indices[1] = LLVMConstInt(lb_type(m, t_int), testing_proc_index++, false);
  1936. LLVMValueRef vals[3] = {};
  1937. vals[0] = v_pkg.value;
  1938. vals[1] = v_name.value;
  1939. vals[2] = v_proc.value;
  1940. GB_ASSERT(LLVMIsConstant(vals[0]));
  1941. GB_ASSERT(LLVMIsConstant(vals[1]));
  1942. GB_ASSERT(LLVMIsConstant(vals[2]));
  1943. LLVMValueRef dst = LLVMConstInBoundsGEP2(llvm_addr_type(m, all_tests_array), all_tests_array.value, indices, gb_count_of(indices));
  1944. LLVMValueRef src = llvm_const_named_struct(m, t_Internal_Test, vals, gb_count_of(vals));
  1945. LLVMBuildStore(p->builder, src, dst);
  1946. }
  1947. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  1948. lb_fill_slice(p, all_tests_slice,
  1949. lb_array_elem(p, all_tests_array),
  1950. lb_const_int(m, t_int, m->info->testing_procedures.count));
  1951. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  1952. TEMPORARY_ALLOCATOR_GUARD();
  1953. auto args = array_make<lbValue>(temporary_allocator(), 1);
  1954. args[0] = lb_addr_load(p, all_tests_slice);
  1955. lbValue result = lb_emit_call(p, runner, args);
  1956. lbValue exit_runner = lb_find_package_value(m, str_lit("os"), str_lit("exit"));
  1957. auto exit_args = array_make<lbValue>(temporary_allocator(), 1);
  1958. exit_args[0] = lb_emit_select(p, result, lb_const_int(m, t_int, 0), lb_const_int(m, t_int, 1));
  1959. lb_emit_call(p, exit_runner, exit_args, ProcInlining_none);
  1960. } else {
  1961. if (m->info->entry_point != nullptr) {
  1962. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  1963. lb_emit_call(p, entry_point, {}, ProcInlining_no_inline);
  1964. }
  1965. if (call_cleanup) {
  1966. lbValue cleanup_runtime_value = {cleanup_runtime->value, cleanup_runtime->type};
  1967. lb_emit_call(p, cleanup_runtime_value, {}, ProcInlining_none);
  1968. }
  1969. if (is_dll_main) {
  1970. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 1, false));
  1971. } else {
  1972. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  1973. }
  1974. }
  1975. lb_end_procedure_body(p);
  1976. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  1977. if (is_arch_wasm()) {
  1978. lb_set_wasm_export_attributes(p->value, p->name);
  1979. }
  1980. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  1981. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main");
  1982. LLVMDumpValue(p->value);
  1983. gb_printf_err("\n\n\n\n");
  1984. LLVMVerifyFunction(p->value, LLVMAbortProcessAction);
  1985. }
  1986. lb_run_function_pass_manager(default_function_pass_manager, p, lbFunctionPassManager_default);
  1987. return p;
  1988. }
  1989. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p) {
  1990. if (p->is_done) {
  1991. return;
  1992. }
  1993. if (p->body != nullptr) { // Build Procedure
  1994. m->curr_procedure = p;
  1995. lb_begin_procedure_body(p);
  1996. lb_build_stmt(p, p->body);
  1997. lb_end_procedure_body(p);
  1998. p->is_done = true;
  1999. m->curr_procedure = nullptr;
  2000. }
  2001. lb_end_procedure(p);
  2002. // Add Flags
  2003. if (p->body != nullptr) {
  2004. if (p->name == "memcpy" || p->name == "memmove" ||
  2005. p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" ||
  2006. string_starts_with(p->name, str_lit("llvm.memcpy")) ||
  2007. string_starts_with(p->name, str_lit("llvm.memmove"))) {
  2008. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  2009. }
  2010. }
  2011. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  2012. char *llvm_error = nullptr;
  2013. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  2014. LLVMDumpValue(p->value);
  2015. gb_printf_err("\n\n\n\n");
  2016. String filepath_ll = lb_filepath_ll_for_module(m);
  2017. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  2018. gb_printf_err("LLVM Error: %s\n", llvm_error);
  2019. }
  2020. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  2021. exit_with_errors();
  2022. }
  2023. }
  2024. gb_internal bool lb_generate_code(lbGenerator *gen) {
  2025. TIME_SECTION("LLVM Initializtion");
  2026. isize thread_count = gb_max(build_context.thread_count, 1);
  2027. isize worker_count = thread_count-1;
  2028. bool do_threading = !!(LLVMIsMultithreaded() && USE_SEPARATE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  2029. lbModule *default_module = &gen->default_module;
  2030. CheckerInfo *info = gen->info;
  2031. auto *min_dep_set = &info->minimum_dependency_set;
  2032. switch (build_context.metrics.arch) {
  2033. case TargetArch_amd64:
  2034. case TargetArch_i386:
  2035. LLVMInitializeX86TargetInfo();
  2036. LLVMInitializeX86Target();
  2037. LLVMInitializeX86TargetMC();
  2038. LLVMInitializeX86AsmPrinter();
  2039. LLVMInitializeX86AsmParser();
  2040. LLVMInitializeX86Disassembler();
  2041. break;
  2042. case TargetArch_arm64:
  2043. LLVMInitializeAArch64TargetInfo();
  2044. LLVMInitializeAArch64Target();
  2045. LLVMInitializeAArch64TargetMC();
  2046. LLVMInitializeAArch64AsmPrinter();
  2047. LLVMInitializeAArch64AsmParser();
  2048. LLVMInitializeAArch64Disassembler();
  2049. break;
  2050. case TargetArch_wasm32:
  2051. case TargetArch_wasm64p32:
  2052. LLVMInitializeWebAssemblyTargetInfo();
  2053. LLVMInitializeWebAssemblyTarget();
  2054. LLVMInitializeWebAssemblyTargetMC();
  2055. LLVMInitializeWebAssemblyAsmPrinter();
  2056. LLVMInitializeWebAssemblyAsmParser();
  2057. LLVMInitializeWebAssemblyDisassembler();
  2058. break;
  2059. default:
  2060. LLVMInitializeAllTargetInfos();
  2061. LLVMInitializeAllTargets();
  2062. LLVMInitializeAllTargetMCs();
  2063. LLVMInitializeAllAsmPrinters();
  2064. LLVMInitializeAllAsmParsers();
  2065. LLVMInitializeAllDisassemblers();
  2066. break;
  2067. }
  2068. if (build_context.microarch == "native") {
  2069. LLVMInitializeNativeTarget();
  2070. }
  2071. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  2072. for (auto const &entry : gen->modules) {
  2073. LLVMSetTarget(entry.value->mod, target_triple);
  2074. }
  2075. LLVMTargetRef target = {};
  2076. char *llvm_error = nullptr;
  2077. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  2078. GB_ASSERT(target != nullptr);
  2079. TIME_SECTION("LLVM Create Target Machine");
  2080. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  2081. if (is_arch_wasm()) {
  2082. code_mode = LLVMCodeModelJITDefault;
  2083. } else if (is_arch_x86() && build_context.metrics.os == TargetOs_freestanding) {
  2084. code_mode = LLVMCodeModelKernel;
  2085. }
  2086. String llvm_cpu = get_final_microarchitecture();
  2087. gbString llvm_features = gb_string_make(temporary_allocator(), "");
  2088. String_Iterator it = {build_context.target_features_string, 0};
  2089. bool first = true;
  2090. for (;;) {
  2091. String str = string_split_iterator(&it, ',');
  2092. if (str == "") break;
  2093. if (!first) {
  2094. llvm_features = gb_string_appendc(llvm_features, ",");
  2095. }
  2096. first = false;
  2097. llvm_features = gb_string_appendc(llvm_features, "+");
  2098. llvm_features = gb_string_append_length(llvm_features, str.text, str.len);
  2099. }
  2100. debugf("CPU: %.*s, Features: %s\n", LIT(llvm_cpu), llvm_features);
  2101. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  2102. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  2103. if (!LB_USE_NEW_PASS_SYSTEM) {
  2104. build_context.optimization_level = gb_clamp(build_context.optimization_level, -1, 2);
  2105. }
  2106. switch (build_context.optimization_level) {
  2107. default:/*fallthrough*/
  2108. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  2109. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  2110. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  2111. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  2112. }
  2113. // NOTE(bill): Target Machine Creation
  2114. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  2115. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), 0, gen->modules.count);
  2116. // NOTE(dweiler): Dynamic libraries require position-independent code.
  2117. LLVMRelocMode reloc_mode = LLVMRelocDefault;
  2118. if (build_context.build_mode == BuildMode_DynamicLibrary) {
  2119. reloc_mode = LLVMRelocPIC;
  2120. }
  2121. switch (build_context.reloc_mode) {
  2122. case RelocMode_Default:
  2123. if (build_context.metrics.os == TargetOs_openbsd || build_context.metrics.os == TargetOs_haiku) {
  2124. // Always use PIC for OpenBSD and Haiku: they default to PIE
  2125. reloc_mode = LLVMRelocPIC;
  2126. }
  2127. break;
  2128. case RelocMode_Static:
  2129. reloc_mode = LLVMRelocStatic;
  2130. break;
  2131. case RelocMode_PIC:
  2132. reloc_mode = LLVMRelocPIC;
  2133. break;
  2134. case RelocMode_DynamicNoPIC:
  2135. reloc_mode = LLVMRelocDynamicNoPic;
  2136. break;
  2137. }
  2138. for (auto const &entry : gen->modules) {
  2139. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(
  2140. target, target_triple, (const char *)llvm_cpu.text,
  2141. llvm_features,
  2142. code_gen_level,
  2143. reloc_mode,
  2144. code_mode);
  2145. lbModule *m = entry.value;
  2146. m->target_machine = target_machine;
  2147. LLVMSetModuleDataLayout(m->mod, LLVMCreateTargetDataLayout(target_machine));
  2148. array_add(&target_machines, target_machine);
  2149. }
  2150. for (auto const &entry : gen->modules) {
  2151. lbModule *m = entry.value;
  2152. if (m->debug_builder) { // Debug Info
  2153. for (auto const &file_entry : info->files) {
  2154. AstFile *f = file_entry.value;
  2155. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  2156. cast(char const *)f->filename.text, f->filename.len,
  2157. cast(char const *)f->directory.text, f->directory.len);
  2158. lb_set_llvm_metadata(m, f, res);
  2159. }
  2160. TEMPORARY_ALLOCATOR_GUARD();
  2161. gbString producer = gb_string_make(temporary_allocator(), "odin");
  2162. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  2163. // #ifdef NIGHTLY
  2164. // producer = gb_string_appendc(producer, "-nightly");
  2165. // #endif
  2166. // #ifdef GIT_SHA
  2167. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  2168. // #endif
  2169. gbString split_name = gb_string_make(temporary_allocator(), "");
  2170. LLVMBool is_optimized = build_context.optimization_level > 0;
  2171. AstFile *init_file = m->info->init_package->files[0];
  2172. if (Entity *entry_point = m->info->entry_point) {
  2173. if (Ast *ident = entry_point->identifier.load()) {
  2174. if (ident->file_id) {
  2175. init_file = ident->file();
  2176. }
  2177. }
  2178. }
  2179. LLVMBool split_debug_inlining = build_context.build_mode == BuildMode_Assembly;
  2180. LLVMBool debug_info_for_profiling = false;
  2181. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  2182. lb_get_llvm_metadata(m, init_file),
  2183. producer, gb_string_length(producer),
  2184. is_optimized, "", 0,
  2185. 1, split_name, gb_string_length(split_name),
  2186. LLVMDWARFEmissionFull,
  2187. 0, split_debug_inlining,
  2188. debug_info_for_profiling,
  2189. "", 0, // sys_root
  2190. "", 0 // SDK
  2191. );
  2192. GB_ASSERT(m->debug_compile_unit != nullptr);
  2193. }
  2194. }
  2195. TIME_SECTION("LLVM Global Variables");
  2196. if (!build_context.no_rtti) {
  2197. lbModule *m = default_module;
  2198. { // Add type info data
  2199. isize max_type_info_count = info->minimum_dependency_type_info_set.count+1;
  2200. Type *t = alloc_type_array(t_type_info_ptr, max_type_info_count);
  2201. // IMPORTANT NOTE(bill): As LLVM does not have a union type, an array of unions cannot be initialized
  2202. // at compile time without cheating in some way. This means to emulate an array of unions is to use
  2203. // a giant packed struct of "corrected" data types.
  2204. LLVMTypeRef internal_llvm_type = lb_type(m, t);
  2205. LLVMValueRef g = LLVMAddGlobal(m->mod, internal_llvm_type, LB_TYPE_INFO_DATA_NAME);
  2206. LLVMSetInitializer(g, LLVMConstNull(internal_llvm_type));
  2207. LLVMSetLinkage(g, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
  2208. LLVMSetUnnamedAddress(g, LLVMGlobalUnnamedAddr);
  2209. LLVMSetGlobalConstant(g, true);
  2210. lbValue value = {};
  2211. value.value = g;
  2212. value.type = alloc_type_pointer(t);
  2213. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  2214. lb_add_entity(m, lb_global_type_info_data_entity, value);
  2215. }
  2216. { // Type info member buffer
  2217. // NOTE(bill): Removes need for heap allocation by making it global memory
  2218. isize count = 0;
  2219. isize offsets_extra = 0;
  2220. for (Type *t : m->info->type_info_types) {
  2221. isize index = lb_type_info_index(m->info, t, false);
  2222. if (index < 0) {
  2223. continue;
  2224. }
  2225. switch (t->kind) {
  2226. case Type_Union:
  2227. count += t->Union.variants.count;
  2228. break;
  2229. case Type_Struct:
  2230. count += t->Struct.fields.count;
  2231. break;
  2232. case Type_Tuple:
  2233. count += t->Tuple.variables.count;
  2234. break;
  2235. case Type_BitField:
  2236. count += t->BitField.fields.count;
  2237. // Twice is needed for the bit_offsets
  2238. offsets_extra += t->BitField.fields.count;
  2239. break;
  2240. }
  2241. }
  2242. auto const global_type_info_make = [](lbModule *m, char const *name, Type *elem_type, i64 count) -> lbAddr {
  2243. Type *t = alloc_type_array(elem_type, count);
  2244. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  2245. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  2246. LLVMSetLinkage(g, LLVMInternalLinkage);
  2247. lb_make_global_private_const(g);
  2248. return lb_addr({g, alloc_type_pointer(t)});
  2249. };
  2250. lb_global_type_info_member_types = global_type_info_make(m, LB_TYPE_INFO_TYPES_NAME, t_type_info_ptr, count);
  2251. lb_global_type_info_member_names = global_type_info_make(m, LB_TYPE_INFO_NAMES_NAME, t_string, count);
  2252. lb_global_type_info_member_offsets = global_type_info_make(m, LB_TYPE_INFO_OFFSETS_NAME, t_uintptr, count+offsets_extra);
  2253. lb_global_type_info_member_usings = global_type_info_make(m, LB_TYPE_INFO_USINGS_NAME, t_bool, count);
  2254. lb_global_type_info_member_tags = global_type_info_make(m, LB_TYPE_INFO_TAGS_NAME, t_string, count);
  2255. }
  2256. }
  2257. isize global_variable_max_count = 0;
  2258. bool already_has_entry_point = false;
  2259. for (Entity *e : info->entities) {
  2260. String name = e->token.string;
  2261. if (e->kind == Entity_Variable) {
  2262. global_variable_max_count++;
  2263. } else if (e->kind == Entity_Procedure) {
  2264. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  2265. GB_ASSERT(e == info->entry_point);
  2266. }
  2267. if (build_context.command_kind == Command_test &&
  2268. (e->Procedure.is_export || e->Procedure.link_name.len > 0)) {
  2269. String link_name = e->Procedure.link_name;
  2270. if (e->pkg->kind == Package_Runtime) {
  2271. if (link_name == "main" ||
  2272. link_name == "DllMain" ||
  2273. link_name == "WinMain" ||
  2274. link_name == "wWinMain" ||
  2275. link_name == "mainCRTStartup" ||
  2276. link_name == "_start") {
  2277. already_has_entry_point = true;
  2278. }
  2279. }
  2280. }
  2281. }
  2282. }
  2283. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  2284. for (DeclInfo *d : info->variable_init_order) {
  2285. Entity *e = d->entity;
  2286. if ((e->scope->flags & ScopeFlag_File) == 0) {
  2287. continue;
  2288. }
  2289. if (!ptr_set_exists(min_dep_set, e)) {
  2290. continue;
  2291. }
  2292. DeclInfo *decl = decl_info_of_entity(e);
  2293. if (decl == nullptr) {
  2294. continue;
  2295. }
  2296. GB_ASSERT(e->kind == Entity_Variable);
  2297. bool is_foreign = e->Variable.is_foreign;
  2298. bool is_export = e->Variable.is_export;
  2299. lbModule *m = &gen->default_module;
  2300. String name = lb_get_entity_name(m, e);
  2301. lbValue g = {};
  2302. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2303. g.type = alloc_type_pointer(e->type);
  2304. if (e->Variable.thread_local_model != "") {
  2305. LLVMSetThreadLocal(g.value, true);
  2306. String m = e->Variable.thread_local_model;
  2307. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  2308. if (m == "default") {
  2309. mode = LLVMGeneralDynamicTLSModel;
  2310. } else if (m == "localdynamic") {
  2311. mode = LLVMLocalDynamicTLSModel;
  2312. } else if (m == "initialexec") {
  2313. mode = LLVMInitialExecTLSModel;
  2314. } else if (m == "localexec") {
  2315. mode = LLVMLocalExecTLSModel;
  2316. } else {
  2317. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  2318. }
  2319. LLVMSetThreadLocalMode(g.value, mode);
  2320. }
  2321. if (is_foreign) {
  2322. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2323. LLVMSetDLLStorageClass(g.value, LLVMDLLImportStorageClass);
  2324. LLVMSetExternallyInitialized(g.value, true);
  2325. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  2326. lb_set_wasm_import_attributes(g.value, e, name);
  2327. } else {
  2328. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  2329. }
  2330. if (is_export) {
  2331. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  2332. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  2333. } else if (!is_foreign) {
  2334. LLVMSetLinkage(g.value, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
  2335. }
  2336. lb_set_linkage_from_entity_flags(m, g.value, e->flags);
  2337. if (e->Variable.link_section.len > 0) {
  2338. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  2339. }
  2340. lbGlobalVariable var = {};
  2341. var.var = g;
  2342. var.decl = decl;
  2343. if (decl->init_expr != nullptr) {
  2344. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  2345. if (!is_type_any(e->type) && !is_type_union(e->type)) {
  2346. if (tav.mode != Addressing_Invalid) {
  2347. if (tav.value.kind != ExactValue_Invalid) {
  2348. ExactValue v = tav.value;
  2349. lbValue init = lb_const_value(m, tav.type, v);
  2350. LLVMSetInitializer(g.value, init.value);
  2351. var.is_initialized = true;
  2352. }
  2353. }
  2354. }
  2355. if (!var.is_initialized && is_type_untyped_nil(tav.type)) {
  2356. var.is_initialized = true;
  2357. }
  2358. }
  2359. array_add(&global_variables, var);
  2360. lb_add_entity(m, e, g);
  2361. lb_add_member(m, name, g);
  2362. if (m->debug_builder) {
  2363. String global_name = e->token.string;
  2364. if (global_name.len != 0 && global_name != "_") {
  2365. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  2366. LLVMMetadataRef llvm_scope = llvm_file;
  2367. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  2368. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2369. LLVMMetadataRef llvm_decl = nullptr;
  2370. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  2371. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  2372. m->debug_builder, llvm_scope,
  2373. cast(char const *)global_name.text, global_name.len,
  2374. "", 0, // linkage
  2375. llvm_file, e->token.pos.line,
  2376. lb_debug_type(m, e->type),
  2377. local_to_unit,
  2378. llvm_expr,
  2379. llvm_decl,
  2380. align_in_bits
  2381. );
  2382. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  2383. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  2384. }
  2385. }
  2386. }
  2387. TIME_SECTION("LLVM Runtime Objective-C Names Creation");
  2388. gen->objc_names = lb_create_objc_names(default_module);
  2389. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables & @(init))");
  2390. gen->startup_runtime = lb_create_startup_runtime(default_module, gen->objc_names, global_variables);
  2391. TIME_SECTION("LLVM Runtime Cleanup Creation & @(fini)");
  2392. gen->cleanup_runtime = lb_create_cleanup_runtime(default_module);
  2393. if (build_context.ODIN_DEBUG) {
  2394. for (auto const &entry : builtin_pkg->scope->elements) {
  2395. Entity *e = entry.value;
  2396. add_debug_info_for_global_constant_from_entity(gen, e);
  2397. }
  2398. }
  2399. if (gen->modules.count <= 1) {
  2400. do_threading = false;
  2401. }
  2402. TIME_SECTION("LLVM Global Procedures and Types");
  2403. lb_create_global_procedures_and_types(gen, info, do_threading);
  2404. TIME_SECTION("LLVM Procedure Generation");
  2405. lb_generate_procedures(gen, do_threading);
  2406. if (build_context.command_kind == Command_test && !already_has_entry_point) {
  2407. TIME_SECTION("LLVM main");
  2408. lb_create_main_procedure(default_module, gen->startup_runtime, gen->cleanup_runtime);
  2409. }
  2410. TIME_SECTION("LLVM Procedure Generation (missing)");
  2411. lb_generate_missing_procedures(gen, do_threading);
  2412. if (gen->objc_names) {
  2413. TIME_SECTION("Finalize objc names");
  2414. lb_finalize_objc_names(gen->objc_names);
  2415. }
  2416. if (build_context.ODIN_DEBUG) {
  2417. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  2418. lb_debug_info_complete_types_and_finalize(gen);
  2419. }
  2420. if (do_threading) {
  2421. isize non_empty_module_count = 0;
  2422. for (auto const &entry : gen->modules) {
  2423. lbModule *m = entry.value;
  2424. if (!lb_is_module_empty(m)) {
  2425. non_empty_module_count += 1;
  2426. }
  2427. }
  2428. if (non_empty_module_count <= 1) {
  2429. do_threading = false;
  2430. }
  2431. }
  2432. TIME_SECTION("LLVM Function Pass");
  2433. lb_llvm_function_passes(gen, do_threading && !build_context.ODIN_DEBUG);
  2434. TIME_SECTION("LLVM Module Pass");
  2435. lb_llvm_module_passes(gen, do_threading);
  2436. TIME_SECTION("LLVM Module Verification");
  2437. if (!lb_llvm_module_verification(gen, do_threading)) {
  2438. return false;
  2439. }
  2440. llvm_error = nullptr;
  2441. defer (LLVMDisposeMessage(llvm_error));
  2442. if (build_context.keep_temp_files ||
  2443. build_context.build_mode == BuildMode_LLVM_IR) {
  2444. TIME_SECTION("LLVM Print Module to File");
  2445. for (auto const &entry : gen->modules) {
  2446. lbModule *m = entry.value;
  2447. if (lb_is_module_empty(m)) {
  2448. continue;
  2449. }
  2450. String filepath_ll = lb_filepath_ll_for_module(m);
  2451. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  2452. gb_printf_err("LLVM Error: %s\n", llvm_error);
  2453. exit_with_errors();
  2454. return false;
  2455. }
  2456. array_add(&gen->output_temp_paths, filepath_ll);
  2457. }
  2458. if (build_context.build_mode == BuildMode_LLVM_IR) {
  2459. return true;
  2460. }
  2461. }
  2462. TIME_SECTION("LLVM Add Foreign Library Paths");
  2463. lb_add_foreign_library_paths(gen);
  2464. TIME_SECTION("LLVM Object Generation");
  2465. if (build_context.ignore_llvm_build) {
  2466. gb_printf_err("LLVM object generation has been ignored!\n");
  2467. return false;
  2468. }
  2469. if (!lb_llvm_object_generation(gen, do_threading)) {
  2470. return false;
  2471. }
  2472. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  2473. if (build_context.metrics.os == TargetOs_windows) {
  2474. auto paths = array_make<String>(heap_allocator(), 0, 1);
  2475. String path = concatenate_strings(permanent_allocator(), build_context.ODIN_ROOT, str_lit("\\bin\\llvm\\windows\\clang_rt.asan-x86_64.lib"));
  2476. array_add(&paths, path);
  2477. Entity *lib = alloc_entity_library_name(nullptr, make_token_ident("asan_lib"), nullptr, slice_from_array(paths), str_lit("asan_lib"));
  2478. array_add(&gen->foreign_libraries, lib);
  2479. } else if (build_context.metrics.os == TargetOs_darwin || build_context.metrics.os == TargetOs_linux) {
  2480. if (!build_context.extra_linker_flags.text) {
  2481. build_context.extra_linker_flags = str_lit("-fsanitize=address");
  2482. } else {
  2483. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=address"));
  2484. }
  2485. }
  2486. }
  2487. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  2488. if (build_context.metrics.os == TargetOs_darwin || build_context.metrics.os == TargetOs_linux) {
  2489. if (!build_context.extra_linker_flags.text) {
  2490. build_context.extra_linker_flags = str_lit("-fsanitize=memory");
  2491. } else {
  2492. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=memory"));
  2493. }
  2494. }
  2495. }
  2496. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  2497. if (build_context.metrics.os == TargetOs_darwin || build_context.metrics.os == TargetOs_linux) {
  2498. if (!build_context.extra_linker_flags.text) {
  2499. build_context.extra_linker_flags = str_lit("-fsanitize=thread");
  2500. } else {
  2501. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=thread"));
  2502. }
  2503. }
  2504. }
  2505. array_sort(gen->foreign_libraries, foreign_library_cmp);
  2506. return true;
  2507. }