llvm_backend.cpp 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664
  1. #define MULTITHREAD_OBJECT_GENERATION 1
  2. #ifndef MULTITHREAD_OBJECT_GENERATION
  3. #define MULTITHREAD_OBJECT_GENERATION 0
  4. #endif
  5. #ifndef USE_SEPARATE_MODULES
  6. #define USE_SEPARATE_MODULES build_context.use_separate_modules
  7. #endif
  8. #ifndef LLVM_IGNORE_VERIFICATION
  9. #define LLVM_IGNORE_VERIFICATION build_context.internal_ignore_llvm_verification
  10. #endif
  11. #ifndef LLVM_WEAK_MONOMORPHIZATION
  12. #define LLVM_WEAK_MONOMORPHIZATION (USE_SEPARATE_MODULES && build_context.internal_weak_monomorphization)
  13. #endif
  14. #include "llvm_backend.hpp"
  15. #include "llvm_abi.cpp"
  16. #include "llvm_backend_opt.cpp"
  17. #include "llvm_backend_general.cpp"
  18. #include "llvm_backend_debug.cpp"
  19. #include "llvm_backend_const.cpp"
  20. #include "llvm_backend_type.cpp"
  21. #include "llvm_backend_utility.cpp"
  22. #include "llvm_backend_expr.cpp"
  23. #include "llvm_backend_stmt.cpp"
  24. #include "llvm_backend_proc.cpp"
  25. gb_internal String get_default_microarchitecture() {
  26. String default_march = str_lit("generic");
  27. if (build_context.metrics.arch == TargetArch_amd64) {
  28. // NOTE(bill): x86-64-v2 is more than enough for everyone
  29. //
  30. // x86-64: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2
  31. // x86-64-v2: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3
  32. // x86-64-v3: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE
  33. // x86-64-v4: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL
  34. if (ODIN_LLVM_MINIMUM_VERSION_12) {
  35. if (build_context.metrics.os == TargetOs_freestanding) {
  36. default_march = str_lit("x86-64");
  37. } else {
  38. default_march = str_lit("x86-64-v2");
  39. }
  40. }
  41. } else if (build_context.metrics.arch == TargetArch_riscv64) {
  42. default_march = str_lit("generic-rv64");
  43. }
  44. return default_march;
  45. }
  46. gb_internal String get_final_microarchitecture() {
  47. BuildContext *bc = &build_context;
  48. String microarch = bc->microarch;
  49. if (microarch.len == 0) {
  50. microarch = get_default_microarchitecture();
  51. } else if (microarch == str_lit("native")) {
  52. microarch = make_string_c(LLVMGetHostCPUName());
  53. }
  54. return microarch;
  55. }
  56. gb_internal String get_default_features() {
  57. BuildContext *bc = &build_context;
  58. int off = 0;
  59. for (int i = 0; i < bc->metrics.arch; i += 1) {
  60. off += target_microarch_counts[i];
  61. }
  62. String microarch = get_final_microarchitecture();
  63. // NOTE(laytan): for riscv64 to work properly with Odin, we need to enforce some features.
  64. // and we also overwrite the generic target to include more features so we don't default to
  65. // a potato feature set.
  66. if (bc->metrics.arch == TargetArch_riscv64) {
  67. if (microarch == str_lit("generic-rv64")) {
  68. // This is what clang does by default (on -march=rv64gc for General Computing), seems good to also default to.
  69. String features = str_lit("64bit,a,c,d,f,m,relax,zicsr,zifencei");
  70. // Update the features string so LLVM uses it later.
  71. if (bc->target_features_string.len > 0) {
  72. bc->target_features_string = concatenate3_strings(permanent_allocator(), features, str_lit(","), bc->target_features_string);
  73. } else {
  74. bc->target_features_string = features;
  75. }
  76. return features;
  77. }
  78. }
  79. for (int i = off; i < off+target_microarch_counts[bc->metrics.arch]; i += 1) {
  80. if (microarch_features_list[i].microarch == microarch) {
  81. return microarch_features_list[i].features;
  82. }
  83. }
  84. GB_PANIC("unknown microarch: %.*s", LIT(microarch));
  85. return {};
  86. }
  87. gb_internal void lb_add_foreign_library_path(lbModule *m, Entity *e) {
  88. if (e == nullptr) {
  89. return;
  90. }
  91. GB_ASSERT(e->kind == Entity_LibraryName);
  92. GB_ASSERT(e->flags & EntityFlag_Used);
  93. mutex_lock(&m->gen->foreign_mutex);
  94. if (!ptr_set_update(&m->gen->foreign_libraries_set, e)) {
  95. array_add(&m->gen->foreign_libraries, e);
  96. }
  97. mutex_unlock(&m->gen->foreign_mutex);
  98. }
  99. gb_internal GB_COMPARE_PROC(foreign_library_cmp) {
  100. int cmp = 0;
  101. Entity *x = *(Entity **)a;
  102. Entity *y = *(Entity **)b;
  103. if (x == y) {
  104. return 0;
  105. }
  106. GB_ASSERT(x->kind == Entity_LibraryName);
  107. GB_ASSERT(y->kind == Entity_LibraryName);
  108. cmp = i64_cmp(x->LibraryName.priority_index, y->LibraryName.priority_index);
  109. if (cmp) {
  110. return cmp;
  111. }
  112. if (x->pkg != y->pkg) {
  113. isize order_x = x->pkg ? x->pkg->order : 0;
  114. isize order_y = y->pkg ? y->pkg->order : 0;
  115. cmp = isize_cmp(order_x, order_y);
  116. if (cmp) {
  117. return cmp;
  118. }
  119. }
  120. if (x->file != y->file) {
  121. String fullpath_x = x->file ? x->file->fullpath : (String{});
  122. String fullpath_y = y->file ? y->file->fullpath : (String{});
  123. String file_x = filename_from_path(fullpath_x);
  124. String file_y = filename_from_path(fullpath_y);
  125. cmp = string_compare(file_x, file_y);
  126. if (cmp) {
  127. return cmp;
  128. }
  129. }
  130. cmp = u64_cmp(x->order_in_src, y->order_in_src);
  131. if (cmp) {
  132. return cmp;
  133. }
  134. return i32_cmp(x->token.pos.offset, y->token.pos.offset);
  135. }
  136. gb_internal void lb_set_entity_from_other_modules_linkage_correctly(lbModule *other_module, Entity *e, String const &name) {
  137. if (other_module == nullptr) {
  138. return;
  139. }
  140. char const *cname = alloc_cstring(permanent_allocator(), name);
  141. mpsc_enqueue(&other_module->gen->entities_to_correct_linkage, lbEntityCorrection{other_module, e, cname});
  142. }
  143. gb_internal void lb_correct_entity_linkage(lbGenerator *gen) {
  144. for (lbEntityCorrection ec = {}; mpsc_dequeue(&gen->entities_to_correct_linkage, &ec); /**/) {
  145. LLVMValueRef other_global = nullptr;
  146. if (ec.e->kind == Entity_Variable) {
  147. other_global = LLVMGetNamedGlobal(ec.other_module->mod, ec.cname);
  148. if (other_global) {
  149. LLVMSetLinkage(other_global, LLVMWeakAnyLinkage);
  150. if (!ec.e->Variable.is_export && !ec.e->Variable.is_foreign) {
  151. LLVMSetVisibility(other_global, LLVMHiddenVisibility);
  152. }
  153. }
  154. } else if (ec.e->kind == Entity_Procedure) {
  155. other_global = LLVMGetNamedFunction(ec.other_module->mod, ec.cname);
  156. if (other_global) {
  157. LLVMSetLinkage(other_global, LLVMWeakAnyLinkage);
  158. if (!ec.e->Procedure.is_export && !ec.e->Procedure.is_foreign) {
  159. LLVMSetVisibility(other_global, LLVMHiddenVisibility);
  160. }
  161. }
  162. }
  163. }
  164. }
  165. gb_internal void lb_emit_init_context(lbProcedure *p, lbAddr addr) {
  166. TEMPORARY_ALLOCATOR_GUARD();
  167. GB_ASSERT(addr.kind == lbAddr_Context);
  168. GB_ASSERT(addr.ctx.sel.index.count == 0);
  169. auto args = array_make<lbValue>(temporary_allocator(), 1);
  170. args[0] = addr.addr;
  171. lb_emit_runtime_call(p, "__init_context", args);
  172. }
  173. gb_internal lbContextData *lb_push_context_onto_stack_from_implicit_parameter(lbProcedure *p) {
  174. Type *pt = base_type(p->type);
  175. GB_ASSERT(pt->kind == Type_Proc);
  176. GB_ASSERT(pt->Proc.calling_convention == ProcCC_Odin);
  177. String name = str_lit("__.context_ptr");
  178. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false);
  179. e->flags |= EntityFlag_NoAlias;
  180. LLVMValueRef context_ptr = LLVMGetParam(p->value, LLVMCountParams(p->value)-1);
  181. LLVMSetValueName2(context_ptr, cast(char const *)name.text, name.len);
  182. context_ptr = LLVMBuildPointerCast(p->builder, context_ptr, lb_type(p->module, e->type), "");
  183. lbValue param = {context_ptr, e->type};
  184. lb_add_entity(p->module, e, param);
  185. lbAddr ctx_addr = {};
  186. ctx_addr.kind = lbAddr_Context;
  187. ctx_addr.addr = param;
  188. lbContextData *cd = array_add_and_get(&p->context_stack);
  189. cd->ctx = ctx_addr;
  190. cd->scope_index = -1;
  191. cd->uses = +1; // make sure it has been used already
  192. return cd;
  193. }
  194. gb_internal lbContextData *lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) {
  195. ctx.kind = lbAddr_Context;
  196. lbContextData *cd = array_add_and_get(&p->context_stack);
  197. cd->ctx = ctx;
  198. cd->scope_index = p->scope_index;
  199. return cd;
  200. }
  201. gb_internal String lb_internal_gen_name_from_type(char const *prefix, Type *type) {
  202. gbString str = gb_string_make(permanent_allocator(), prefix);
  203. u64 hash = type_hash_canonical_type(type);
  204. str = gb_string_appendc(str, "-");
  205. str = gb_string_append_fmt(str, "%llu", cast(unsigned long long)hash);
  206. String proc_name = make_string(cast(u8 const *)str, gb_string_length(str));
  207. return proc_name;
  208. }
  209. gb_internal void lb_equal_proc_generate_body(lbModule *m, lbProcedure *p) {
  210. Type *type = p->internal_gen_type;
  211. Type *pt = alloc_type_pointer(type);
  212. LLVMTypeRef ptr_type = lb_type(m, pt);
  213. lb_begin_procedure_body(p);
  214. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  215. // lb_add_attribute_to_proc(m, p->value, "readonly");
  216. lb_add_attribute_to_proc(m, p->value, "nounwind");
  217. LLVMValueRef x = LLVMGetParam(p->value, 0);
  218. LLVMValueRef y = LLVMGetParam(p->value, 1);
  219. x = LLVMBuildPointerCast(p->builder, x, ptr_type, "");
  220. y = LLVMBuildPointerCast(p->builder, y, ptr_type, "");
  221. lbValue lhs = {x, pt};
  222. lbValue rhs = {y, pt};
  223. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  224. lb_add_proc_attribute_at_index(p, 1+1, "nonnull");
  225. lbBlock *block_same_ptr = lb_create_block(p, "same_ptr");
  226. lbBlock *block_diff_ptr = lb_create_block(p, "diff_ptr");
  227. lbValue same_ptr = lb_emit_comp(p, Token_CmpEq, lhs, rhs);
  228. lb_emit_if(p, same_ptr, block_same_ptr, block_diff_ptr);
  229. lb_start_block(p, block_same_ptr);
  230. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  231. lb_start_block(p, block_diff_ptr);
  232. if (type->kind == Type_Struct) {
  233. type_set_offsets(type);
  234. lbBlock *block_false = lb_create_block(p, "bfalse");
  235. lbValue res = lb_const_bool(m, t_bool, true);
  236. for_array(i, type->Struct.fields) {
  237. lbBlock *next_block = lb_create_block(p, "btrue");
  238. lbValue pleft = lb_emit_struct_ep(p, lhs, cast(i32)i);
  239. lbValue pright = lb_emit_struct_ep(p, rhs, cast(i32)i);
  240. lbValue left = lb_emit_load(p, pleft);
  241. lbValue right = lb_emit_load(p, pright);
  242. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  243. lb_emit_if(p, ok, next_block, block_false);
  244. lb_emit_jump(p, next_block);
  245. lb_start_block(p, next_block);
  246. }
  247. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  248. lb_start_block(p, block_false);
  249. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  250. } else if (type->kind == Type_Union) {
  251. if (type_size_of(type) == 0) {
  252. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  253. } else if (is_type_union_maybe_pointer(type)) {
  254. Type *v = type->Union.variants[0];
  255. Type *pv = alloc_type_pointer(v);
  256. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, pv));
  257. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, pv));
  258. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  259. ok = lb_emit_conv(p, ok, t_bool);
  260. LLVMBuildRet(p->builder, ok.value);
  261. } else {
  262. lbBlock *block_false = lb_create_block(p, "bfalse");
  263. lbBlock *block_switch = lb_create_block(p, "bswitch");
  264. lbValue left_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, lhs));
  265. lbValue right_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, rhs));
  266. lbValue tag_eq = lb_emit_comp(p, Token_CmpEq, left_tag, right_tag);
  267. lb_emit_if(p, tag_eq, block_switch, block_false);
  268. lb_start_block(p, block_switch);
  269. unsigned variant_count = cast(unsigned)type->Union.variants.count;
  270. if (type->Union.kind != UnionType_no_nil) {
  271. variant_count += 1;
  272. }
  273. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, left_tag.value, block_false->block, variant_count);
  274. if (type->Union.kind != UnionType_no_nil) {
  275. lbBlock *case_block = lb_create_block(p, "bcase");
  276. lb_start_block(p, case_block);
  277. lbValue case_tag = lb_const_int(p->module, union_tag_type(type), 0);
  278. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 1, false));
  279. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  280. }
  281. for (Type *v : type->Union.variants) {
  282. lbBlock *case_block = lb_create_block(p, "bcase");
  283. lb_start_block(p, case_block);
  284. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  285. Type *vp = alloc_type_pointer(v);
  286. lbValue left = lb_emit_load(p, lb_emit_conv(p, lhs, vp));
  287. lbValue right = lb_emit_load(p, lb_emit_conv(p, rhs, vp));
  288. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  289. ok = lb_emit_conv(p, ok, t_bool);
  290. LLVMBuildRet(p->builder, ok.value);
  291. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  292. }
  293. lb_start_block(p, block_false);
  294. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_bool), 0, false));
  295. }
  296. } else {
  297. lbValue left = lb_emit_load(p, lhs);
  298. lbValue right = lb_emit_load(p, rhs);
  299. lbValue ok = lb_emit_comp(p, Token_CmpEq, left, right);
  300. ok = lb_emit_conv(p, ok, t_bool);
  301. LLVMBuildRet(p->builder, ok.value);
  302. }
  303. lb_end_procedure_body(p);
  304. }
  305. gb_internal lbValue lb_equal_proc_for_type(lbModule *m, Type *type) {
  306. type = base_type(type);
  307. GB_ASSERT(is_type_comparable(type));
  308. String proc_name = lb_internal_gen_name_from_type("__$equal", type);
  309. lbProcedure **found = string_map_get(&m->gen_procs, proc_name);
  310. if (found) {
  311. lbProcedure *p = *found;
  312. GB_ASSERT(p != nullptr);
  313. return {p->value, p->type};
  314. }
  315. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_equal_proc);
  316. string_map_set(&m->gen_procs, proc_name, p);
  317. p->internal_gen_type = type;
  318. p->generate_body = lb_equal_proc_generate_body;
  319. // p->generate_body(m, p);
  320. mpsc_enqueue(&m->procedures_to_generate, p);
  321. return {p->value, p->type};
  322. }
  323. gb_internal lbValue lb_simple_compare_hash(lbProcedure *p, Type *type, lbValue data, lbValue seed) {
  324. TEMPORARY_ALLOCATOR_GUARD();
  325. GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type));
  326. auto args = array_make<lbValue>(temporary_allocator(), 3);
  327. args[0] = data;
  328. args[1] = seed;
  329. args[2] = lb_const_int(p->module, t_int, type_size_of(type));
  330. return lb_emit_runtime_call(p, "default_hasher", args);
  331. }
  332. gb_internal void lb_add_callsite_force_inline(lbProcedure *p, lbValue ret_value) {
  333. LLVMAddCallSiteAttribute(ret_value.value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  334. }
  335. gb_internal lbValue lb_hasher_proc_for_type(lbModule *m, Type *type) {
  336. type = core_type(type);
  337. GB_ASSERT_MSG(is_type_comparable(type), "%s", type_to_string(type));
  338. Type *pt = alloc_type_pointer(type);
  339. String proc_name = lb_internal_gen_name_from_type("__$hasher", type);
  340. lbProcedure **found = string_map_get(&m->gen_procs, proc_name);
  341. if (found) {
  342. GB_ASSERT(*found != nullptr);
  343. return {(*found)->value, (*found)->type};
  344. }
  345. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_hasher_proc);
  346. string_map_set(&m->gen_procs, proc_name, p);
  347. lb_begin_procedure_body(p);
  348. defer (lb_end_procedure_body(p));
  349. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  350. // lb_add_attribute_to_proc(m, p->value, "readonly");
  351. lb_add_attribute_to_proc(m, p->value, "nounwind");
  352. LLVMValueRef x = LLVMGetParam(p->value, 0);
  353. LLVMValueRef y = LLVMGetParam(p->value, 1);
  354. lbValue data = {x, t_rawptr};
  355. lbValue seed = {y, t_uintptr};
  356. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  357. // lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  358. if (is_type_simple_compare(type)) {
  359. lbValue res = lb_simple_compare_hash(p, type, data, seed);
  360. lb_add_callsite_force_inline(p, res);
  361. LLVMBuildRet(p->builder, res.value);
  362. return {p->value, p->type};
  363. }
  364. TEMPORARY_ALLOCATOR_GUARD();
  365. if (type->kind == Type_Struct) {
  366. type_set_offsets(type);
  367. data = lb_emit_conv(p, data, t_u8_ptr);
  368. auto args = array_make<lbValue>(temporary_allocator(), 2);
  369. for_array(i, type->Struct.fields) {
  370. GB_ASSERT(type->Struct.offsets != nullptr);
  371. i64 offset = type->Struct.offsets[i];
  372. Entity *field = type->Struct.fields[i];
  373. lbValue field_hasher = lb_hasher_proc_for_type(m, field->type);
  374. lbValue ptr = lb_emit_ptr_offset(p, data, lb_const_int(m, t_uintptr, offset));
  375. args[0] = ptr;
  376. args[1] = seed;
  377. seed = lb_emit_call(p, field_hasher, args);
  378. }
  379. LLVMBuildRet(p->builder, seed.value);
  380. } else if (type->kind == Type_Union) {
  381. auto args = array_make<lbValue>(temporary_allocator(), 2);
  382. if (is_type_union_maybe_pointer(type)) {
  383. Type *v = type->Union.variants[0];
  384. lbValue variant_hasher = lb_hasher_proc_for_type(m, v);
  385. args[0] = data;
  386. args[1] = seed;
  387. lbValue res = lb_emit_call(p, variant_hasher, args);
  388. lb_add_callsite_force_inline(p, res);
  389. LLVMBuildRet(p->builder, res.value);
  390. }
  391. lbBlock *end_block = lb_create_block(p, "bend");
  392. data = lb_emit_conv(p, data, pt);
  393. lbValue tag_ptr = lb_emit_union_tag_ptr(p, data);
  394. lbValue tag = lb_emit_load(p, tag_ptr);
  395. LLVMValueRef v_switch = LLVMBuildSwitch(p->builder, tag.value, end_block->block, cast(unsigned)type->Union.variants.count);
  396. for (Type *v : type->Union.variants) {
  397. lbBlock *case_block = lb_create_block(p, "bcase");
  398. lb_start_block(p, case_block);
  399. lbValue case_tag = lb_const_union_tag(p->module, type, v);
  400. lbValue variant_hasher = lb_hasher_proc_for_type(m, v);
  401. args[0] = data;
  402. args[1] = seed;
  403. lbValue res = lb_emit_call(p, variant_hasher, args);
  404. LLVMBuildRet(p->builder, res.value);
  405. LLVMAddCase(v_switch, case_tag.value, case_block->block);
  406. }
  407. lb_start_block(p, end_block);
  408. LLVMBuildRet(p->builder, seed.value);
  409. } else if (type->kind == Type_Array) {
  410. lbAddr pres = lb_add_local_generated(p, t_uintptr, false);
  411. lb_addr_store(p, pres, seed);
  412. auto args = array_make<lbValue>(temporary_allocator(), 2);
  413. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->Array.elem);
  414. auto loop_data = lb_loop_start(p, cast(isize)type->Array.count, t_i32);
  415. data = lb_emit_conv(p, data, pt);
  416. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  417. args[0] = ptr;
  418. args[1] = lb_addr_load(p, pres);
  419. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  420. lb_addr_store(p, pres, new_seed);
  421. lb_loop_end(p, loop_data);
  422. lbValue res = lb_addr_load(p, pres);
  423. LLVMBuildRet(p->builder, res.value);
  424. } else if (type->kind == Type_EnumeratedArray) {
  425. lbAddr res = lb_add_local_generated(p, t_uintptr, false);
  426. lb_addr_store(p, res, seed);
  427. auto args = array_make<lbValue>(temporary_allocator(), 2);
  428. lbValue elem_hasher = lb_hasher_proc_for_type(m, type->EnumeratedArray.elem);
  429. auto loop_data = lb_loop_start(p, cast(isize)type->EnumeratedArray.count, t_i32);
  430. data = lb_emit_conv(p, data, pt);
  431. lbValue ptr = lb_emit_array_ep(p, data, loop_data.idx);
  432. args[0] = ptr;
  433. args[1] = lb_addr_load(p, res);
  434. lbValue new_seed = lb_emit_call(p, elem_hasher, args);
  435. lb_addr_store(p, res, new_seed);
  436. lb_loop_end(p, loop_data);
  437. lbValue vres = lb_addr_load(p, res);
  438. LLVMBuildRet(p->builder, vres.value);
  439. } else if (is_type_cstring(type)) {
  440. auto args = array_make<lbValue>(temporary_allocator(), 2);
  441. args[0] = data;
  442. args[1] = seed;
  443. lbValue res = lb_emit_runtime_call(p, "default_hasher_cstring", args);
  444. lb_add_callsite_force_inline(p, res);
  445. LLVMBuildRet(p->builder, res.value);
  446. } else if (is_type_string(type)) {
  447. auto args = array_make<lbValue>(temporary_allocator(), 2);
  448. args[0] = data;
  449. args[1] = seed;
  450. lbValue res = lb_emit_runtime_call(p, "default_hasher_string", args);
  451. lb_add_callsite_force_inline(p, res);
  452. LLVMBuildRet(p->builder, res.value);
  453. } else if (is_type_float(type)) {
  454. lbValue ptr = lb_emit_conv(p, data, pt);
  455. lbValue v = lb_emit_load(p, ptr);
  456. v = lb_emit_conv(p, v, t_f64);
  457. auto args = array_make<lbValue>(temporary_allocator(), 2);
  458. args[0] = v;
  459. args[1] = seed;
  460. lbValue res = lb_emit_runtime_call(p, "default_hasher_f64", args);
  461. lb_add_callsite_force_inline(p, res);
  462. LLVMBuildRet(p->builder, res.value);
  463. } else if (is_type_complex(type)) {
  464. lbValue ptr = lb_emit_conv(p, data, pt);
  465. lbValue xp = lb_emit_struct_ep(p, ptr, 0);
  466. lbValue yp = lb_emit_struct_ep(p, ptr, 1);
  467. lbValue x = lb_emit_conv(p, lb_emit_load(p, xp), t_f64);
  468. lbValue y = lb_emit_conv(p, lb_emit_load(p, yp), t_f64);
  469. auto args = array_make<lbValue>(temporary_allocator(), 3);
  470. args[0] = x;
  471. args[1] = y;
  472. args[2] = seed;
  473. lbValue res = lb_emit_runtime_call(p, "default_hasher_complex128", args);
  474. lb_add_callsite_force_inline(p, res);
  475. LLVMBuildRet(p->builder, res.value);
  476. } else if (is_type_quaternion(type)) {
  477. lbValue ptr = lb_emit_conv(p, data, pt);
  478. lbValue xp = lb_emit_struct_ep(p, ptr, 0);
  479. lbValue yp = lb_emit_struct_ep(p, ptr, 1);
  480. lbValue zp = lb_emit_struct_ep(p, ptr, 2);
  481. lbValue wp = lb_emit_struct_ep(p, ptr, 3);
  482. lbValue x = lb_emit_conv(p, lb_emit_load(p, xp), t_f64);
  483. lbValue y = lb_emit_conv(p, lb_emit_load(p, yp), t_f64);
  484. lbValue z = lb_emit_conv(p, lb_emit_load(p, zp), t_f64);
  485. lbValue w = lb_emit_conv(p, lb_emit_load(p, wp), t_f64);
  486. auto args = array_make<lbValue>(temporary_allocator(), 5);
  487. args[0] = x;
  488. args[1] = y;
  489. args[2] = z;
  490. args[3] = w;
  491. args[4] = seed;
  492. lbValue res = lb_emit_runtime_call(p, "default_hasher_quaternion256", args);
  493. lb_add_callsite_force_inline(p, res);
  494. LLVMBuildRet(p->builder, res.value);
  495. } else {
  496. GB_PANIC("Unhandled type for hasher: %s", type_to_string(type));
  497. }
  498. return {p->value, p->type};
  499. }
  500. #define LLVM_SET_VALUE_NAME(value, name) LLVMSetValueName2((value), (name), gb_count_of((name))-1);
  501. gb_internal lbValue lb_map_get_proc_for_type(lbModule *m, Type *type) {
  502. GB_ASSERT(!build_context.dynamic_map_calls);
  503. type = base_type(type);
  504. GB_ASSERT(type->kind == Type_Map);
  505. String proc_name = lb_internal_gen_name_from_type("__$map_get", type);
  506. lbProcedure **found = string_map_get(&m->gen_procs, proc_name);
  507. if (found) {
  508. GB_ASSERT(*found != nullptr);
  509. return {(*found)->value, (*found)->type};
  510. }
  511. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_get_proc);
  512. string_map_set(&m->gen_procs, proc_name, p);
  513. p->internal_gen_type = type;
  514. lb_begin_procedure_body(p);
  515. defer (lb_end_procedure_body(p));
  516. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  517. lb_add_attribute_to_proc(m, p->value, "nounwind");
  518. if (build_context.ODIN_DEBUG) {
  519. lb_add_attribute_to_proc(m, p->value, "noinline");
  520. }
  521. LLVMValueRef x = LLVMGetParam(p->value, 0);
  522. LLVMValueRef y = LLVMGetParam(p->value, 1);
  523. LLVMValueRef z = LLVMGetParam(p->value, 2);
  524. lbValue map_ptr = {x, t_rawptr};
  525. lbValue h = {y, t_uintptr};
  526. lbValue key_ptr = {z, t_rawptr};
  527. LLVM_SET_VALUE_NAME(h.value, "hash");
  528. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  529. lb_add_proc_attribute_at_index(p, 1+0, "readonly");
  530. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  531. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  532. lbBlock *loop_block = lb_create_block(p, "loop");
  533. lbBlock *hash_block = lb_create_block(p, "hash");
  534. lbBlock *probe_block = lb_create_block(p, "probe");
  535. lbBlock *increment_block = lb_create_block(p, "increment");
  536. lbBlock *hash_compare_block = lb_create_block(p, "hash_compare");
  537. lbBlock *key_compare_block = lb_create_block(p, "key_compare");
  538. lbBlock *value_block = lb_create_block(p, "value");
  539. lbBlock *nil_block = lb_create_block(p, "nil");
  540. map_ptr = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  541. LLVM_SET_VALUE_NAME(map_ptr.value, "map_ptr");
  542. lbValue map = lb_emit_load(p, map_ptr);
  543. LLVM_SET_VALUE_NAME(map.value, "map");
  544. lbValue length = lb_map_len(p, map);
  545. LLVM_SET_VALUE_NAME(length.value, "length");
  546. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, length, lb_const_nil(m, t_int)), nil_block, hash_block);
  547. lb_start_block(p, hash_block);
  548. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  549. LLVM_SET_VALUE_NAME(key_ptr.value, "key_ptr");
  550. lbValue key = lb_emit_load(p, key_ptr);
  551. LLVM_SET_VALUE_NAME(key.value, "key");
  552. lbAddr pos = lb_add_local_generated(p, t_uintptr, false);
  553. lbAddr distance = lb_add_local_generated(p, t_uintptr, true);
  554. LLVM_SET_VALUE_NAME(pos.addr.value, "pos");
  555. LLVM_SET_VALUE_NAME(distance.addr.value, "distance");
  556. lbValue capacity = lb_map_cap(p, map);
  557. LLVM_SET_VALUE_NAME(capacity.value, "capacity");
  558. lbValue cap_minus_1 = lb_emit_arith(p, Token_Sub, capacity, lb_const_int(m, t_int, 1), t_int);
  559. lbValue mask = lb_emit_conv(p, cap_minus_1, t_uintptr);
  560. LLVM_SET_VALUE_NAME(mask.value, "mask");
  561. {
  562. // map_desired_position inlined
  563. lbValue the_pos = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  564. the_pos = lb_emit_conv(p, the_pos, t_uintptr);
  565. lb_addr_store(p, pos, the_pos);
  566. }
  567. lbValue zero_uintptr = lb_const_int(m, t_uintptr, 0);
  568. lbValue one_uintptr = lb_const_int(m, t_uintptr, 1);
  569. lbValue ks = lb_map_data_uintptr(p, map);
  570. lbValue vs = lb_map_cell_index_static(p, type->Map.key, ks, capacity);
  571. lbValue hs = lb_map_cell_index_static(p, type->Map.value, vs, capacity);
  572. ks = lb_emit_conv(p, ks, alloc_type_pointer(type->Map.key));
  573. vs = lb_emit_conv(p, vs, alloc_type_pointer(type->Map.value));
  574. hs = lb_emit_conv(p, hs, alloc_type_pointer(t_uintptr));
  575. LLVM_SET_VALUE_NAME(ks.value, "ks");
  576. LLVM_SET_VALUE_NAME(vs.value, "vs");
  577. LLVM_SET_VALUE_NAME(hs.value, "hs");
  578. lb_emit_jump(p, loop_block);
  579. lb_start_block(p, loop_block);
  580. lbValue element_hash = lb_emit_load(p, lb_emit_ptr_offset(p, hs, lb_addr_load(p, pos)));
  581. LLVM_SET_VALUE_NAME(element_hash.value, "element_hash");
  582. {
  583. // if element_hash == 0 { return nil }
  584. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, zero_uintptr), nil_block, probe_block);
  585. }
  586. lb_start_block(p, probe_block);
  587. {
  588. // map_probe_distance inlined
  589. lbValue probe_distance = lb_emit_arith(p, Token_And, h, mask, t_uintptr);
  590. probe_distance = lb_emit_conv(p, probe_distance, t_uintptr);
  591. lbValue cap = lb_emit_conv(p, capacity, t_uintptr);
  592. lbValue base = lb_emit_arith(p, Token_Add, lb_addr_load(p, pos), cap, t_uintptr);
  593. probe_distance = lb_emit_arith(p, Token_Sub, base, probe_distance, t_uintptr);
  594. probe_distance = lb_emit_arith(p, Token_And, probe_distance, mask, t_uintptr);
  595. LLVM_SET_VALUE_NAME(probe_distance.value, "probe_distance");
  596. lbValue cond = lb_emit_comp(p, Token_Gt, lb_addr_load(p, distance), probe_distance);
  597. lb_emit_if(p, cond, nil_block, hash_compare_block);
  598. }
  599. lb_start_block(p, hash_compare_block);
  600. {
  601. lb_emit_if(p, lb_emit_comp(p, Token_CmpEq, element_hash, h), key_compare_block, increment_block);
  602. }
  603. lb_start_block(p, key_compare_block);
  604. {
  605. lbValue element_key = lb_map_cell_index_static(p, type->Map.key, ks, lb_addr_load(p, pos));
  606. element_key = lb_emit_conv(p, element_key, ks.type);
  607. LLVM_SET_VALUE_NAME(element_key.value, "element_key_ptr");
  608. lbValue cond = lb_emit_comp(p, Token_CmpEq, lb_emit_load(p, element_key), key);
  609. lb_emit_if(p, cond, value_block, increment_block);
  610. }
  611. lb_start_block(p, value_block);
  612. {
  613. lbValue element_value = lb_map_cell_index_static(p, type->Map.value, vs, lb_addr_load(p, pos));
  614. LLVM_SET_VALUE_NAME(element_value.value, "element_value_ptr");
  615. element_value = lb_emit_conv(p, element_value, t_rawptr);
  616. LLVMBuildRet(p->builder, element_value.value);
  617. }
  618. lb_start_block(p, increment_block);
  619. {
  620. lbValue pp = lb_addr_load(p, pos);
  621. pp = lb_emit_arith(p, Token_Add, pp, one_uintptr, t_uintptr);
  622. pp = lb_emit_arith(p, Token_And, pp, mask, t_uintptr);
  623. lb_addr_store(p, pos, pp);
  624. lb_emit_increment(p, distance.addr);
  625. }
  626. lb_emit_jump(p, loop_block);
  627. lb_start_block(p, nil_block);
  628. {
  629. lbValue res = lb_const_nil(m, t_rawptr);
  630. LLVMBuildRet(p->builder, res.value);
  631. }
  632. // gb_printf_err("%s\n", LLVMPrintValueToString(p->value));
  633. return {p->value, p->type};
  634. }
  635. // gb_internal void lb_debug_print(lbProcedure *p, String const &str) {
  636. // auto args = array_make<lbValue>(heap_allocator(), 1);
  637. // args[0] = lb_const_string(p->module, str);
  638. // lb_emit_runtime_call(p, "print_string", args);
  639. // }
  640. gb_internal lbValue lb_map_set_proc_for_type(lbModule *m, Type *type) {
  641. TEMPORARY_ALLOCATOR_GUARD();
  642. GB_ASSERT(!build_context.dynamic_map_calls);
  643. type = base_type(type);
  644. GB_ASSERT(type->kind == Type_Map);
  645. String proc_name = lb_internal_gen_name_from_type("__$map_set", type);
  646. lbProcedure **found = string_map_get(&m->gen_procs, proc_name);
  647. if (found) {
  648. GB_ASSERT(*found != nullptr);
  649. return {(*found)->value, (*found)->type};
  650. }
  651. lbProcedure *p = lb_create_dummy_procedure(m, proc_name, t_map_set_proc);
  652. string_map_set(&m->gen_procs, proc_name, p);
  653. lb_begin_procedure_body(p);
  654. defer (lb_end_procedure_body(p));
  655. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  656. lb_add_attribute_to_proc(m, p->value, "nounwind");
  657. if (build_context.ODIN_DEBUG) {
  658. lb_add_attribute_to_proc(m, p->value, "noinline");
  659. }
  660. lbValue map_ptr = {LLVMGetParam(p->value, 0), t_rawptr};
  661. lbValue hash_param = {LLVMGetParam(p->value, 1), t_uintptr};
  662. lbValue key_ptr = {LLVMGetParam(p->value, 2), t_rawptr};
  663. lbValue value_ptr = {LLVMGetParam(p->value, 3), t_rawptr};
  664. lbValue location_ptr = {LLVMGetParam(p->value, 4), t_source_code_location_ptr};
  665. map_ptr = lb_emit_conv(p, map_ptr, alloc_type_pointer(type));
  666. key_ptr = lb_emit_conv(p, key_ptr, alloc_type_pointer(type->Map.key));
  667. LLVM_SET_VALUE_NAME(map_ptr.value, "map_ptr");
  668. LLVM_SET_VALUE_NAME(hash_param.value, "hash_param");
  669. LLVM_SET_VALUE_NAME(key_ptr.value, "key_ptr");
  670. LLVM_SET_VALUE_NAME(value_ptr.value, "value_ptr");
  671. LLVM_SET_VALUE_NAME(location_ptr.value, "location");
  672. lb_add_proc_attribute_at_index(p, 1+0, "nonnull");
  673. lb_add_proc_attribute_at_index(p, 1+0, "noalias");
  674. lb_add_proc_attribute_at_index(p, 1+2, "nonnull");
  675. if (!are_types_identical(type->Map.key, type->Map.value)) {
  676. lb_add_proc_attribute_at_index(p, 1+2, "noalias");
  677. }
  678. lb_add_proc_attribute_at_index(p, 1+2, "readonly");
  679. lb_add_proc_attribute_at_index(p, 1+3, "nonnull");
  680. if (!are_types_identical(type->Map.key, type->Map.value)) {
  681. lb_add_proc_attribute_at_index(p, 1+3, "noalias");
  682. }
  683. lb_add_proc_attribute_at_index(p, 1+3, "readonly");
  684. lb_add_proc_attribute_at_index(p, 1+4, "nonnull");
  685. lb_add_proc_attribute_at_index(p, 1+4, "noalias");
  686. lb_add_proc_attribute_at_index(p, 1+4, "readonly");
  687. lbAddr hash_addr = lb_add_local_generated(p, t_uintptr, false);
  688. lb_addr_store(p, hash_addr, hash_param);
  689. LLVM_SET_VALUE_NAME(hash_addr.addr.value, "hash");
  690. ////
  691. lbValue found_ptr = {};
  692. {
  693. lbValue map_get_proc = lb_map_get_proc_for_type(m, type);
  694. auto args = array_make<lbValue>(temporary_allocator(), 3);
  695. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  696. args[1] = lb_addr_load(p, hash_addr);
  697. args[2] = key_ptr;
  698. found_ptr = lb_emit_call(p, map_get_proc, args);
  699. }
  700. LLVM_SET_VALUE_NAME(found_ptr.value, "found_ptr");
  701. lbBlock *found_block = lb_create_block(p, "found");
  702. lbBlock *check_grow_block = lb_create_block(p, "check-grow");
  703. lbBlock *grow_fail_block = lb_create_block(p, "grow-fail");
  704. lbBlock *insert_block = lb_create_block(p, "insert");
  705. lbBlock *check_has_grown_block = lb_create_block(p, "check-has-grown");
  706. lbBlock *rehash_block = lb_create_block(p, "rehash");
  707. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, found_ptr), found_block, check_grow_block);
  708. lb_start_block(p, found_block);
  709. {
  710. lb_mem_copy_non_overlapping(p, found_ptr, value_ptr, lb_const_int(m, t_int, type_size_of(type->Map.value)));
  711. LLVMBuildRet(p->builder, lb_emit_conv(p, found_ptr, t_rawptr).value);
  712. }
  713. lb_start_block(p, check_grow_block);
  714. lbValue map_info = lb_gen_map_info_ptr(p->module, type);
  715. LLVM_SET_VALUE_NAME(map_info.value, "map_info");
  716. {
  717. auto args = array_make<lbValue>(temporary_allocator(), 3);
  718. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  719. args[1] = map_info;
  720. args[2] = lb_emit_load(p, location_ptr);
  721. lbValue grow_err_and_has_grown = lb_emit_runtime_call(p, "__dynamic_map_check_grow", args);
  722. lbValue grow_err = lb_emit_struct_ev(p, grow_err_and_has_grown, 0);
  723. lbValue has_grown = lb_emit_struct_ev(p, grow_err_and_has_grown, 1);
  724. LLVM_SET_VALUE_NAME(grow_err.value, "grow_err");
  725. LLVM_SET_VALUE_NAME(has_grown.value, "has_grown");
  726. lb_emit_if(p, lb_emit_comp_against_nil(p, Token_NotEq, grow_err), grow_fail_block, check_has_grown_block);
  727. lb_start_block(p, grow_fail_block);
  728. LLVMBuildRet(p->builder, LLVMConstNull(lb_type(m, t_rawptr)));
  729. lb_start_block(p, check_has_grown_block);
  730. lb_emit_if(p, has_grown, rehash_block, insert_block);
  731. lb_start_block(p, rehash_block);
  732. lbValue key = lb_emit_load(p, key_ptr);
  733. lbValue new_hash = lb_gen_map_key_hash(p, map_ptr, key, nullptr);
  734. LLVM_SET_VALUE_NAME(new_hash.value, "new_hash");
  735. lb_addr_store(p, hash_addr, new_hash);
  736. lb_emit_jump(p, insert_block);
  737. }
  738. lb_start_block(p, insert_block);
  739. {
  740. auto args = array_make<lbValue>(temporary_allocator(), 5);
  741. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  742. args[1] = map_info;
  743. args[2] = lb_addr_load(p, hash_addr);
  744. args[3] = lb_emit_conv(p, key_ptr, t_uintptr);
  745. args[4] = lb_emit_conv(p, value_ptr, t_uintptr);
  746. lbValue result = lb_emit_runtime_call(p, "map_insert_hash_dynamic", args);
  747. lb_emit_increment(p, lb_map_len_ptr(p, map_ptr));
  748. LLVMBuildRet(p->builder, lb_emit_conv(p, result, t_rawptr).value);
  749. }
  750. return {p->value, p->type};
  751. }
  752. gb_internal lbValue lb_gen_map_cell_info_ptr(lbModule *m, Type *type) {
  753. lbAddr *found = map_get(&m->map_cell_info_map, type);
  754. if (found) {
  755. return found->addr;
  756. }
  757. i64 size = 0, len = 0;
  758. map_cell_size_and_len(type, &size, &len);
  759. LLVMValueRef const_values[4] = {};
  760. const_values[0] = lb_const_int(m, t_uintptr, type_size_of(type)).value;
  761. const_values[1] = lb_const_int(m, t_uintptr, type_align_of(type)).value;
  762. const_values[2] = lb_const_int(m, t_uintptr, size).value;
  763. const_values[3] = lb_const_int(m, t_uintptr, len).value;
  764. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_cell_info, const_values, gb_count_of(const_values));
  765. lbValue res = {llvm_res, t_map_cell_info};
  766. lbAddr addr = lb_add_global_generated_with_name(m, t_map_cell_info, res, lb_internal_gen_name_from_type("ggv$map_cell_info", type));
  767. lb_make_global_private_const(addr);
  768. map_set(&m->map_cell_info_map, type, addr);
  769. return addr.addr;
  770. }
  771. gb_internal lbValue lb_gen_map_info_ptr(lbModule *m, Type *map_type) {
  772. map_type = base_type(map_type);
  773. GB_ASSERT(map_type->kind == Type_Map);
  774. lbAddr *found = map_get(&m->map_info_map, map_type);
  775. if (found) {
  776. return found->addr;
  777. }
  778. GB_ASSERT(t_map_info != nullptr);
  779. GB_ASSERT(t_map_cell_info != nullptr);
  780. LLVMValueRef key_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.key).value;
  781. LLVMValueRef value_cell_info = lb_gen_map_cell_info_ptr(m, map_type->Map.value).value;
  782. LLVMValueRef const_values[4] = {};
  783. const_values[0] = key_cell_info;
  784. const_values[1] = value_cell_info;
  785. const_values[2] = lb_hasher_proc_for_type(m, map_type->Map.key).value;
  786. const_values[3] = lb_equal_proc_for_type(m, map_type->Map.key).value;
  787. LLVMValueRef llvm_res = llvm_const_named_struct(m, t_map_info, const_values, gb_count_of(const_values));
  788. lbValue res = {llvm_res, t_map_info};
  789. lbAddr addr = lb_add_global_generated_with_name(m, t_map_info, res, lb_internal_gen_name_from_type("ggv$map_info", map_type));
  790. lb_make_global_private_const(addr);
  791. map_set(&m->map_info_map, map_type, addr);
  792. return addr.addr;
  793. }
  794. gb_internal lbValue lb_const_hash(lbModule *m, lbValue key, Type *key_type) {
  795. if (true) {
  796. return {};
  797. }
  798. lbValue hashed_key = {};
  799. #if 0
  800. if (lb_is_const(key)) {
  801. u64 hash = 0xcbf29ce484222325;
  802. if (is_type_cstring(key_type)) {
  803. size_t length = 0;
  804. char const *text = LLVMGetAsString(key.value, &length);
  805. hash = fnv64a(text, cast(isize)length);
  806. } else if (is_type_string(key_type)) {
  807. unsigned data_indices[] = {0};
  808. unsigned len_indices[] = {1};
  809. LLVMValueRef data = LLVMConstExtractValue(key.value, data_indices, gb_count_of(data_indices));
  810. LLVMValueRef len = LLVMConstExtractValue(key.value, len_indices, gb_count_of(len_indices));
  811. i64 length = LLVMConstIntGetSExtValue(len);
  812. char const *text = nullptr;
  813. if (false && length != 0) {
  814. if (LLVMGetConstOpcode(data) != LLVMGetElementPtr) {
  815. return {};
  816. }
  817. // TODO(bill): THIS IS BROKEN! THIS NEEDS FIXING :P
  818. size_t ulength = 0;
  819. text = LLVMGetAsString(data, &ulength);
  820. gb_printf_err("%lld %llu %s\n", length, ulength, text);
  821. length = gb_min(length, cast(i64)ulength);
  822. }
  823. hash = fnv64a(text, cast(isize)length);
  824. } else {
  825. return {};
  826. }
  827. // TODO(bill): other const hash types
  828. if (build_context.word_size == 4) {
  829. hash &= 0xffffffffull;
  830. }
  831. hashed_key = lb_const_int(m, t_uintptr, hash);
  832. }
  833. #endif
  834. return hashed_key;
  835. }
  836. gb_internal lbValue lb_gen_map_key_hash(lbProcedure *p, lbValue const &map_ptr, lbValue key, lbValue *key_ptr_) {
  837. TEMPORARY_ALLOCATOR_GUARD();
  838. Type* key_type = base_type(type_deref(map_ptr.type))->Map.key;
  839. lbValue real_key = lb_emit_conv(p, key, key_type);
  840. lbValue key_ptr = lb_address_from_load_or_generate_local(p, real_key);
  841. key_ptr = lb_emit_conv(p, key_ptr, t_rawptr);
  842. if (key_ptr_) *key_ptr_ = key_ptr;
  843. lbValue hashed_key = lb_const_hash(p->module, real_key, key_type);
  844. if (hashed_key.value == nullptr) {
  845. lbValue hasher = lb_hasher_proc_for_type(p->module, key_type);
  846. lbValue seed = {};
  847. {
  848. auto args = array_make<lbValue>(temporary_allocator(), 1);
  849. args[0] = lb_map_data_uintptr(p, lb_emit_load(p, map_ptr));
  850. seed = lb_emit_runtime_call(p, "map_seed_from_map_data", args);
  851. }
  852. auto args = array_make<lbValue>(temporary_allocator(), 2);
  853. args[0] = key_ptr;
  854. args[1] = seed;
  855. hashed_key = lb_emit_call(p, hasher, args);
  856. }
  857. return hashed_key;
  858. }
  859. gb_internal lbValue lb_internal_dynamic_map_get_ptr(lbProcedure *p, lbValue const &map_ptr, lbValue const &key) {
  860. TEMPORARY_ALLOCATOR_GUARD();
  861. Type *map_type = base_type(type_deref(map_ptr.type));
  862. GB_ASSERT(map_type->kind == Type_Map);
  863. lbValue ptr = {};
  864. lbValue key_ptr = {};
  865. lbValue hash = lb_gen_map_key_hash(p, map_ptr, key, &key_ptr);
  866. if (build_context.dynamic_map_calls) {
  867. auto args = array_make<lbValue>(temporary_allocator(), 4);
  868. args[0] = lb_emit_transmute(p, map_ptr, t_raw_map_ptr);
  869. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  870. args[2] = hash;
  871. args[3] = key_ptr;
  872. ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  873. } else {
  874. lbValue map_get_proc = lb_map_get_proc_for_type(p->module, map_type);
  875. auto args = array_make<lbValue>(temporary_allocator(), 3);
  876. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  877. args[1] = hash;
  878. args[2] = key_ptr;
  879. ptr = lb_emit_call(p, map_get_proc, args);
  880. }
  881. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  882. }
  883. gb_internal void lb_internal_dynamic_map_set(lbProcedure *p, lbValue const &map_ptr, Type *map_type,
  884. lbValue const &map_key, lbValue const &map_value, Ast *node) {
  885. TEMPORARY_ALLOCATOR_GUARD();
  886. map_type = base_type(map_type);
  887. GB_ASSERT(map_type->kind == Type_Map);
  888. lbValue key_ptr = {};
  889. lbValue hash = lb_gen_map_key_hash(p, map_ptr, map_key, &key_ptr);
  890. lbValue v = lb_emit_conv(p, map_value, map_type->Map.value);
  891. lbValue value_ptr = lb_address_from_load_or_generate_local(p, v);
  892. if (build_context.dynamic_map_calls) {
  893. auto args = array_make<lbValue>(temporary_allocator(), 6);
  894. args[0] = lb_emit_conv(p, map_ptr, t_raw_map_ptr);
  895. args[1] = lb_gen_map_info_ptr(p->module, map_type);
  896. args[2] = hash;
  897. args[3] = lb_emit_conv(p, key_ptr, t_rawptr);
  898. args[4] = lb_emit_conv(p, value_ptr, t_rawptr);
  899. args[5] = lb_emit_source_code_location_as_global(p, node);
  900. lb_emit_runtime_call(p, "__dynamic_map_set", args);
  901. } else {
  902. lbValue map_set_proc = lb_map_set_proc_for_type(p->module, map_type);
  903. auto args = array_make<lbValue>(temporary_allocator(), 5);
  904. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  905. args[1] = hash;
  906. args[2] = lb_emit_conv(p, key_ptr, t_rawptr);
  907. args[3] = lb_emit_conv(p, value_ptr, t_rawptr);
  908. args[4] = lb_emit_source_code_location_as_global(p, node);
  909. lb_emit_call(p, map_set_proc, args);
  910. }
  911. }
  912. gb_internal lbValue lb_dynamic_map_reserve(lbProcedure *p, lbValue const &map_ptr, isize const capacity, TokenPos const &pos) {
  913. TEMPORARY_ALLOCATOR_GUARD();
  914. String proc_name = {};
  915. if (p->entity) {
  916. proc_name = p->entity->token.string;
  917. }
  918. auto args = array_make<lbValue>(temporary_allocator(), 4);
  919. args[0] = lb_emit_conv(p, map_ptr, t_rawptr);
  920. args[1] = lb_gen_map_info_ptr(p->module, type_deref(map_ptr.type));
  921. args[2] = lb_const_int(p->module, t_uint, capacity);
  922. args[3] = lb_emit_source_code_location_as_global(p, proc_name, pos);
  923. return lb_emit_runtime_call(p, "__dynamic_map_reserve", args);
  924. }
  925. gb_internal lbProcedure *lb_create_objc_names(lbModule *main_module) {
  926. if (build_context.metrics.os != TargetOs_darwin) {
  927. return nullptr;
  928. }
  929. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl);
  930. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit("__$init_objc_names"), proc_type);
  931. lb_add_attribute_to_proc(p->module, p->value, "nounwind");
  932. p->is_startup = true;
  933. return p;
  934. }
  935. String lb_get_objc_type_encoding(Type *t, isize pointer_depth = 0) {
  936. // NOTE(harold): See https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100
  937. // NOTE(harold): Darwin targets are always 64-bit. Should we drop this and assume "q" always?
  938. #define INT_SIZE_ENCODING (build_context.metrics.int_size == 4 ? "i" : "q")
  939. switch (t->kind) {
  940. case Type_Basic: {
  941. switch (t->Basic.kind) {
  942. case Basic_Invalid:
  943. return str_lit("?");
  944. case Basic_llvm_bool:
  945. case Basic_bool:
  946. case Basic_b8:
  947. return str_lit("B");
  948. case Basic_b16:
  949. return str_lit("C");
  950. case Basic_b32:
  951. return str_lit("I");
  952. case Basic_b64:
  953. return str_lit("q");
  954. case Basic_i8:
  955. return str_lit("c");
  956. case Basic_u8:
  957. return str_lit("C");
  958. case Basic_i16:
  959. case Basic_i16le:
  960. case Basic_i16be:
  961. return str_lit("s");
  962. case Basic_u16:
  963. case Basic_u16le:
  964. case Basic_u16be:
  965. return str_lit("S");
  966. case Basic_i32:
  967. case Basic_i32le:
  968. case Basic_i32be:
  969. return str_lit("i");
  970. case Basic_u32le:
  971. case Basic_u32:
  972. case Basic_u32be:
  973. return str_lit("I");
  974. case Basic_i64:
  975. case Basic_i64le:
  976. case Basic_i64be:
  977. return str_lit("q");
  978. case Basic_u64:
  979. case Basic_u64le:
  980. case Basic_u64be:
  981. return str_lit("Q");
  982. case Basic_i128:
  983. case Basic_i128le:
  984. case Basic_i128be:
  985. return str_lit("t");
  986. case Basic_u128:
  987. case Basic_u128le:
  988. case Basic_u128be:
  989. return str_lit("T");
  990. case Basic_rune:
  991. return str_lit("I");
  992. case Basic_f16:
  993. case Basic_f16le:
  994. case Basic_f16be:
  995. return str_lit("s"); // @harold: Closest we've got?
  996. case Basic_f32:
  997. case Basic_f32le:
  998. case Basic_f32be:
  999. return str_lit("f");
  1000. case Basic_f64:
  1001. case Basic_f64le:
  1002. case Basic_f64be:
  1003. return str_lit("d");
  1004. case Basic_complex32: return str_lit("{complex32=ss}"); // No f16 encoding, so fallback to i16, as above in Basic_f16*
  1005. case Basic_complex64: return str_lit("{complex64=ff}");
  1006. case Basic_complex128: return str_lit("{complex128=dd}");
  1007. case Basic_quaternion64: return str_lit("{quaternion64=ssss}");
  1008. case Basic_quaternion128: return str_lit("{quaternion128=ffff}");
  1009. case Basic_quaternion256: return str_lit("{quaternion256=dddd}");
  1010. case Basic_int:
  1011. return str_lit(INT_SIZE_ENCODING);
  1012. case Basic_uint:
  1013. return build_context.metrics.int_size == 4 ? str_lit("I") : str_lit("Q");
  1014. case Basic_uintptr:
  1015. case Basic_rawptr:
  1016. return str_lit("^v");
  1017. case Basic_string:
  1018. return build_context.metrics.int_size == 4 ? str_lit("{string=*i}") : str_lit("{string=*q}");
  1019. case Basic_string16:
  1020. return build_context.metrics.int_size == 4 ? str_lit("{string16=*i}") : str_lit("{string16=*q}");
  1021. case Basic_cstring: return str_lit("*");
  1022. case Basic_cstring16: return str_lit("*");
  1023. case Basic_any: return str_lit("{any=^v^v}"); // rawptr + ^Type_Info
  1024. case Basic_typeid:
  1025. GB_ASSERT(t->Basic.size == 8);
  1026. return str_lit("q");
  1027. // Untyped types
  1028. case Basic_UntypedBool:
  1029. case Basic_UntypedInteger:
  1030. case Basic_UntypedFloat:
  1031. case Basic_UntypedComplex:
  1032. case Basic_UntypedQuaternion:
  1033. case Basic_UntypedString:
  1034. case Basic_UntypedRune:
  1035. case Basic_UntypedNil:
  1036. case Basic_UntypedUninit:
  1037. GB_PANIC("Untyped types cannot be @encoded()");
  1038. return str_lit("?");
  1039. }
  1040. break;
  1041. }
  1042. case Type_Named:
  1043. case Type_Struct:
  1044. case Type_Union: {
  1045. Type* base = t;
  1046. if (base->kind == Type_Named) {
  1047. base = base_type(base);
  1048. if(base->kind != Type_Struct && base->kind != Type_Union) {
  1049. return lb_get_objc_type_encoding(base, pointer_depth);
  1050. }
  1051. }
  1052. const bool is_union = base->kind == Type_Union;
  1053. if (!is_union) {
  1054. // Treat struct as an Objective-C Class?
  1055. if (has_type_got_objc_class_attribute(t) && pointer_depth == 0) {
  1056. return str_lit("#");
  1057. }
  1058. }
  1059. if (is_type_objc_object(base)) {
  1060. return str_lit("@");
  1061. }
  1062. gbString s = gb_string_make_reserve(temporary_allocator(), 16);
  1063. s = gb_string_append_length(s, is_union ? "(" :"{", 1);
  1064. if (t->kind == Type_Named) {
  1065. s = gb_string_append_length(s, t->Named.name.text, t->Named.name.len);
  1066. }
  1067. // Write fields
  1068. if (pointer_depth < 2) {
  1069. s = gb_string_append_length(s, "=", 1);
  1070. if (!is_union) {
  1071. for( auto& f : base->Struct.fields ) {
  1072. String field_type = lb_get_objc_type_encoding(f->type, pointer_depth);
  1073. s = gb_string_append_length(s, field_type.text, field_type.len);
  1074. }
  1075. } else {
  1076. for( auto& v : base->Union.variants ) {
  1077. String variant_type = lb_get_objc_type_encoding(v, pointer_depth);
  1078. s = gb_string_append_length(s, variant_type.text, variant_type.len);
  1079. }
  1080. }
  1081. }
  1082. s = gb_string_append_length(s, is_union ? ")" :"}", 1);
  1083. return make_string_c(s);
  1084. }
  1085. case Type_Generic:
  1086. GB_PANIC("Generic types cannot be @encoded()");
  1087. return str_lit("?");
  1088. case Type_Pointer: {
  1089. // NOTE: These types are pointers, so we must check here for special cases
  1090. // Check for objc_SEL
  1091. if (internal_check_is_assignable_to(t, t_objc_SEL)) {
  1092. return str_lit(":");
  1093. }
  1094. // Check for objc_Class
  1095. if (internal_check_is_assignable_to(t, t_objc_Class)) {
  1096. return str_lit("#");
  1097. }
  1098. String pointee = lb_get_objc_type_encoding(t->Pointer.elem, pointer_depth +1);
  1099. // Special case for Objective-C Objects
  1100. if (pointer_depth == 0 && pointee == "@") {
  1101. return pointee;
  1102. }
  1103. return concatenate_strings(temporary_allocator(), str_lit("^"), pointee);
  1104. }
  1105. case Type_MultiPointer:
  1106. return concatenate_strings(temporary_allocator(), str_lit("^"), lb_get_objc_type_encoding(t->Pointer.elem, pointer_depth +1));
  1107. case Type_Array: {
  1108. String type_str = lb_get_objc_type_encoding(t->Array.elem, pointer_depth);
  1109. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 8);
  1110. s = gb_string_append_fmt(s, "[%lld%.*s]", t->Array.count, LIT(type_str));
  1111. return make_string_c(s);
  1112. }
  1113. case Type_EnumeratedArray: {
  1114. String type_str = lb_get_objc_type_encoding(t->EnumeratedArray.elem, pointer_depth);
  1115. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 8);
  1116. s = gb_string_append_fmt(s, "[%lld%.*s]", t->EnumeratedArray.count, LIT(type_str));
  1117. return make_string_c(s);
  1118. }
  1119. case Type_Slice: {
  1120. String type_str = lb_get_objc_type_encoding(t->Slice.elem, pointer_depth);
  1121. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 8);
  1122. s = gb_string_append_fmt(s, "{slice=^%.*s%s}", LIT(type_str), INT_SIZE_ENCODING);
  1123. return make_string_c(s);
  1124. }
  1125. case Type_DynamicArray: {
  1126. String type_str = lb_get_objc_type_encoding(t->DynamicArray.elem, pointer_depth);
  1127. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 8);
  1128. s = gb_string_append_fmt(s, "{dynamic=^%.*s%s%sAllocator={?^v}}", LIT(type_str), INT_SIZE_ENCODING, INT_SIZE_ENCODING);
  1129. return make_string_c(s);
  1130. }
  1131. case Type_Map:
  1132. return str_lit("{^v^v{Allocator=?^v}}");
  1133. case Type_Enum:
  1134. return lb_get_objc_type_encoding(t->Enum.base_type, pointer_depth);
  1135. case Type_Tuple:
  1136. // NOTE(harold): Is this type allowed here?
  1137. return str_lit("?");
  1138. case Type_Proc:
  1139. return str_lit("?");
  1140. case Type_BitSet:
  1141. return lb_get_objc_type_encoding(t->BitSet.underlying, pointer_depth);
  1142. case Type_SimdVector: {
  1143. String type_str = lb_get_objc_type_encoding(t->SimdVector.elem, pointer_depth);
  1144. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 5);
  1145. gb_string_append_fmt(s, "[%lld%.*s]", t->SimdVector.count, LIT(type_str));
  1146. return make_string_c(s);
  1147. }
  1148. case Type_Matrix: {
  1149. String type_str = lb_get_objc_type_encoding(t->Matrix.elem, pointer_depth);
  1150. gbString s = gb_string_make_reserve(temporary_allocator(), type_str.len + 5);
  1151. i64 element_count = t->Matrix.column_count * t->Matrix.row_count;
  1152. gb_string_append_fmt(s, "[%lld%.*s]", element_count, LIT(type_str));
  1153. return make_string_c(s);
  1154. }
  1155. case Type_BitField:
  1156. return lb_get_objc_type_encoding(t->BitField.backing_type, pointer_depth);
  1157. case Type_SoaPointer: {
  1158. gbString s = gb_string_make_reserve(temporary_allocator(), 8);
  1159. s = gb_string_append_fmt(s, "{=^v%s}", INT_SIZE_ENCODING);
  1160. return make_string_c(s);
  1161. }
  1162. } // End switch t->kind
  1163. #undef INT_SIZE_ENCODING
  1164. GB_PANIC("Unreachable");
  1165. return str_lit("");
  1166. }
  1167. struct lbObjCGlobalClass {
  1168. lbObjCGlobal g;
  1169. lbValue class_value; // Local registered class value
  1170. };
  1171. gb_internal void lb_register_objc_thing(
  1172. StringSet &handled,
  1173. lbModule *m,
  1174. Array<lbValue> &args,
  1175. Array<lbObjCGlobalClass> &class_impls,
  1176. StringMap<lbObjCGlobalClass> &class_map,
  1177. lbProcedure *p,
  1178. lbObjCGlobal const &g,
  1179. char const *call
  1180. ) {
  1181. if (string_set_update(&handled, g.name)) {
  1182. return;
  1183. }
  1184. lbAddr addr = {};
  1185. lbValue *found = string_map_get(&m->members, g.global_name);
  1186. if (found) {
  1187. addr = lb_addr(*found);
  1188. } else {
  1189. lbValue v = {};
  1190. LLVMTypeRef t = lb_type(m, g.type);
  1191. v.value = LLVMAddGlobal(m->mod, t, g.global_name);
  1192. v.type = alloc_type_pointer(g.type);
  1193. addr = lb_addr(v);
  1194. LLVMSetInitializer(v.value, LLVMConstNull(t));
  1195. }
  1196. lbValue class_ptr = {};
  1197. lbValue class_name = lb_const_value(m, t_cstring, exact_value_string(g.name));
  1198. // If this class requires an implementation, save it for registration below.
  1199. if (g.class_impl_type != nullptr) {
  1200. // Make sure the superclass has been initialized before us
  1201. lbValue superclass_value = lb_const_nil(m, t_objc_Class);
  1202. auto &tn = g.class_impl_type->Named.type_name->TypeName;
  1203. Type *superclass = tn.objc_superclass;
  1204. if (superclass != nullptr) {
  1205. auto& superclass_global = string_map_must_get(&class_map, superclass->Named.type_name->TypeName.objc_class_name);
  1206. lb_register_objc_thing(handled, m, args, class_impls, class_map, p, superclass_global.g, call);
  1207. GB_ASSERT(superclass_global.class_value.value);
  1208. superclass_value = superclass_global.class_value;
  1209. }
  1210. args.count = 3;
  1211. args[0] = superclass_value;
  1212. args[1] = class_name;
  1213. args[2] = lb_const_int(m, t_uint, 0);
  1214. class_ptr = lb_emit_runtime_call(p, "objc_allocateClassPair", args);
  1215. array_add(&class_impls, lbObjCGlobalClass{g, class_ptr});
  1216. }
  1217. else {
  1218. args.count = 1;
  1219. args[0] = class_name;
  1220. class_ptr = lb_emit_runtime_call(p, call, args);
  1221. }
  1222. lb_addr_store(p, addr, class_ptr);
  1223. lbObjCGlobalClass* class_global = string_map_get(&class_map, g.name);
  1224. if (class_global != nullptr) {
  1225. class_global->class_value = class_ptr;
  1226. }
  1227. }
  1228. gb_internal void lb_finalize_objc_names(lbGenerator *gen, lbProcedure *p) {
  1229. if (p == nullptr) {
  1230. return;
  1231. }
  1232. lbModule *m = p->module;
  1233. GB_ASSERT(m == &p->module->gen->default_module);
  1234. TEMPORARY_ALLOCATOR_GUARD();
  1235. StringSet handled = {};
  1236. string_set_init(&handled);
  1237. defer (string_set_destroy(&handled));
  1238. auto args = array_make<lbValue>(temporary_allocator(), 3, 8);
  1239. auto class_impls = array_make<lbObjCGlobalClass>(temporary_allocator(), 0, 16);
  1240. // Register all class implementations unconditionally, even if not statically referenced
  1241. for (Entity *e = {}; mpsc_dequeue(&gen->info->objc_class_implementations, &e); /**/) {
  1242. GB_ASSERT(e->kind == Entity_TypeName && e->TypeName.objc_is_implementation);
  1243. lb_handle_objc_find_or_register_class(p, e->TypeName.objc_class_name, e->type);
  1244. }
  1245. // Ensure classes that have been implicitly referenced through
  1246. // the objc_superclass attribute have a global variable available for them.
  1247. TypeSet class_set{};
  1248. type_set_init(&class_set, gen->objc_classes.count+16);
  1249. defer (type_set_destroy(&class_set));
  1250. auto referenced_classes = array_make<lbObjCGlobal>(temporary_allocator());
  1251. for (lbObjCGlobal g = {}; mpsc_dequeue(&gen->objc_classes, &g); /**/) {
  1252. array_add(&referenced_classes, g);
  1253. Type *cls = g.class_impl_type;
  1254. while (cls) {
  1255. if (type_set_update(&class_set, cls)) {
  1256. break;
  1257. }
  1258. GB_ASSERT(cls->kind == Type_Named);
  1259. cls = cls->Named.type_name->TypeName.objc_superclass;
  1260. }
  1261. }
  1262. for (auto pair : class_set) {
  1263. auto& tn = pair.type->Named.type_name->TypeName;
  1264. Type *class_impl = !tn.objc_is_implementation ? nullptr : pair.type;
  1265. lb_handle_objc_find_or_register_class(p, tn.objc_class_name, class_impl);
  1266. }
  1267. for (lbObjCGlobal g = {}; mpsc_dequeue(&gen->objc_classes, &g); /**/) {
  1268. array_add( &referenced_classes, g );
  1269. }
  1270. // Add all class globals to a map so that we can look them up dynamically
  1271. // in order to resolve out-of-order because classes that are being implemented
  1272. // require their superclasses to be registered before them.
  1273. StringMap<lbObjCGlobalClass> global_class_map{};
  1274. string_map_init(&global_class_map, (usize)gen->objc_classes.count);
  1275. defer (string_map_destroy(&global_class_map));
  1276. for (lbObjCGlobal g :referenced_classes) {
  1277. string_map_set(&global_class_map, g.name, lbObjCGlobalClass{g});
  1278. }
  1279. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  1280. lb_begin_procedure_body(p);
  1281. // Register class globals, gathering classes that must be implemented
  1282. for (auto& kv : global_class_map) {
  1283. lb_register_objc_thing(handled, m, args, class_impls, global_class_map, p, kv.value.g, "objc_lookUpClass");
  1284. }
  1285. // Prefetch selectors for implemented methods so that they can also be registered.
  1286. for (const auto& cd : class_impls) {
  1287. auto& g = cd.g;
  1288. Type *class_type = g.class_impl_type;
  1289. Array<ObjcMethodData>* methods = map_get(&m->info->objc_method_implementations, class_type);
  1290. if (!methods) {
  1291. continue;
  1292. }
  1293. for (const ObjcMethodData& md : *methods) {
  1294. lb_handle_objc_find_or_register_selector(p, md.ac.objc_selector);
  1295. }
  1296. }
  1297. // Now we can register all referenced selectors
  1298. for (lbObjCGlobal g = {}; mpsc_dequeue(&gen->objc_selectors, &g); /**/) {
  1299. lb_register_objc_thing(handled, m, args, class_impls, global_class_map, p, g, "sel_registerName");
  1300. }
  1301. // Emit method wrapper implementations and registration
  1302. auto wrapper_args = array_make<Type *>(temporary_allocator(), 2, 8);
  1303. auto get_context_args = array_make<lbValue>(temporary_allocator(), 1);
  1304. PtrMap<Type *, lbObjCGlobal> ivar_map{};
  1305. map_init(&ivar_map, gen->objc_ivars.count);
  1306. for (lbObjCGlobal g = {}; mpsc_dequeue(&gen->objc_ivars, &g); /**/) {
  1307. map_set(&ivar_map, g.class_impl_type, g);
  1308. }
  1309. for (const auto &cd : class_impls) {
  1310. auto &g = cd.g;
  1311. Type *class_type = g.class_impl_type;
  1312. Type *class_ptr_type = alloc_type_pointer(class_type);
  1313. lbValue class_value = cd.class_value;
  1314. Type *ivar_type = class_type->Named.type_name->TypeName.objc_ivar;
  1315. Entity *context_provider = class_type->Named.type_name->TypeName.objc_context_provider;
  1316. Type *contex_provider_self_ptr_type = nullptr;
  1317. Type *contex_provider_self_named_type = nullptr;
  1318. bool is_context_provider_ivar = false;
  1319. lbValue context_provider_proc_value{};
  1320. if (context_provider) {
  1321. context_provider_proc_value = lb_find_procedure_value_from_entity(m, context_provider);
  1322. contex_provider_self_ptr_type = base_type(context_provider->type->Proc.params->Tuple.variables[0]->type);
  1323. GB_ASSERT(contex_provider_self_ptr_type->kind == Type_Pointer);
  1324. contex_provider_self_named_type = base_named_type(type_deref(contex_provider_self_ptr_type));
  1325. is_context_provider_ivar = ivar_type != nullptr && internal_check_is_assignable_to(contex_provider_self_named_type, ivar_type);
  1326. }
  1327. Array<ObjcMethodData> *methods = map_get(&m->info->objc_method_implementations, class_type);
  1328. if (!methods) {
  1329. continue;
  1330. }
  1331. // Check if it has any class methods ahead of time so that we know to grab the meta_class
  1332. lbValue meta_class_value = {};
  1333. for (const ObjcMethodData &md : *methods) {
  1334. if (!md.ac.objc_is_class_method) {
  1335. continue;
  1336. }
  1337. // Get the meta_class
  1338. args.count = 1;
  1339. args[0] = class_value;
  1340. meta_class_value = lb_emit_runtime_call(p, "object_getClass", args);
  1341. break;
  1342. }
  1343. for (const ObjcMethodData &md : *methods) {
  1344. GB_ASSERT( md.proc_entity->kind == Entity_Procedure);
  1345. Type *method_type = md.proc_entity->type;
  1346. String proc_name = make_string_c("__$objc_method::");
  1347. proc_name = concatenate_strings(temporary_allocator(), proc_name, g.name);
  1348. proc_name = concatenate_strings(temporary_allocator(), proc_name, str_lit("::"));
  1349. proc_name = concatenate_strings( permanent_allocator(), proc_name, md.ac.objc_name);
  1350. wrapper_args.count = 2;
  1351. wrapper_args[0] = md.ac.objc_is_class_method ? t_objc_Class : class_ptr_type;
  1352. wrapper_args[1] = t_objc_SEL;
  1353. isize method_param_count = method_type->Proc.param_count;
  1354. isize method_param_offset = 0;
  1355. if (!md.ac.objc_is_class_method) {
  1356. GB_ASSERT(method_param_count >= 1);
  1357. method_param_count -= 1;
  1358. method_param_offset = 1;
  1359. }
  1360. for (isize i = 0; i < method_param_count; i++) {
  1361. array_add(&wrapper_args, method_type->Proc.params->Tuple.variables[method_param_offset+i]->type);
  1362. }
  1363. Type *wrapper_args_tuple = alloc_type_tuple_from_field_types(wrapper_args.data, wrapper_args.count, false, true);
  1364. Type *wrapper_results_tuple = nullptr;
  1365. if (method_type->Proc.result_count > 0) {
  1366. GB_ASSERT(method_type->Proc.result_count == 1);
  1367. wrapper_results_tuple = alloc_type_tuple_from_field_types(&method_type->Proc.results->Tuple.variables[0]->type, 1, false, true);
  1368. }
  1369. Type *wrapper_proc_type = alloc_type_proc(nullptr, wrapper_args_tuple, wrapper_args_tuple->Tuple.variables.count,
  1370. wrapper_results_tuple, method_type->Proc.result_count, false, ProcCC_CDecl);
  1371. lbProcedure *wrapper_proc = lb_create_dummy_procedure(m, proc_name, wrapper_proc_type);
  1372. lb_add_attribute_to_proc(wrapper_proc->module, wrapper_proc->value, "nounwind");
  1373. // Emit the wrapper
  1374. LLVMSetLinkage(wrapper_proc->value, LLVMExternalLinkage);
  1375. lb_begin_procedure_body(wrapper_proc);
  1376. {
  1377. if (method_type->Proc.calling_convention == ProcCC_Odin) {
  1378. GB_ASSERT(context_provider);
  1379. // Emit the get odin context call
  1380. get_context_args[0] = lbValue {
  1381. wrapper_proc->raw_input_parameters[0],
  1382. contex_provider_self_ptr_type,
  1383. };
  1384. if (is_context_provider_ivar) {
  1385. // The context provider takes the ivar's type.
  1386. // Emit an objc_ivar_get call and use that pointer for 'self' instead.
  1387. lbValue real_self {
  1388. wrapper_proc->raw_input_parameters[0],
  1389. class_ptr_type
  1390. };
  1391. get_context_args[0] = lb_handle_objc_ivar_for_objc_object_pointer(wrapper_proc, real_self);
  1392. }
  1393. lbValue context = lb_emit_call(wrapper_proc, context_provider_proc_value, get_context_args);
  1394. lbAddr context_addr = lb_addr(lb_address_from_load_or_generate_local(wrapper_proc, context));
  1395. lb_push_context_onto_stack(wrapper_proc, context_addr);
  1396. }
  1397. auto method_call_args = array_make<lbValue>(temporary_allocator(), method_param_count + method_param_offset);
  1398. if (!md.ac.objc_is_class_method) {
  1399. method_call_args[0] = lbValue {
  1400. wrapper_proc->raw_input_parameters[0],
  1401. class_ptr_type,
  1402. };
  1403. }
  1404. for (isize i = 0; i < method_param_count; i++) {
  1405. method_call_args[i+method_param_offset] = lbValue {
  1406. wrapper_proc->raw_input_parameters[i+2],
  1407. method_type->Proc.params->Tuple.variables[i+method_param_offset]->type,
  1408. };
  1409. }
  1410. lbValue method_proc_value = lb_find_procedure_value_from_entity(m, md.proc_entity);
  1411. // Call real procedure for method from here, passing the parameters expected, if any.
  1412. lbValue return_value = lb_emit_call(wrapper_proc, method_proc_value, method_call_args);
  1413. if (wrapper_results_tuple != nullptr) {
  1414. auto &result_var = method_type->Proc.results->Tuple.variables[0];
  1415. return_value = lb_emit_conv(wrapper_proc, return_value, result_var->type);
  1416. lb_build_return_stmt_internal(wrapper_proc, return_value, result_var->token.pos);
  1417. }
  1418. }
  1419. lb_end_procedure_body(wrapper_proc);
  1420. // Add the method to the class
  1421. String method_encoding = str_lit("v");
  1422. // TODO (harold): Checker must ensure that objc_methods have a single return value or none!
  1423. GB_ASSERT(method_type->Proc.result_count <= 1);
  1424. if (method_type->Proc.result_count != 0) {
  1425. method_encoding = lb_get_objc_type_encoding(method_type->Proc.results->Tuple.variables[0]->type);
  1426. }
  1427. if (!md.ac.objc_is_class_method) {
  1428. method_encoding = concatenate_strings(temporary_allocator(), method_encoding, str_lit("@:"));
  1429. } else {
  1430. method_encoding = concatenate_strings(temporary_allocator(), method_encoding, str_lit("#:"));
  1431. }
  1432. for (isize i = method_param_offset; i < method_param_count; i++) {
  1433. Type *param_type = method_type->Proc.params->Tuple.variables[i]->type;
  1434. String param_encoding = lb_get_objc_type_encoding(param_type);
  1435. method_encoding = concatenate_strings(temporary_allocator(), method_encoding, param_encoding);
  1436. }
  1437. // Emit method registration
  1438. lbAddr* sel_address = string_map_get(&m->objc_selectors, md.ac.objc_selector);
  1439. GB_ASSERT(sel_address);
  1440. lbValue selector_value = lb_addr_load(p, *sel_address);
  1441. lbValue target_class = !md.ac.objc_is_class_method ? class_value : meta_class_value;
  1442. args.count = 4;
  1443. args[0] = target_class; // Class
  1444. args[1] = selector_value; // SEL
  1445. args[2] = lbValue { wrapper_proc->value, wrapper_proc->type };
  1446. args[3] = lb_const_value(m, t_cstring, exact_value_string(method_encoding));
  1447. // TODO(harold): Emit check BOOL result and panic if false.
  1448. lb_emit_runtime_call(p, "class_addMethod", args);
  1449. } // End methods
  1450. // Add ivar if we have one
  1451. if (ivar_type != nullptr) {
  1452. // Register a single ivar for this class
  1453. Type *ivar_base = ivar_type->Named.base;
  1454. // @note(harold): The alignment is supposed to be passed as log2(alignment): https://developer.apple.com/documentation/objectivec/class_addivar(_:_:_:_:_:)?language=objc
  1455. const i64 size = type_size_of(ivar_base);
  1456. const i64 alignment = (i64)floor_log2((u64)type_align_of(ivar_base));
  1457. // NOTE(harold): I've opted to not emit the type encoding for ivars in order to keep the data private.
  1458. // If there is desire in the future to emit the type encoding for introspection through the Obj-C runtime,
  1459. // then perhaps an option can be added for it then.
  1460. // Should we pass the actual type encoding? Might not be ideal for obfuscation.
  1461. String ivar_name = str_lit("__$ivar");
  1462. String ivar_types = str_lit("{= }"); //lb_get_objc_type_encoding(ivar_type);
  1463. args.count = 5;
  1464. args[0] = class_value;
  1465. args[1] = lb_const_value(m, t_cstring, exact_value_string(ivar_name));
  1466. args[2] = lb_const_value(m, t_uint, exact_value_u64((u64)size));
  1467. args[3] = lb_const_value(m, t_u8, exact_value_u64((u64)alignment));
  1468. args[4] = lb_const_value(m, t_cstring, exact_value_string(ivar_types));
  1469. lb_emit_runtime_call(p, "class_addIvar", args);
  1470. }
  1471. // Complete the class registration
  1472. args.count = 1;
  1473. args[0] = class_value;
  1474. lb_emit_runtime_call(p, "objc_registerClassPair", args);
  1475. }
  1476. // Register ivar offsets for any `objc_ivar_get` expressions emitted.
  1477. for (auto const& kv : ivar_map) {
  1478. lbObjCGlobal const& g = kv.value;
  1479. lbAddr ivar_addr = {};
  1480. lbValue *found = string_map_get(&m->members, g.global_name);
  1481. if (found) {
  1482. ivar_addr = lb_addr(*found);
  1483. GB_ASSERT(ivar_addr.addr.type == t_int_ptr);
  1484. } else {
  1485. // Defined in an external package, define it now in the main package
  1486. LLVMTypeRef t = lb_type(m, t_int);
  1487. lbValue global{};
  1488. global.value = LLVMAddGlobal(m->mod, t, g.global_name);
  1489. global.type = t_int_ptr;
  1490. LLVMSetInitializer(global.value, LLVMConstInt(t, 0, true));
  1491. ivar_addr = lb_addr(global);
  1492. }
  1493. String class_name = g.class_impl_type->Named.type_name->TypeName.objc_class_name;
  1494. lbValue class_value = string_map_must_get(&global_class_map, class_name).class_value;
  1495. args.count = 2;
  1496. args[0] = class_value;
  1497. args[1] = lb_const_value(m, t_cstring, exact_value_string(str_lit("__$ivar")));
  1498. lbValue ivar = lb_emit_runtime_call(p, "class_getInstanceVariable", args);
  1499. args.count = 1;
  1500. args[0] = ivar;
  1501. lbValue ivar_offset = lb_emit_runtime_call(p, "ivar_getOffset", args);
  1502. lbValue ivar_offset_int = lb_emit_conv(p, ivar_offset, t_int);
  1503. lb_addr_store(p, ivar_addr, ivar_offset_int);
  1504. }
  1505. lb_end_procedure_body(p);
  1506. }
  1507. gb_internal void lb_verify_function(lbModule *m, lbProcedure *p, bool dump_ll=false) {
  1508. if (LLVM_IGNORE_VERIFICATION) {
  1509. return;
  1510. }
  1511. if (!m->debug_builder && LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) {
  1512. char *llvm_error = nullptr;
  1513. gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name));
  1514. LLVMDumpValue(p->value);
  1515. gb_printf_err("\n");
  1516. if (dump_ll) {
  1517. gb_printf_err("\n\n\n");
  1518. String filepath_ll = lb_filepath_ll_for_module(m);
  1519. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1520. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1521. }
  1522. }
  1523. LLVMVerifyFunction(p->value, LLVMPrintMessageAction);
  1524. exit_with_errors();
  1525. }
  1526. }
  1527. gb_internal WORKER_TASK_PROC(lb_llvm_module_verification_worker_proc) {
  1528. if (LLVM_IGNORE_VERIFICATION) {
  1529. return 0;
  1530. }
  1531. char *llvm_error = nullptr;
  1532. defer (LLVMDisposeMessage(llvm_error));
  1533. lbModule *m = cast(lbModule *)data;
  1534. if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) {
  1535. gb_printf_err("LLVM Error in module %s:\n%s\n", m->module_name, llvm_error);
  1536. if (build_context.keep_temp_files) {
  1537. TIME_SECTION("LLVM Print Module to File");
  1538. String filepath_ll = lb_filepath_ll_for_module(m);
  1539. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1540. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1541. exit_with_errors();
  1542. return false;
  1543. }
  1544. }
  1545. exit_with_errors();
  1546. return 1;
  1547. }
  1548. return 0;
  1549. }
  1550. gb_internal bool lb_init_global_var(lbModule *m, lbProcedure *p, Entity *e, Ast *init_expr, lbGlobalVariable &var) {
  1551. if (init_expr != nullptr) {
  1552. lbValue init = lb_build_expr(p, init_expr);
  1553. if (init.value == nullptr) {
  1554. LLVMTypeRef global_type = llvm_addr_type(p->module, var.var);
  1555. if (is_type_untyped_nil(init.type)) {
  1556. LLVMSetInitializer(var.var.value, LLVMConstNull(global_type));
  1557. var.is_initialized = true;
  1558. if (e->Variable.is_rodata) {
  1559. LLVMSetGlobalConstant(var.var.value, true);
  1560. }
  1561. return true;
  1562. }
  1563. GB_PANIC("Invalid init value, got %s", expr_to_string(init_expr));
  1564. }
  1565. if (is_type_any(e->type)) {
  1566. var.init = init;
  1567. } else if (lb_is_const_or_global(init)) {
  1568. if (!var.is_initialized) {
  1569. if (is_type_proc(init.type)) {
  1570. init.value = LLVMConstPointerCast(init.value, lb_type(p->module, init.type));
  1571. }
  1572. LLVMSetInitializer(var.var.value, init.value);
  1573. var.is_initialized = true;
  1574. if (e->Variable.is_rodata) {
  1575. LLVMSetGlobalConstant(var.var.value, true);
  1576. }
  1577. return true;
  1578. }
  1579. } else {
  1580. var.init = init;
  1581. }
  1582. }
  1583. if (var.init.value != nullptr) {
  1584. GB_ASSERT(!var.is_initialized);
  1585. Type *t = type_deref(var.var.type);
  1586. if (is_type_any(t)) {
  1587. // NOTE(bill): Edge case for 'any' type
  1588. Type *var_type = default_type(var.init.type);
  1589. gbString var_name = gb_string_make(permanent_allocator(), "__$global_any::");
  1590. gbString e_str = string_canonical_entity_name(temporary_allocator(), e);
  1591. var_name = gb_string_append_length(var_name, e_str, gb_strlen(e_str));
  1592. lbAddr g = lb_add_global_generated_with_name(m, var_type, {}, make_string_c(var_name));
  1593. lb_addr_store(p, g, var.init);
  1594. lbValue gp = lb_addr_get_ptr(p, g);
  1595. lbValue data = lb_emit_struct_ep(p, var.var, 0);
  1596. lbValue ti = lb_emit_struct_ep(p, var.var, 1);
  1597. lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr));
  1598. lb_emit_store(p, ti, lb_typeid(p->module, var_type));
  1599. } else {
  1600. LLVMTypeRef vt = llvm_addr_type(p->module, var.var);
  1601. lbValue src0 = lb_emit_conv(p, var.init, t);
  1602. LLVMValueRef src = OdinLLVMBuildTransmute(p, src0.value, vt);
  1603. LLVMValueRef dst = var.var.value;
  1604. LLVMBuildStore(p->builder, src, dst);
  1605. }
  1606. var.is_initialized = true;
  1607. }
  1608. return false;
  1609. }
  1610. gb_internal void lb_create_startup_runtime_generate_body(lbModule *m, lbProcedure *p) {
  1611. lb_begin_procedure_body(p);
  1612. lb_setup_type_info_data(m);
  1613. if (p->objc_names) {
  1614. LLVMBuildCall2(p->builder, lb_type_internal_for_procedures_raw(m, p->objc_names->type), p->objc_names->value, nullptr, 0, "");
  1615. }
  1616. Type *dummy_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  1617. LLVMTypeRef raw_dummy_type = lb_type_internal_for_procedures_raw(m, dummy_type);
  1618. for (auto &var : *p->global_variables) {
  1619. if (var.is_initialized) {
  1620. continue;
  1621. }
  1622. lbModule *entity_module = m;
  1623. Entity *e = var.decl->entity;
  1624. GB_ASSERT(e->kind == Entity_Variable);
  1625. e->code_gen_module = entity_module;
  1626. Ast *init_expr = var.decl->init_expr;
  1627. if (init_expr == nullptr && var.init.value == nullptr) {
  1628. continue;
  1629. }
  1630. if (type_size_of(e->type) > 8) {
  1631. String ename = lb_get_entity_name(m, e);
  1632. gbString name = gb_string_make(permanent_allocator(), "");
  1633. name = gb_string_appendc(name, "__$startup$");
  1634. name = gb_string_append_length(name, ename.text, ename.len);
  1635. lbProcedure *dummy = lb_create_dummy_procedure(m, make_string_c(name), dummy_type);
  1636. LLVMSetVisibility(dummy->value, LLVMHiddenVisibility);
  1637. LLVMSetLinkage(dummy->value, LLVMWeakAnyLinkage);
  1638. lb_begin_procedure_body(dummy);
  1639. lb_init_global_var(m, dummy, e, init_expr, var);
  1640. lb_end_procedure_body(dummy);
  1641. LLVMValueRef context_ptr = lb_find_or_generate_context_ptr(p).addr.value;
  1642. LLVMBuildCall2(p->builder, raw_dummy_type, dummy->value, &context_ptr, 1, "");
  1643. } else {
  1644. lb_init_global_var(m, p, e, init_expr, var);
  1645. }
  1646. }
  1647. CheckerInfo *info = m->gen->info;
  1648. for (Entity *e : info->init_procedures) {
  1649. lbValue value = lb_find_procedure_value_from_entity(m, e);
  1650. lb_emit_call(p, value, {}, ProcInlining_none);
  1651. }
  1652. lb_end_procedure_body(p);
  1653. }
  1654. gb_internal lbProcedure *lb_create_startup_runtime(lbModule *main_module, lbProcedure *objc_names, Array<lbGlobalVariable> &global_variables) { // Startup Runtime
  1655. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  1656. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type);
  1657. p->is_startup = true;
  1658. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  1659. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  1660. // Make sure shared libraries call their own runtime startup on Linux.
  1661. LLVMSetVisibility(p->value, LLVMHiddenVisibility);
  1662. LLVMSetLinkage(p->value, LLVMWeakAnyLinkage);
  1663. p->global_variables = &global_variables;
  1664. p->objc_names = objc_names;
  1665. lb_create_startup_runtime_generate_body(main_module, p);
  1666. return p;
  1667. }
  1668. gb_internal lbProcedure *lb_create_cleanup_runtime(lbModule *main_module) { // Cleanup Runtime
  1669. Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin);
  1670. lbProcedure *p = lb_create_dummy_procedure(main_module, str_lit(LB_CLEANUP_RUNTIME_PROC_NAME), proc_type);
  1671. p->is_startup = true;
  1672. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  1673. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  1674. // Make sure shared libraries call their own runtime cleanup on Linux.
  1675. LLVMSetVisibility(p->value, LLVMHiddenVisibility);
  1676. LLVMSetLinkage(p->value, LLVMWeakAnyLinkage);
  1677. lb_begin_procedure_body(p);
  1678. CheckerInfo *info = main_module->gen->info;
  1679. for (Entity *e : info->fini_procedures) {
  1680. lbValue value = lb_find_procedure_value_from_entity(main_module, e);
  1681. lb_emit_call(p, value, {}, ProcInlining_none);
  1682. }
  1683. lb_end_procedure_body(p);
  1684. lb_verify_function(main_module, p);
  1685. return p;
  1686. }
  1687. gb_internal WORKER_TASK_PROC(lb_generate_procedures_and_types_per_module) {
  1688. lbModule *m = cast(lbModule *)data;
  1689. for (Entity *e : m->global_types_to_create) {
  1690. (void)lb_get_entity_name(m, e);
  1691. (void)lb_type(m, e->type);
  1692. }
  1693. for (Entity *e : m->global_procedures_to_create) {
  1694. (void)lb_get_entity_name(m, e);
  1695. mpsc_enqueue(&m->procedures_to_generate, lb_create_procedure(m, e));
  1696. }
  1697. return 0;
  1698. }
  1699. gb_internal GB_COMPARE_PROC(llvm_global_entity_cmp) {
  1700. Entity *x = *cast(Entity **)a;
  1701. Entity *y = *cast(Entity **)b;
  1702. if (x == y) {
  1703. return 0;
  1704. }
  1705. if (x->kind != y->kind) {
  1706. return cast(i32)(x->kind - y->kind);
  1707. }
  1708. i32 cmp = 0;
  1709. cmp = token_pos_cmp(x->token.pos, y->token.pos);
  1710. if (!cmp) {
  1711. return cmp;
  1712. }
  1713. return cmp;
  1714. }
  1715. gb_internal void lb_create_global_procedures_and_types(lbGenerator *gen, CheckerInfo *info, bool do_threading) {
  1716. for (Entity *e : info->entities) {
  1717. String name = e->token.string;
  1718. Scope * scope = e->scope;
  1719. if ((scope->flags & ScopeFlag_File) == 0) {
  1720. continue;
  1721. }
  1722. Scope *package_scope = scope->parent;
  1723. GB_ASSERT(package_scope->flags & ScopeFlag_Pkg);
  1724. switch (e->kind) {
  1725. case Entity_Variable:
  1726. // NOTE(bill): Handled above as it requires a specific load order
  1727. continue;
  1728. case Entity_ProcGroup:
  1729. continue;
  1730. case Entity_TypeName:
  1731. case Entity_Procedure:
  1732. break;
  1733. case Entity_Constant:
  1734. if (build_context.ODIN_DEBUG) {
  1735. lb_add_debug_info_for_global_constant_from_entity(gen, e);
  1736. }
  1737. break;
  1738. }
  1739. bool polymorphic_struct = false;
  1740. if (e->type != nullptr && e->kind == Entity_TypeName) {
  1741. Type *bt = base_type(e->type);
  1742. if (bt->kind == Type_Struct) {
  1743. polymorphic_struct = is_type_polymorphic(bt);
  1744. }
  1745. }
  1746. if (!polymorphic_struct && e->min_dep_count.load(std::memory_order_relaxed) == 0) {
  1747. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1748. continue;
  1749. }
  1750. // if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  1751. // // NOTE(bill): Nothing depends upon it so doesn't need to be built
  1752. // continue;
  1753. // }
  1754. lbModule *m = &gen->default_module;
  1755. if (USE_SEPARATE_MODULES) {
  1756. m = lb_module_of_entity(gen, e, m);
  1757. }
  1758. GB_ASSERT(m != nullptr);
  1759. if (e->kind == Entity_Procedure) {
  1760. array_add(&m->global_procedures_to_create, e);
  1761. } else if (e->kind == Entity_TypeName) {
  1762. array_add(&m->global_types_to_create, e);
  1763. }
  1764. }
  1765. for (auto const &entry : gen->modules) {
  1766. lbModule *m = entry.value;
  1767. array_sort(m->global_types_to_create, llvm_global_entity_cmp);
  1768. array_sort(m->global_procedures_to_create, llvm_global_entity_cmp);
  1769. }
  1770. if (do_threading) {
  1771. for (auto const &entry : gen->modules) {
  1772. lbModule *m = entry.value;
  1773. thread_pool_add_task(lb_generate_procedures_and_types_per_module, m);
  1774. }
  1775. } else {
  1776. for (auto const &entry : gen->modules) {
  1777. lbModule *m = entry.value;
  1778. lb_generate_procedures_and_types_per_module(m);
  1779. }
  1780. }
  1781. thread_pool_wait();
  1782. }
  1783. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p);
  1784. gb_internal bool lb_is_module_empty(lbModule *m) {
  1785. if (LLVMGetFirstFunction(m->mod) == nullptr &&
  1786. LLVMGetFirstGlobal(m->mod) == nullptr) {
  1787. return true;
  1788. }
  1789. for (auto fn = LLVMGetFirstFunction(m->mod); fn != nullptr; fn = LLVMGetNextFunction(fn)) {
  1790. if (LLVMGetFirstBasicBlock(fn) != nullptr) {
  1791. return false;
  1792. }
  1793. }
  1794. for (auto g = LLVMGetFirstGlobal(m->mod); g != nullptr; g = LLVMGetNextGlobal(g)) {
  1795. LLVMLinkage linkage = LLVMGetLinkage(g);
  1796. if (linkage == LLVMExternalLinkage ||
  1797. linkage == LLVMWeakAnyLinkage) {
  1798. continue;
  1799. }
  1800. if (!LLVMIsExternallyInitialized(g)) {
  1801. return false;
  1802. }
  1803. }
  1804. return true;
  1805. }
  1806. struct lbLLVMEmitWorker {
  1807. LLVMTargetMachineRef target_machine;
  1808. LLVMCodeGenFileType code_gen_file_type;
  1809. String filepath_obj;
  1810. lbModule *m;
  1811. };
  1812. gb_internal WORKER_TASK_PROC(lb_llvm_emit_worker_proc) {
  1813. GB_ASSERT(MULTITHREAD_OBJECT_GENERATION);
  1814. char *llvm_error = nullptr;
  1815. auto wd = cast(lbLLVMEmitWorker *)data;
  1816. if (LLVMTargetMachineEmitToFile(wd->target_machine, wd->m->mod, cast(char *)wd->filepath_obj.text, wd->code_gen_file_type, &llvm_error)) {
  1817. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1818. exit_with_errors();
  1819. }
  1820. debugf("Generated File: %.*s\n", LIT(wd->filepath_obj));
  1821. return 0;
  1822. }
  1823. gb_internal void lb_llvm_function_pass_per_function_internal(lbModule *module, lbProcedure *p, lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default) {
  1824. LLVMPassManagerRef pass_manager = module->function_pass_managers[pass_manager_kind];
  1825. lb_run_function_pass_manager(pass_manager, p, pass_manager_kind);
  1826. }
  1827. gb_internal WORKER_TASK_PROC(lb_llvm_function_pass_per_module) {
  1828. lbModule *m = cast(lbModule *)data;
  1829. {
  1830. GB_ASSERT(m->function_pass_managers[lbFunctionPassManager_default] == nullptr);
  1831. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1832. m->function_pass_managers[i] = LLVMCreateFunctionPassManagerForModule(m->mod);
  1833. }
  1834. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1835. LLVMInitializeFunctionPassManager(m->function_pass_managers[i]);
  1836. }
  1837. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default], false, build_context.optimization_level);
  1838. lb_populate_function_pass_manager(m, m->function_pass_managers[lbFunctionPassManager_default_without_memcpy], true, build_context.optimization_level);
  1839. lb_populate_function_pass_manager_specific(m, m->function_pass_managers[lbFunctionPassManager_none], -1);
  1840. for (i32 i = 0; i < lbFunctionPassManager_COUNT; i++) {
  1841. LLVMFinalizeFunctionPassManager(m->function_pass_managers[i]);
  1842. }
  1843. }
  1844. if (m == &m->gen->default_module) {
  1845. lb_llvm_function_pass_per_function_internal(m, m->gen->startup_runtime);
  1846. lb_llvm_function_pass_per_function_internal(m, m->gen->cleanup_runtime);
  1847. lb_llvm_function_pass_per_function_internal(m, m->gen->objc_names);
  1848. }
  1849. MUTEX_GUARD_BLOCK(&m->generated_procedures_mutex) for (lbProcedure *p : m->generated_procedures) {
  1850. if (p->body != nullptr) { // Build Procedure
  1851. lbFunctionPassManagerKind pass_manager_kind = lbFunctionPassManager_default;
  1852. if (p->flags & lbProcedureFlag_WithoutMemcpyPass) {
  1853. pass_manager_kind = lbFunctionPassManager_default_without_memcpy;
  1854. lb_add_attribute_to_proc(p->module, p->value, "optnone");
  1855. lb_add_attribute_to_proc(p->module, p->value, "noinline");
  1856. } else {
  1857. if (p->entity && p->entity->kind == Entity_Procedure) {
  1858. switch (p->entity->Procedure.optimization_mode) {
  1859. case ProcedureOptimizationMode_None:
  1860. pass_manager_kind = lbFunctionPassManager_none;
  1861. GB_ASSERT(lb_proc_has_attribute(p->module, p->value, "optnone"));
  1862. GB_ASSERT(lb_proc_has_attribute(p->module, p->value, "noinline"));
  1863. break;
  1864. case ProcedureOptimizationMode_FavorSize:
  1865. GB_ASSERT(lb_proc_has_attribute(p->module, p->value, "optsize"));
  1866. break;
  1867. }
  1868. }
  1869. }
  1870. lb_llvm_function_pass_per_function_internal(m, p, pass_manager_kind);
  1871. }
  1872. }
  1873. for (auto const &entry : m->gen_procs) {
  1874. lbProcedure *p = entry.value;
  1875. if (string_starts_with(p->name, str_lit("__$map"))) {
  1876. lb_llvm_function_pass_per_function_internal(m, p, lbFunctionPassManager_none);
  1877. } else {
  1878. lb_llvm_function_pass_per_function_internal(m, p);
  1879. }
  1880. }
  1881. return 0;
  1882. }
  1883. void lb_remove_unused_functions_and_globals(lbGenerator *gen) {
  1884. for (auto &entry : gen->modules) {
  1885. lbModule *m = entry.value;
  1886. lb_run_remove_unused_function_pass(m);
  1887. lb_run_remove_unused_globals_pass(m);
  1888. }
  1889. }
  1890. struct lbLLVMModulePassWorkerData {
  1891. lbModule *m;
  1892. LLVMTargetMachineRef target_machine;
  1893. bool do_threading;
  1894. };
  1895. gb_internal WORKER_TASK_PROC(lb_llvm_module_pass_worker_proc) {
  1896. auto wd = cast(lbLLVMModulePassWorkerData *)data;
  1897. LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager();
  1898. lb_populate_module_pass_manager(wd->target_machine, module_pass_manager, build_context.optimization_level);
  1899. LLVMRunPassManager(module_pass_manager, wd->m->mod);
  1900. #if LB_USE_NEW_PASS_SYSTEM
  1901. auto passes = array_make<char const *>(heap_allocator(), 0, 64);
  1902. defer (array_free(&passes));
  1903. LLVMPassBuilderOptionsRef pb_options = LLVMCreatePassBuilderOptions();
  1904. defer (LLVMDisposePassBuilderOptions(pb_options));
  1905. #include "llvm_backend_passes.cpp"
  1906. // asan - Linux, Darwin, Windows
  1907. // msan - linux
  1908. // tsan - Linux, Darwin
  1909. // ubsan - Linux, Darwin, Windows (NOT SUPPORTED WITH LLVM C-API)
  1910. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  1911. array_add(&passes, "asan");
  1912. }
  1913. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  1914. array_add(&passes, "msan");
  1915. }
  1916. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  1917. array_add(&passes, "tsan");
  1918. }
  1919. if (passes.count == 0) {
  1920. array_add(&passes, "verify");
  1921. }
  1922. gbString passes_str = gb_string_make_reserve(heap_allocator(), 1024);
  1923. defer (gb_string_free(passes_str));
  1924. for_array(i, passes) {
  1925. if (i != 0) {
  1926. passes_str = gb_string_appendc(passes_str, ",");
  1927. }
  1928. passes_str = gb_string_appendc(passes_str, passes[i]);
  1929. }
  1930. for (isize i = 0; i < gb_string_length(passes_str); /**/) {
  1931. switch (passes_str[i]) {
  1932. case ' ':
  1933. case '\n':
  1934. case '\t':
  1935. gb_memmove(&passes_str[i], &passes_str[i+1], gb_string_length(passes_str)-i);
  1936. GB_STRING_HEADER(passes_str)->length -= 1;
  1937. continue;
  1938. default:
  1939. i += 1;
  1940. break;
  1941. }
  1942. }
  1943. LLVMErrorRef llvm_err = LLVMRunPasses(wd->m->mod, passes_str, wd->target_machine, pb_options);
  1944. defer (LLVMConsumeError(llvm_err));
  1945. if (llvm_err != nullptr) {
  1946. char *llvm_error = LLVMGetErrorMessage(llvm_err);
  1947. gb_printf_err("LLVM Error:\n%s\n", llvm_error);
  1948. LLVMDisposeErrorMessage(llvm_error);
  1949. llvm_error = nullptr;
  1950. if (build_context.keep_temp_files) {
  1951. TIME_SECTION("LLVM Print Module to File");
  1952. String filepath_ll = lb_filepath_ll_for_module(wd->m);
  1953. if (LLVMPrintModuleToFile(wd->m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  1954. gb_printf_err("LLVM Error: %s\n", llvm_error);
  1955. }
  1956. }
  1957. exit_with_errors();
  1958. return 1;
  1959. }
  1960. #endif
  1961. if (LLVM_IGNORE_VERIFICATION) {
  1962. return 0;
  1963. }
  1964. if (wd->do_threading) {
  1965. thread_pool_add_task(lb_llvm_module_verification_worker_proc, wd->m);
  1966. } else {
  1967. lb_llvm_module_verification_worker_proc(wd->m);
  1968. }
  1969. return 0;
  1970. }
  1971. gb_internal WORKER_TASK_PROC(lb_generate_procedures_worker_proc) {
  1972. lbModule *m = cast(lbModule *)data;
  1973. for (lbProcedure *p = nullptr; mpsc_dequeue(&m->procedures_to_generate, &p); /**/) {
  1974. lb_generate_procedure(p->module, p);
  1975. }
  1976. return 0;
  1977. }
  1978. gb_internal void lb_generate_procedures(lbGenerator *gen, bool do_threading) {
  1979. if (do_threading) {
  1980. for (auto const &entry : gen->modules) {
  1981. lbModule *m = entry.value;
  1982. thread_pool_add_task(lb_generate_procedures_worker_proc, m);
  1983. }
  1984. thread_pool_wait();
  1985. } else {
  1986. for (auto const &entry : gen->modules) {
  1987. lbModule *m = entry.value;
  1988. lb_generate_procedures_worker_proc(m);
  1989. }
  1990. }
  1991. }
  1992. gb_internal WORKER_TASK_PROC(lb_generate_missing_procedures_to_check_worker_proc) {
  1993. lbModule *m = cast(lbModule *)data;
  1994. for (lbProcedure *p = nullptr; mpsc_dequeue(&m->missing_procedures_to_check, &p); /**/) {
  1995. if (!p->is_done.load(std::memory_order_relaxed)) {
  1996. debugf("Generate missing procedure: %.*s module %p\n", LIT(p->name), m);
  1997. lb_generate_procedure(m, p);
  1998. }
  1999. for (lbProcedure *nested = nullptr; mpsc_dequeue(&m->procedures_to_generate, &nested); /**/) {
  2000. mpsc_enqueue(&m->missing_procedures_to_check, nested);
  2001. }
  2002. }
  2003. return 0;
  2004. }
  2005. gb_internal void lb_generate_missing_procedures(lbGenerator *gen, bool do_threading) {
  2006. if (do_threading) {
  2007. for (auto const &entry : gen->modules) {
  2008. lbModule *m = entry.value;
  2009. // NOTE(bill): procedures may be added during generation
  2010. thread_pool_add_task(lb_generate_missing_procedures_to_check_worker_proc, m);
  2011. }
  2012. thread_pool_wait();
  2013. } else {
  2014. for (auto const &entry : gen->modules) {
  2015. lbModule *m = entry.value;
  2016. // NOTE(bill): procedures may be added during generation
  2017. lb_generate_missing_procedures_to_check_worker_proc(m);
  2018. }
  2019. }
  2020. for (auto const &entry : gen->modules) {
  2021. lbModule *m = entry.value;
  2022. GB_ASSERT(m->missing_procedures_to_check.count == 0);
  2023. GB_ASSERT(m->procedures_to_generate.count == 0);
  2024. }
  2025. }
  2026. gb_internal void lb_debug_info_complete_types_and_finalize(lbGenerator *gen) {
  2027. for (auto const &entry : gen->modules) {
  2028. lbModule *m = entry.value;
  2029. if (m->debug_builder != nullptr) {
  2030. LLVMDIBuilderFinalize(m->debug_builder);
  2031. }
  2032. }
  2033. }
  2034. gb_internal void lb_llvm_function_passes(lbGenerator *gen, bool do_threading) {
  2035. if (do_threading) {
  2036. for (auto const &entry : gen->modules) {
  2037. lbModule *m = entry.value;
  2038. thread_pool_add_task(lb_llvm_function_pass_per_module, m);
  2039. }
  2040. thread_pool_wait();
  2041. } else {
  2042. for (auto const &entry : gen->modules) {
  2043. lbModule *m = entry.value;
  2044. lb_llvm_function_pass_per_module(m);
  2045. }
  2046. }
  2047. }
  2048. gb_internal void lb_llvm_module_passes_and_verification(lbGenerator *gen, bool do_threading) {
  2049. if (do_threading) {
  2050. for (auto const &entry : gen->modules) {
  2051. lbModule *m = entry.value;
  2052. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  2053. wd->m = m;
  2054. wd->target_machine = m->target_machine;
  2055. wd->do_threading = true;
  2056. thread_pool_add_task(lb_llvm_module_pass_worker_proc, wd);
  2057. }
  2058. thread_pool_wait();
  2059. } else {
  2060. for (auto const &entry : gen->modules) {
  2061. lbModule *m = entry.value;
  2062. auto wd = gb_alloc_item(permanent_allocator(), lbLLVMModulePassWorkerData);
  2063. wd->m = m;
  2064. wd->target_machine = m->target_machine;
  2065. wd->do_threading = false;
  2066. lb_llvm_module_pass_worker_proc(wd);
  2067. }
  2068. }
  2069. }
  2070. gb_internal String lb_filepath_ll_for_module(lbModule *m) {
  2071. String path = concatenate3_strings(permanent_allocator(),
  2072. build_context.build_paths[BuildPath_Output].basename,
  2073. STR_LIT("/"),
  2074. build_context.build_paths[BuildPath_Output].name
  2075. );
  2076. GB_ASSERT(m->module_name != nullptr);
  2077. String s = make_string_c(m->module_name);
  2078. String prefix = str_lit("odin_package-");
  2079. if (string_starts_with(s, prefix)) {
  2080. s.text += prefix.len;
  2081. s.len -= prefix.len;
  2082. }
  2083. path = concatenate_strings(permanent_allocator(), path, s);
  2084. path = concatenate_strings(permanent_allocator(), s, STR_LIT(".ll"));
  2085. return path;
  2086. }
  2087. gb_internal String lb_filepath_obj_for_module(lbModule *m) {
  2088. String basename = build_context.build_paths[BuildPath_Output].basename;
  2089. String name = build_context.build_paths[BuildPath_Output].name;
  2090. bool use_temporary_directory = false;
  2091. if (USE_SEPARATE_MODULES && build_context.build_mode == BuildMode_Executable) {
  2092. // NOTE(bill): use a temporary directory
  2093. String dir = temporary_directory(permanent_allocator());
  2094. if (dir.len != 0) {
  2095. basename = dir;
  2096. use_temporary_directory = true;
  2097. }
  2098. }
  2099. gbString path = gb_string_make_length(heap_allocator(), basename.text, basename.len);
  2100. path = gb_string_appendc(path, "/");
  2101. if (USE_SEPARATE_MODULES) {
  2102. GB_ASSERT(m->module_name != nullptr);
  2103. String s = make_string_c(m->module_name);
  2104. String prefix = str_lit("odin_package");
  2105. if (string_starts_with(s, prefix)) {
  2106. s.text += prefix.len;
  2107. s.len -= prefix.len;
  2108. }
  2109. path = gb_string_append_length(path, s.text, s.len);
  2110. } else {
  2111. path = gb_string_append_length(path, name.text, name.len);
  2112. }
  2113. if (use_temporary_directory) {
  2114. // NOTE(bill): this must be suffixed to ensure it is not conflicting with anything else in the temporary directory
  2115. path = gb_string_append_fmt(path, "-%p", m);
  2116. }
  2117. String ext = {};
  2118. if (build_context.build_mode == BuildMode_Assembly) {
  2119. ext = STR_LIT("S");
  2120. } else if (build_context.build_mode == BuildMode_Object) {
  2121. // Allow a user override for the object extension.
  2122. ext = build_context.build_paths[BuildPath_Output].ext;
  2123. } else {
  2124. ext = infer_object_extension_from_build_context();
  2125. }
  2126. path = gb_string_append_length(path, ".", 1);
  2127. path = gb_string_append_length(path, ext.text, ext.len);
  2128. return make_string(cast(u8 *)path, gb_string_length(path));
  2129. }
  2130. gb_internal void lb_add_foreign_library_paths(lbGenerator *gen) {
  2131. for (auto const &entry : gen->modules) {
  2132. lbModule *m = entry.value;
  2133. for (Entity *e : m->info->required_foreign_imports_through_force) {
  2134. lb_add_foreign_library_path(m, e);
  2135. }
  2136. if (lb_is_module_empty(m)) {
  2137. continue;
  2138. }
  2139. }
  2140. }
  2141. gb_internal bool lb_llvm_object_generation(lbGenerator *gen, bool do_threading) {
  2142. LLVMCodeGenFileType code_gen_file_type = LLVMObjectFile;
  2143. if (build_context.build_mode == BuildMode_Assembly) {
  2144. code_gen_file_type = LLVMAssemblyFile;
  2145. }
  2146. char *llvm_error = nullptr;
  2147. defer (LLVMDisposeMessage(llvm_error));
  2148. if (do_threading) {
  2149. for (auto const &entry : gen->modules) {
  2150. lbModule *m = entry.value;
  2151. if (lb_is_module_empty(m)) {
  2152. continue;
  2153. }
  2154. String filepath_ll = lb_filepath_ll_for_module(m);
  2155. String filepath_obj = lb_filepath_obj_for_module(m);
  2156. array_add(&gen->output_object_paths, filepath_obj);
  2157. array_add(&gen->output_temp_paths, filepath_ll);
  2158. auto *wd = gb_alloc_item(permanent_allocator(), lbLLVMEmitWorker);
  2159. wd->target_machine = m->target_machine;
  2160. wd->code_gen_file_type = code_gen_file_type;
  2161. wd->filepath_obj = filepath_obj;
  2162. wd->m = m;
  2163. thread_pool_add_task(lb_llvm_emit_worker_proc, wd);
  2164. }
  2165. thread_pool_wait(&global_thread_pool);
  2166. } else {
  2167. for (auto const &entry : gen->modules) {
  2168. lbModule *m = entry.value;
  2169. if (lb_is_module_empty(m)) {
  2170. continue;
  2171. }
  2172. String filepath_obj = lb_filepath_obj_for_module(m);
  2173. array_add(&gen->output_object_paths, filepath_obj);
  2174. String short_name = remove_directory_from_path(filepath_obj);
  2175. gbString section_name = gb_string_make(permanent_allocator(), "LLVM Generate Object: ");
  2176. section_name = gb_string_append_length(section_name, short_name.text, short_name.len);
  2177. TIME_SECTION_WITH_LEN(section_name, gb_string_length(section_name));
  2178. if (LLVMTargetMachineEmitToFile(m->target_machine, m->mod, cast(char *)filepath_obj.text, code_gen_file_type, &llvm_error)) {
  2179. gb_printf_err("LLVM Error: %s\n", llvm_error);
  2180. exit_with_errors();
  2181. return false;
  2182. }
  2183. debugf("Generated File: %.*s\n", LIT(filepath_obj));
  2184. }
  2185. }
  2186. return true;
  2187. }
  2188. gb_internal lbProcedure *lb_create_main_procedure(lbModule *m, lbProcedure *startup_runtime, lbProcedure *cleanup_runtime) {
  2189. LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(m->mod);
  2190. lb_populate_function_pass_manager(m, default_function_pass_manager, false, build_context.optimization_level);
  2191. LLVMFinalizeFunctionPassManager(default_function_pass_manager);
  2192. Type *params = alloc_type_tuple();
  2193. Type *results = alloc_type_tuple();
  2194. Type *t_ptr_cstring = alloc_type_pointer(t_cstring);
  2195. bool call_cleanup = true;
  2196. bool has_args = false;
  2197. bool is_dll_main = false;
  2198. String name = str_lit("main");
  2199. if (build_context.metrics.os == TargetOs_windows && build_context.build_mode == BuildMode_DynamicLibrary) {
  2200. is_dll_main = true;
  2201. name = str_lit("DllMain");
  2202. slice_init(&params->Tuple.variables, permanent_allocator(), 3);
  2203. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("hinstDLL"), t_rawptr, false, true);
  2204. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("fdwReason"), t_u32, false, true);
  2205. params->Tuple.variables[2] = alloc_entity_param(nullptr, make_token_ident("lpReserved"), t_rawptr, false, true);
  2206. call_cleanup = false;
  2207. } else if (build_context.metrics.os == TargetOs_windows && build_context.no_crt) {
  2208. name = str_lit("mainCRTStartup");
  2209. } else if (build_context.metrics.os == TargetOs_windows && build_context.metrics.arch == TargetArch_i386 && !build_context.no_crt) {
  2210. // Windows i386 with CRT: libcmt expects _main (main with underscore prefix)
  2211. name = str_lit("main");
  2212. has_args = true;
  2213. slice_init(&params->Tuple.variables, permanent_allocator(), 2);
  2214. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  2215. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  2216. } else if (is_arch_wasm()) {
  2217. name = str_lit("_start");
  2218. call_cleanup = false;
  2219. } else {
  2220. has_args = true;
  2221. slice_init(&params->Tuple.variables, permanent_allocator(), 2);
  2222. params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true);
  2223. params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), t_ptr_cstring, false, true);
  2224. }
  2225. slice_init(&results->Tuple.variables, permanent_allocator(), 1);
  2226. results->Tuple.variables[0] = alloc_entity_param(nullptr, blank_token, t_i32, false, true);
  2227. Type *proc_type = alloc_type_proc(nullptr,
  2228. params, params->Tuple.variables.count,
  2229. results, results->Tuple.variables.count, false, ProcCC_CDecl);
  2230. lbProcedure *p = lb_create_dummy_procedure(m, name, proc_type);
  2231. p->is_startup = true;
  2232. lb_begin_procedure_body(p);
  2233. if (has_args) { // initialize `runtime.args__`
  2234. lbValue argc = {LLVMGetParam(p->value, 0), t_i32};
  2235. lbValue argv = {LLVMGetParam(p->value, 1), t_ptr_cstring};
  2236. LLVMSetValueName2(argc.value, "argc", 4);
  2237. LLVMSetValueName2(argv.value, "argv", 4);
  2238. argc = lb_emit_conv(p, argc, t_int);
  2239. lbAddr args = lb_addr(lb_find_runtime_value(p->module, str_lit("args__")));
  2240. lb_fill_slice(p, args, argv, argc);
  2241. }
  2242. lbValue startup_runtime_value = {startup_runtime->value, startup_runtime->type};
  2243. lb_emit_call(p, startup_runtime_value, {}, ProcInlining_none);
  2244. if (build_context.command_kind == Command_test) {
  2245. Type *t_Internal_Test = find_type_in_pkg(m->info, str_lit("testing"), str_lit("Internal_Test"));
  2246. Type *array_type = alloc_type_array(t_Internal_Test, m->info->testing_procedures.count);
  2247. Type *slice_type = alloc_type_slice(t_Internal_Test);
  2248. lbAddr all_tests_array_addr = lb_add_global_generated_with_name(p->module, array_type, {}, str_lit("__$all_tests_array"));
  2249. lbValue all_tests_array = lb_addr_get_ptr(p, all_tests_array_addr);
  2250. LLVMValueRef indices[2] = {};
  2251. indices[0] = LLVMConstInt(lb_type(m, t_i32), 0, false);
  2252. isize testing_proc_index = 0;
  2253. for (Entity *testing_proc : m->info->testing_procedures) {
  2254. String name = testing_proc->token.string;
  2255. String pkg_name = {};
  2256. if (testing_proc->pkg != nullptr) {
  2257. pkg_name = testing_proc->pkg->name;
  2258. }
  2259. lbValue v_pkg = lb_find_or_add_entity_string(m, pkg_name, false);
  2260. lbValue v_name = lb_find_or_add_entity_string(m, name, false);
  2261. lbValue v_proc = lb_find_procedure_value_from_entity(m, testing_proc);
  2262. indices[1] = LLVMConstInt(lb_type(m, t_int), testing_proc_index++, false);
  2263. LLVMValueRef vals[3] = {};
  2264. vals[0] = v_pkg.value;
  2265. vals[1] = v_name.value;
  2266. vals[2] = v_proc.value;
  2267. GB_ASSERT(LLVMIsConstant(vals[0]));
  2268. GB_ASSERT(LLVMIsConstant(vals[1]));
  2269. GB_ASSERT(LLVMIsConstant(vals[2]));
  2270. LLVMValueRef dst = LLVMConstInBoundsGEP2(llvm_addr_type(m, all_tests_array), all_tests_array.value, indices, gb_count_of(indices));
  2271. LLVMValueRef src = llvm_const_named_struct(m, t_Internal_Test, vals, gb_count_of(vals));
  2272. LLVMBuildStore(p->builder, src, dst);
  2273. }
  2274. lbAddr all_tests_slice = lb_add_local_generated(p, slice_type, true);
  2275. lb_fill_slice(p, all_tests_slice,
  2276. lb_array_elem(p, all_tests_array),
  2277. lb_const_int(m, t_int, m->info->testing_procedures.count));
  2278. lbValue runner = lb_find_package_value(m, str_lit("testing"), str_lit("runner"));
  2279. TEMPORARY_ALLOCATOR_GUARD();
  2280. auto args = array_make<lbValue>(temporary_allocator(), 1);
  2281. args[0] = lb_addr_load(p, all_tests_slice);
  2282. lbValue result = lb_emit_call(p, runner, args);
  2283. lbValue exit_runner = lb_find_package_value(m, str_lit("os"), str_lit("exit"));
  2284. auto exit_args = array_make<lbValue>(temporary_allocator(), 1);
  2285. exit_args[0] = lb_emit_select(p, result, lb_const_int(m, t_int, 0), lb_const_int(m, t_int, 1));
  2286. lb_emit_call(p, exit_runner, exit_args, ProcInlining_none);
  2287. } else {
  2288. if (m->info->entry_point != nullptr) {
  2289. lbValue entry_point = lb_find_procedure_value_from_entity(m, m->info->entry_point);
  2290. lb_emit_call(p, entry_point, {}, ProcInlining_no_inline);
  2291. }
  2292. if (call_cleanup) {
  2293. lbValue cleanup_runtime_value = {cleanup_runtime->value, cleanup_runtime->type};
  2294. lb_emit_call(p, cleanup_runtime_value, {}, ProcInlining_none);
  2295. }
  2296. if (is_dll_main) {
  2297. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 1, false));
  2298. } else {
  2299. LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false));
  2300. }
  2301. }
  2302. lb_end_procedure_body(p);
  2303. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  2304. if (is_arch_wasm()) {
  2305. lb_set_wasm_export_attributes(p->value, p->name);
  2306. }
  2307. lb_verify_function(m, p);
  2308. lb_run_function_pass_manager(default_function_pass_manager, p, lbFunctionPassManager_default);
  2309. return p;
  2310. }
  2311. gb_internal void lb_generate_procedure(lbModule *m, lbProcedure *p) {
  2312. if (p->is_done.load(std::memory_order_relaxed)) {
  2313. return;
  2314. }
  2315. if (p->body != nullptr) { // Build Procedure
  2316. m->curr_procedure = p;
  2317. lb_begin_procedure_body(p);
  2318. lb_build_stmt(p, p->body);
  2319. lb_end_procedure_body(p);
  2320. p->is_done.store(true, std::memory_order_relaxed);
  2321. m->curr_procedure = nullptr;
  2322. } else if (p->generate_body != nullptr) {
  2323. p->generate_body(m, p);
  2324. }
  2325. // Add Flags
  2326. if (p->entity && p->entity->kind == Entity_Procedure && p->entity->Procedure.is_memcpy_like) {
  2327. p->flags |= lbProcedureFlag_WithoutMemcpyPass;
  2328. }
  2329. lb_verify_function(m, p, true);
  2330. MUTEX_GUARD(&m->generated_procedures_mutex);
  2331. array_add(&m->generated_procedures, p);
  2332. }
  2333. gb_internal bool lb_generate_code(lbGenerator *gen) {
  2334. TIME_SECTION("LLVM Initializtion");
  2335. isize thread_count = gb_max(build_context.thread_count, 1);
  2336. isize worker_count = thread_count-1;
  2337. bool do_threading = !!(LLVMIsMultithreaded() && USE_SEPARATE_MODULES && MULTITHREAD_OBJECT_GENERATION && worker_count > 0);
  2338. lbModule *default_module = &gen->default_module;
  2339. CheckerInfo *info = gen->info;
  2340. switch (build_context.metrics.arch) {
  2341. case TargetArch_amd64:
  2342. case TargetArch_i386:
  2343. LLVMInitializeX86TargetInfo();
  2344. LLVMInitializeX86Target();
  2345. LLVMInitializeX86TargetMC();
  2346. LLVMInitializeX86AsmPrinter();
  2347. LLVMInitializeX86AsmParser();
  2348. LLVMInitializeX86Disassembler();
  2349. break;
  2350. case TargetArch_arm64:
  2351. LLVMInitializeAArch64TargetInfo();
  2352. LLVMInitializeAArch64Target();
  2353. LLVMInitializeAArch64TargetMC();
  2354. LLVMInitializeAArch64AsmPrinter();
  2355. LLVMInitializeAArch64AsmParser();
  2356. LLVMInitializeAArch64Disassembler();
  2357. break;
  2358. case TargetArch_wasm32:
  2359. case TargetArch_wasm64p32:
  2360. LLVMInitializeWebAssemblyTargetInfo();
  2361. LLVMInitializeWebAssemblyTarget();
  2362. LLVMInitializeWebAssemblyTargetMC();
  2363. LLVMInitializeWebAssemblyAsmPrinter();
  2364. LLVMInitializeWebAssemblyAsmParser();
  2365. LLVMInitializeWebAssemblyDisassembler();
  2366. break;
  2367. case TargetArch_riscv64:
  2368. LLVMInitializeRISCVTargetInfo();
  2369. LLVMInitializeRISCVTarget();
  2370. LLVMInitializeRISCVTargetMC();
  2371. LLVMInitializeRISCVAsmPrinter();
  2372. LLVMInitializeRISCVAsmParser();
  2373. LLVMInitializeRISCVDisassembler();
  2374. break;
  2375. case TargetArch_arm32:
  2376. LLVMInitializeARMTargetInfo();
  2377. LLVMInitializeARMTarget();
  2378. LLVMInitializeARMTargetMC();
  2379. LLVMInitializeARMAsmPrinter();
  2380. LLVMInitializeARMAsmParser();
  2381. LLVMInitializeARMDisassembler();
  2382. break;
  2383. default:
  2384. GB_PANIC("Unimplemented LLVM target initialization");
  2385. break;
  2386. }
  2387. if (build_context.microarch == "native") {
  2388. LLVMInitializeNativeTarget();
  2389. }
  2390. char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet);
  2391. for (auto const &entry : gen->modules) {
  2392. LLVMSetTarget(entry.value->mod, target_triple);
  2393. }
  2394. LLVMTargetRef target = {};
  2395. char *llvm_error = nullptr;
  2396. LLVMGetTargetFromTriple(target_triple, &target, &llvm_error);
  2397. GB_ASSERT(target != nullptr);
  2398. TIME_SECTION("LLVM Create Target Machine");
  2399. LLVMCodeModel code_mode = LLVMCodeModelDefault;
  2400. if (is_arch_wasm()) {
  2401. code_mode = LLVMCodeModelJITDefault;
  2402. } else if (is_arch_x86() && build_context.metrics.os == TargetOs_freestanding) {
  2403. code_mode = LLVMCodeModelKernel;
  2404. }
  2405. String llvm_cpu = get_final_microarchitecture();
  2406. gbString llvm_features = gb_string_make(temporary_allocator(), "");
  2407. String_Iterator it = {build_context.target_features_string, 0};
  2408. bool first = true;
  2409. for (;;) {
  2410. String str = string_split_iterator(&it, ',');
  2411. if (str == "") break;
  2412. if (!first) {
  2413. llvm_features = gb_string_appendc(llvm_features, ",");
  2414. }
  2415. first = false;
  2416. llvm_features = gb_string_appendc(llvm_features, "+");
  2417. llvm_features = gb_string_append_length(llvm_features, str.text, str.len);
  2418. }
  2419. debugf("CPU: %.*s, Features: %s\n", LIT(llvm_cpu), llvm_features);
  2420. // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target));
  2421. LLVMCodeGenOptLevel code_gen_level = LLVMCodeGenLevelNone;
  2422. if (!LB_USE_NEW_PASS_SYSTEM) {
  2423. build_context.optimization_level = gb_clamp(build_context.optimization_level, -1, 2);
  2424. }
  2425. switch (build_context.optimization_level) {
  2426. default:/*fallthrough*/
  2427. case 0: code_gen_level = LLVMCodeGenLevelNone; break;
  2428. case 1: code_gen_level = LLVMCodeGenLevelLess; break;
  2429. case 2: code_gen_level = LLVMCodeGenLevelDefault; break;
  2430. case 3: code_gen_level = LLVMCodeGenLevelAggressive; break;
  2431. }
  2432. // NOTE(bill): Target Machine Creation
  2433. // NOTE(bill, 2021-05-04): Target machines must be unique to each module because they are not thread safe
  2434. auto target_machines = array_make<LLVMTargetMachineRef>(permanent_allocator(), 0, gen->modules.count);
  2435. // NOTE(dweiler): Dynamic libraries require position-independent code.
  2436. LLVMRelocMode reloc_mode = LLVMRelocDefault;
  2437. if (build_context.build_mode == BuildMode_DynamicLibrary) {
  2438. reloc_mode = LLVMRelocPIC;
  2439. }
  2440. switch (build_context.reloc_mode) {
  2441. case RelocMode_Default:
  2442. if (build_context.metrics.os == TargetOs_openbsd || build_context.metrics.os == TargetOs_haiku) {
  2443. // Always use PIC for OpenBSD and Haiku: they default to PIE
  2444. reloc_mode = LLVMRelocPIC;
  2445. }
  2446. if (build_context.metrics.arch == TargetArch_riscv64) {
  2447. // NOTE(laytan): didn't seem to work without this.
  2448. reloc_mode = LLVMRelocPIC;
  2449. }
  2450. break;
  2451. case RelocMode_Static:
  2452. reloc_mode = LLVMRelocStatic;
  2453. break;
  2454. case RelocMode_PIC:
  2455. reloc_mode = LLVMRelocPIC;
  2456. break;
  2457. case RelocMode_DynamicNoPIC:
  2458. reloc_mode = LLVMRelocDynamicNoPic;
  2459. break;
  2460. }
  2461. for (auto const &entry : gen->modules) {
  2462. LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(
  2463. target, target_triple, (const char *)llvm_cpu.text,
  2464. llvm_features,
  2465. code_gen_level,
  2466. reloc_mode,
  2467. code_mode);
  2468. lbModule *m = entry.value;
  2469. m->target_machine = target_machine;
  2470. LLVMSetModuleDataLayout(m->mod, LLVMCreateTargetDataLayout(target_machine));
  2471. #if LLVM_VERSION_MAJOR >= 18
  2472. if (build_context.fast_isel) {
  2473. LLVMSetTargetMachineFastISel(m->target_machine, true);
  2474. }
  2475. #endif
  2476. array_add(&target_machines, target_machine);
  2477. }
  2478. for (auto const &entry : gen->modules) {
  2479. lbModule *m = entry.value;
  2480. if (m->debug_builder) { // Debug Info
  2481. for (auto const &file_entry : info->files) {
  2482. AstFile *f = file_entry.value;
  2483. LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder,
  2484. cast(char const *)f->filename.text, f->filename.len,
  2485. cast(char const *)f->directory.text, f->directory.len);
  2486. lb_set_llvm_metadata(m, f, res);
  2487. }
  2488. TEMPORARY_ALLOCATOR_GUARD();
  2489. gbString producer = gb_string_make(temporary_allocator(), "odin");
  2490. // producer = gb_string_append_fmt(producer, " version %.*s", LIT(ODIN_VERSION));
  2491. // #ifdef NIGHTLY
  2492. // producer = gb_string_appendc(producer, "-nightly");
  2493. // #endif
  2494. // #ifdef GIT_SHA
  2495. // producer = gb_string_append_fmt(producer, "-%s", GIT_SHA);
  2496. // #endif
  2497. gbString split_name = gb_string_make(temporary_allocator(), "");
  2498. LLVMBool is_optimized = build_context.optimization_level > 0;
  2499. AstFile *init_file = m->info->init_package->files[0];
  2500. if (Entity *entry_point = m->info->entry_point) {
  2501. if (Ast *ident = entry_point->identifier.load()) {
  2502. if (ident->file_id) {
  2503. init_file = ident->file();
  2504. }
  2505. }
  2506. }
  2507. LLVMBool split_debug_inlining = build_context.build_mode == BuildMode_Assembly;
  2508. LLVMBool debug_info_for_profiling = false;
  2509. m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC99,
  2510. lb_get_llvm_metadata(m, init_file),
  2511. producer, gb_string_length(producer),
  2512. is_optimized, "", 0,
  2513. 1, split_name, gb_string_length(split_name),
  2514. LLVMDWARFEmissionFull,
  2515. 0, split_debug_inlining,
  2516. debug_info_for_profiling,
  2517. "", 0, // sys_root
  2518. "", 0 // SDK
  2519. );
  2520. GB_ASSERT(m->debug_compile_unit != nullptr);
  2521. }
  2522. }
  2523. TIME_SECTION("LLVM Global Variables");
  2524. if (!build_context.no_rtti) {
  2525. lbModule *m = default_module;
  2526. { // Add type info data
  2527. // GB_ASSERT_MSG(info->minimum_dependency_type_info_index_map.count == info->type_info_types.count, "%tu vs %tu", info->minimum_dependency_type_info_index_map.count, info->type_info_types.count);
  2528. // isize max_type_info_count = info->minimum_dependency_type_info_index_map.count+1;
  2529. isize max_type_info_count = info->type_info_types_hash_map.count;
  2530. Type *t = alloc_type_array(t_type_info_ptr, max_type_info_count);
  2531. // IMPORTANT NOTE(bill): As LLVM does not have a union type, an array of unions cannot be initialized
  2532. // at compile time without cheating in some way. This means to emulate an array of unions is to use
  2533. // a giant packed struct of "corrected" data types.
  2534. LLVMTypeRef internal_llvm_type = lb_type(m, t);
  2535. LLVMValueRef g = LLVMAddGlobal(m->mod, internal_llvm_type, LB_TYPE_INFO_DATA_NAME);
  2536. LLVMSetInitializer(g, LLVMConstNull(internal_llvm_type));
  2537. LLVMSetLinkage(g, USE_SEPARATE_MODULES ? LLVMExternalLinkage : LLVMInternalLinkage);
  2538. // LLVMSetUnnamedAddress(g, LLVMGlobalUnnamedAddr);
  2539. LLVMSetGlobalConstant(g, true);
  2540. lbValue value = {};
  2541. value.value = g;
  2542. value.type = alloc_type_pointer(t);
  2543. lb_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(LB_TYPE_INFO_DATA_NAME), t, EntityState_Resolved);
  2544. lb_add_entity(m, lb_global_type_info_data_entity, value);
  2545. }
  2546. { // Type info member buffer
  2547. // NOTE(bill): Removes need for heap allocation by making it global memory
  2548. isize count = 0;
  2549. isize offsets_extra = 0;
  2550. for (auto const &tt : m->info->type_info_types_hash_map) {
  2551. Type *t = tt.type;
  2552. if (t == nullptr) {
  2553. continue;
  2554. }
  2555. isize index = lb_type_info_index(m->info, t, false);
  2556. if (index < 0) {
  2557. continue;
  2558. }
  2559. switch (t->kind) {
  2560. case Type_Union:
  2561. count += t->Union.variants.count;
  2562. break;
  2563. case Type_Struct:
  2564. count += t->Struct.fields.count;
  2565. break;
  2566. case Type_Tuple:
  2567. count += t->Tuple.variables.count;
  2568. break;
  2569. case Type_BitField:
  2570. count += t->BitField.fields.count;
  2571. // Twice is needed for the bit_offsets
  2572. offsets_extra += t->BitField.fields.count;
  2573. break;
  2574. }
  2575. }
  2576. auto const global_type_info_make = [](lbModule *m, char const *name, Type *elem_type, i64 count) -> lbAddr {
  2577. Type *t = alloc_type_array(elem_type, count);
  2578. LLVMValueRef g = LLVMAddGlobal(m->mod, lb_type(m, t), name);
  2579. LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t)));
  2580. LLVMSetLinkage(g, LLVMInternalLinkage);
  2581. lb_make_global_private_const(g);
  2582. lb_set_odin_rtti_section(g);
  2583. return lb_addr({g, alloc_type_pointer(t)});
  2584. };
  2585. lb_global_type_info_member_types = global_type_info_make(m, LB_TYPE_INFO_TYPES_NAME, t_type_info_ptr, count);
  2586. lb_global_type_info_member_names = global_type_info_make(m, LB_TYPE_INFO_NAMES_NAME, t_string, count);
  2587. lb_global_type_info_member_offsets = global_type_info_make(m, LB_TYPE_INFO_OFFSETS_NAME, t_uintptr, count+offsets_extra);
  2588. lb_global_type_info_member_usings = global_type_info_make(m, LB_TYPE_INFO_USINGS_NAME, t_bool, count);
  2589. lb_global_type_info_member_tags = global_type_info_make(m, LB_TYPE_INFO_TAGS_NAME, t_string, count);
  2590. }
  2591. }
  2592. isize global_variable_max_count = 0;
  2593. bool already_has_entry_point = false;
  2594. for (Entity *e : info->entities) {
  2595. String name = e->token.string;
  2596. if (e->kind == Entity_Variable) {
  2597. global_variable_max_count++;
  2598. } else if (e->kind == Entity_Procedure) {
  2599. if ((e->scope->flags&ScopeFlag_Init) && name == "main") {
  2600. GB_ASSERT(e == info->entry_point);
  2601. }
  2602. if (build_context.command_kind == Command_test &&
  2603. (e->Procedure.is_export || e->Procedure.link_name.len > 0)) {
  2604. String link_name = e->Procedure.link_name;
  2605. if (e->pkg->kind == Package_Runtime) {
  2606. if (link_name == "main" ||
  2607. link_name == "_main" ||
  2608. link_name == "DllMain" ||
  2609. link_name == "WinMain" ||
  2610. link_name == "wWinMain" ||
  2611. link_name == "mainCRTStartup" ||
  2612. link_name == "_start") {
  2613. already_has_entry_point = true;
  2614. }
  2615. }
  2616. }
  2617. }
  2618. }
  2619. auto global_variables = array_make<lbGlobalVariable>(permanent_allocator(), 0, global_variable_max_count);
  2620. for (DeclInfo *d : info->variable_init_order) {
  2621. Entity *e = d->entity;
  2622. if ((e->scope->flags & ScopeFlag_File) == 0) {
  2623. continue;
  2624. }
  2625. if (e->min_dep_count.load(std::memory_order_relaxed) == 0) {
  2626. continue;
  2627. }
  2628. // if (!ptr_set_exists(min_dep_set, e)) {
  2629. // continue;
  2630. // }
  2631. DeclInfo *decl = decl_info_of_entity(e);
  2632. if (decl == nullptr) {
  2633. continue;
  2634. }
  2635. GB_ASSERT(e->kind == Entity_Variable);
  2636. bool is_foreign = e->Variable.is_foreign;
  2637. bool is_export = e->Variable.is_export;
  2638. lbModule *m = &gen->default_module;
  2639. String name = lb_get_entity_name(m, e);
  2640. lbGlobalVariable var = {};
  2641. var.decl = decl;
  2642. lbValue g = {};
  2643. g.type = alloc_type_pointer(e->type);
  2644. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2645. if (decl->init_expr != nullptr) {
  2646. TypeAndValue tav = type_and_value_of_expr(decl->init_expr);
  2647. if (!is_type_any(e->type)) {
  2648. if (tav.mode != Addressing_Invalid) {
  2649. if (tav.value.kind != ExactValue_Invalid) {
  2650. auto cc = LB_CONST_CONTEXT_DEFAULT;
  2651. cc.is_rodata = e->kind == Entity_Variable && e->Variable.is_rodata;
  2652. cc.allow_local = false;
  2653. cc.link_section = e->Variable.link_section;
  2654. ExactValue v = tav.value;
  2655. lbValue init = lb_const_value(m, tav.type, v, cc);
  2656. LLVMDeleteGlobal(g.value);
  2657. g.value = nullptr;
  2658. g.value = LLVMAddGlobal(m->mod, LLVMTypeOf(init.value), alloc_cstring(permanent_allocator(), name));
  2659. if (e->token.string == "node_camera_info") {
  2660. gb_printf_err("HERE!\n");
  2661. gb_printf_err("%s\n", LLVMPrintValueToString(init.value));
  2662. }
  2663. LLVMSetInitializer(g.value, init.value);
  2664. var.is_initialized = true;
  2665. if (cc.is_rodata) {
  2666. LLVMSetGlobalConstant(g.value, true);
  2667. }
  2668. }
  2669. }
  2670. }
  2671. if (!var.is_initialized && is_type_untyped_nil(tav.type)) {
  2672. var.is_initialized = true;
  2673. if (e->kind == Entity_Variable && e->Variable.is_rodata) {
  2674. LLVMSetGlobalConstant(g.value, true);
  2675. }
  2676. }
  2677. } else if (e->kind == Entity_Variable && e->Variable.is_rodata) {
  2678. LLVMSetGlobalConstant(g.value, true);
  2679. }
  2680. lb_apply_thread_local_model(g.value, e->Variable.thread_local_model);
  2681. if (is_foreign) {
  2682. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2683. LLVMSetDLLStorageClass(g.value, LLVMDLLImportStorageClass);
  2684. LLVMSetExternallyInitialized(g.value, true);
  2685. lb_add_foreign_library_path(m, e->Variable.foreign_library);
  2686. } else if (LLVMGetInitializer(g.value) == nullptr) {
  2687. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type)));
  2688. }
  2689. if (is_export) {
  2690. LLVMSetLinkage(g.value, LLVMDLLExportLinkage);
  2691. LLVMSetDLLStorageClass(g.value, LLVMDLLExportStorageClass);
  2692. } else if (!is_foreign) {
  2693. LLVMSetLinkage(g.value, USE_SEPARATE_MODULES ? LLVMWeakAnyLinkage : LLVMInternalLinkage);
  2694. }
  2695. lb_set_linkage_from_entity_flags(m, g.value, e->flags);
  2696. LLVMSetAlignment(g.value, cast(u32)type_align_of(e->type));
  2697. if (e->Variable.link_section.len > 0) {
  2698. LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section));
  2699. }
  2700. if (e->flags & EntityFlag_Require) {
  2701. lb_append_to_compiler_used(m, g.value);
  2702. }
  2703. if (m->debug_builder) {
  2704. String global_name = e->token.string;
  2705. if (global_name.len != 0 && global_name != "_") {
  2706. LLVMMetadataRef llvm_file = lb_get_llvm_metadata(m, e->file);
  2707. LLVMMetadataRef llvm_scope = llvm_file;
  2708. LLVMBool local_to_unit = LLVMGetLinkage(g.value) == LLVMInternalLinkage;
  2709. LLVMMetadataRef llvm_expr = LLVMDIBuilderCreateExpression(m->debug_builder, nullptr, 0);
  2710. LLVMMetadataRef llvm_decl = nullptr;
  2711. u32 align_in_bits = cast(u32)(8*type_align_of(e->type));
  2712. LLVMMetadataRef global_variable_metadata = LLVMDIBuilderCreateGlobalVariableExpression(
  2713. m->debug_builder, llvm_scope,
  2714. cast(char const *)global_name.text, global_name.len,
  2715. "", 0, // linkage
  2716. llvm_file, e->token.pos.line,
  2717. lb_debug_type(m, e->type),
  2718. local_to_unit,
  2719. llvm_expr,
  2720. llvm_decl,
  2721. align_in_bits
  2722. );
  2723. lb_set_llvm_metadata(m, g.value, global_variable_metadata);
  2724. LLVMGlobalSetMetadata(g.value, 0, global_variable_metadata);
  2725. }
  2726. }
  2727. g.value = LLVMConstPointerCast(g.value, lb_type(m, alloc_type_pointer(e->type)));
  2728. var.var = g;
  2729. array_add(&global_variables, var);
  2730. lb_add_entity(m, e, g);
  2731. lb_add_member(m, name, g);
  2732. }
  2733. if (build_context.ODIN_DEBUG) {
  2734. // Custom `.raddbg` section for its debugger
  2735. if (build_context.metrics.os == TargetOs_windows) {
  2736. lbModule *m = default_module;
  2737. LLVMModuleRef mod = m->mod;
  2738. LLVMContextRef ctx = m->ctx;
  2739. {
  2740. LLVMTypeRef type = LLVMArrayType(LLVMInt8TypeInContext(ctx), 1);
  2741. LLVMValueRef global = LLVMAddGlobal(mod, type, "raddbg_is_attached_byte_marker");
  2742. LLVMSetInitializer(global, LLVMConstNull(type));
  2743. LLVMSetSection(global, ".raddbg");
  2744. }
  2745. if (gen->info->entry_point) {
  2746. String mangled_name = lb_get_entity_name(m, gen->info->entry_point);
  2747. char const *str = alloc_cstring(temporary_allocator(), mangled_name);
  2748. lb_add_raddbg_string(m, "entry_point: \"", str, "\"");
  2749. }
  2750. }
  2751. }
  2752. TIME_SECTION("LLVM Runtime Objective-C Names Creation");
  2753. gen->objc_names = lb_create_objc_names(default_module);
  2754. TIME_SECTION("LLVM Runtime Startup Creation (Global Variables & @(init))");
  2755. gen->startup_runtime = lb_create_startup_runtime(default_module, gen->objc_names, global_variables);
  2756. TIME_SECTION("LLVM Runtime Cleanup Creation & @(fini)");
  2757. gen->cleanup_runtime = lb_create_cleanup_runtime(default_module);
  2758. if (build_context.ODIN_DEBUG) {
  2759. for (auto const &entry : builtin_pkg->scope->elements) {
  2760. Entity *e = entry.value;
  2761. lb_add_debug_info_for_global_constant_from_entity(gen, e);
  2762. }
  2763. }
  2764. if (gen->modules.count <= 1) {
  2765. do_threading = false;
  2766. }
  2767. TIME_SECTION("LLVM Global Procedures and Types");
  2768. lb_create_global_procedures_and_types(gen, info, do_threading);
  2769. TIME_SECTION("LLVM Procedure Generation");
  2770. lb_generate_procedures(gen, do_threading);
  2771. if (build_context.command_kind == Command_test && !already_has_entry_point) {
  2772. TIME_SECTION("LLVM main");
  2773. lb_create_main_procedure(default_module, gen->startup_runtime, gen->cleanup_runtime);
  2774. }
  2775. TIME_SECTION("LLVM Procedure Generation (missing)");
  2776. lb_generate_missing_procedures(gen, do_threading);
  2777. if (gen->objc_names) {
  2778. TIME_SECTION("Finalize objc names");
  2779. lb_finalize_objc_names(gen, gen->objc_names);
  2780. }
  2781. if (build_context.ODIN_DEBUG) {
  2782. TIME_SECTION("LLVM Debug Info Complete Types and Finalize");
  2783. lb_debug_info_complete_types_and_finalize(gen);
  2784. // Custom `.raddbg` section for its debugger
  2785. if (build_context.metrics.os == TargetOs_windows) {
  2786. lbModule *m = default_module;
  2787. LLVMModuleRef mod = m->mod;
  2788. LLVMContextRef ctx = m->ctx;
  2789. lb_add_raddbg_string(m, "type_view: {type: \"[]?\", expr: \"array(data, len)\"}");
  2790. lb_add_raddbg_string(m, "type_view: {type: \"string\", expr: \"array(data, len)\"}");
  2791. lb_add_raddbg_string(m, "type_view: {type: \"[dynamic]?\", expr: \"rows($, array(data, len), len, cap, allocator)\"}");
  2792. // column major matrices
  2793. lb_add_raddbg_string(m, "type_view: {type: \"matrix[1, ?]?\", expr: \"columns($.data, $[0])\"}");
  2794. lb_add_raddbg_string(m, "type_view: {type: \"matrix[2, ?]?\", expr: \"columns($.data, $[0], $[1])\"}");
  2795. lb_add_raddbg_string(m, "type_view: {type: \"matrix[3, ?]?\", expr: \"columns($.data, $[0], $[1], $[2])\"}");
  2796. lb_add_raddbg_string(m, "type_view: {type: \"matrix[4, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3])\"}");
  2797. lb_add_raddbg_string(m, "type_view: {type: \"matrix[5, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4])\"}");
  2798. lb_add_raddbg_string(m, "type_view: {type: \"matrix[6, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5])\"}");
  2799. lb_add_raddbg_string(m, "type_view: {type: \"matrix[7, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6])\"}");
  2800. lb_add_raddbg_string(m, "type_view: {type: \"matrix[8, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7])\"}");
  2801. lb_add_raddbg_string(m, "type_view: {type: \"matrix[9, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8])\"}");
  2802. lb_add_raddbg_string(m, "type_view: {type: \"matrix[10, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9])\"}");
  2803. lb_add_raddbg_string(m, "type_view: {type: \"matrix[11, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10])\"}");
  2804. lb_add_raddbg_string(m, "type_view: {type: \"matrix[12, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11])\"}");
  2805. lb_add_raddbg_string(m, "type_view: {type: \"matrix[13, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12])\"}");
  2806. lb_add_raddbg_string(m, "type_view: {type: \"matrix[14, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13])\"}");
  2807. lb_add_raddbg_string(m, "type_view: {type: \"matrix[15, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13], $[14])\"}");
  2808. lb_add_raddbg_string(m, "type_view: {type: \"matrix[16, ?]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13], $[14], $[15])\"}");
  2809. // row major matrices
  2810. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 1]?\", expr: \"columns($.data, $[0])\"}");
  2811. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 2]?\", expr: \"columns($.data, $[0], $[1])\"}");
  2812. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 3]?\", expr: \"columns($.data, $[0], $[1], $[2])\"}");
  2813. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 4]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3])\"}");
  2814. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 5]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4])\"}");
  2815. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 6]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5])\"}");
  2816. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 7]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6])\"}");
  2817. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 8]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7])\"}");
  2818. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 9]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8])\"}");
  2819. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 10]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9])\"}");
  2820. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 11]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10])\"}");
  2821. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 12]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11])\"}");
  2822. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 13]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12])\"}");
  2823. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 14]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13])\"}");
  2824. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 15]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13], $[14])\"}");
  2825. lb_add_raddbg_string(m, "type_view: {type: \"#row_major matrix[?, 16]?\", expr: \"columns($.data, $[0], $[1], $[2], $[3], $[4], $[5], $[6], $[7], $[8], $[9], $[10], $[11], $[12], $[13], $[14], $[15])\"}");
  2826. TEMPORARY_ALLOCATOR_GUARD();
  2827. for (RaddbgTypeView const &type_view : gen->info->raddbg_type_views) {
  2828. if (type_view.type == nullptr) {
  2829. continue;
  2830. }
  2831. if (type_view.view.len == 0) {
  2832. continue;
  2833. }
  2834. String t_str = type_to_canonical_string(temporary_allocator(), type_view.type);
  2835. gbString s = gb_string_make(temporary_allocator(), "");
  2836. s = gb_string_appendc(s, "type_view: {type: \"");
  2837. s = gb_string_append_length(s, t_str.text, t_str.len);
  2838. s = gb_string_appendc(s, "\", expr: \"");
  2839. s = gb_string_append_length(s, type_view.view.text, type_view.view.len);
  2840. s = gb_string_appendc(s, "\"}");
  2841. lb_add_raddbg_string(m, s);
  2842. }
  2843. TEMPORARY_ALLOCATOR_GUARD();
  2844. u32 global_name_index = 0;
  2845. for (String str = {}; mpsc_dequeue(&gen->raddebug_section_strings, &str); /**/) {
  2846. LLVMValueRef data = LLVMConstStringInContext(ctx, cast(char const *)str.text, cast(unsigned)str.len, false);
  2847. LLVMTypeRef type = LLVMTypeOf(data);
  2848. gbString global_name = gb_string_make(temporary_allocator(), "raddbg_data__");
  2849. global_name = gb_string_append_fmt(global_name, "%u", global_name_index);
  2850. global_name_index += 1;
  2851. LLVMValueRef global = LLVMAddGlobal(mod, type, global_name);
  2852. LLVMSetInitializer(global, data);
  2853. LLVMSetAlignment(global, 1);
  2854. LLVMSetSection(global, ".raddbg");
  2855. }
  2856. }
  2857. }
  2858. if (do_threading) {
  2859. isize non_empty_module_count = 0;
  2860. for (auto const &entry : gen->modules) {
  2861. lbModule *m = entry.value;
  2862. if (!lb_is_module_empty(m)) {
  2863. non_empty_module_count += 1;
  2864. }
  2865. }
  2866. if (non_empty_module_count <= 1) {
  2867. do_threading = false;
  2868. }
  2869. }
  2870. TIME_SECTION("LLVM Add Foreign Library Paths");
  2871. lb_add_foreign_library_paths(gen);
  2872. TIME_SECTION("LLVM Function Pass");
  2873. lb_llvm_function_passes(gen, do_threading && !build_context.ODIN_DEBUG);
  2874. TIME_SECTION("LLVM Remove Unused Functions and Globals");
  2875. lb_remove_unused_functions_and_globals(gen);
  2876. TIME_SECTION("LLVM Module Pass and Verification");
  2877. lb_llvm_module_passes_and_verification(gen, do_threading);
  2878. TIME_SECTION("LLVM Correct Entity Linkage");
  2879. lb_correct_entity_linkage(gen);
  2880. llvm_error = nullptr;
  2881. defer (LLVMDisposeMessage(llvm_error));
  2882. if (build_context.keep_temp_files ||
  2883. build_context.build_mode == BuildMode_LLVM_IR) {
  2884. TIME_SECTION("LLVM Print Module to File");
  2885. for (auto const &entry : gen->modules) {
  2886. lbModule *m = entry.value;
  2887. if (lb_is_module_empty(m)) {
  2888. continue;
  2889. }
  2890. String filepath_ll = lb_filepath_ll_for_module(m);
  2891. if (LLVMPrintModuleToFile(m->mod, cast(char const *)filepath_ll.text, &llvm_error)) {
  2892. gb_printf_err("LLVM Error: %s\n", llvm_error);
  2893. exit_with_errors();
  2894. return false;
  2895. }
  2896. array_add(&gen->output_temp_paths, filepath_ll);
  2897. }
  2898. if (build_context.build_mode == BuildMode_LLVM_IR) {
  2899. return true;
  2900. }
  2901. }
  2902. ////////////////////////////////////////////
  2903. for (auto const &entry: gen->modules) {
  2904. lbModule *m = entry.value;
  2905. if (!lb_is_module_empty(m)) {
  2906. gen->used_module_count += 1;
  2907. }
  2908. }
  2909. gbString label_object_generation = gb_string_make(heap_allocator(), "LLVM Object Generation");
  2910. if (gen->used_module_count > 1) {
  2911. label_object_generation = gb_string_append_fmt(label_object_generation, " (%td used modules)", gen->used_module_count);
  2912. }
  2913. TIME_SECTION_WITH_LEN(label_object_generation, gb_string_length(label_object_generation));
  2914. if (build_context.ignore_llvm_build) {
  2915. gb_printf_err("LLVM object generation has been ignored!\n");
  2916. return false;
  2917. }
  2918. if (!lb_llvm_object_generation(gen, do_threading)) {
  2919. return false;
  2920. }
  2921. if (build_context.sanitizer_flags & SanitizerFlag_Address) {
  2922. switch (build_context.metrics.os) {
  2923. case TargetOs_windows: {
  2924. auto paths = array_make<String>(heap_allocator(), 0, 1);
  2925. String path = concatenate_strings(permanent_allocator(), build_context.ODIN_ROOT, str_lit("\\bin\\llvm\\windows\\clang_rt.asan-x86_64.lib"));
  2926. array_add(&paths, path);
  2927. Entity *lib = alloc_entity_library_name(nullptr, make_token_ident("asan_lib"), nullptr, slice_from_array(paths), str_lit("asan_lib"));
  2928. array_add(&gen->foreign_libraries, lib);
  2929. } break;
  2930. case TargetOs_darwin:
  2931. case TargetOs_linux:
  2932. case TargetOs_freebsd:
  2933. if (!build_context.extra_linker_flags.text) {
  2934. build_context.extra_linker_flags = str_lit("-fsanitize=address");
  2935. } else {
  2936. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=address"));
  2937. }
  2938. break;
  2939. }
  2940. }
  2941. if (build_context.sanitizer_flags & SanitizerFlag_Memory) {
  2942. switch (build_context.metrics.os) {
  2943. case TargetOs_linux:
  2944. case TargetOs_freebsd:
  2945. if (!build_context.extra_linker_flags.text) {
  2946. build_context.extra_linker_flags = str_lit("-fsanitize=memory");
  2947. } else {
  2948. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=memory"));
  2949. }
  2950. break;
  2951. }
  2952. }
  2953. if (build_context.sanitizer_flags & SanitizerFlag_Thread) {
  2954. switch (build_context.metrics.os) {
  2955. case TargetOs_darwin:
  2956. case TargetOs_linux:
  2957. case TargetOs_freebsd:
  2958. if (!build_context.extra_linker_flags.text) {
  2959. build_context.extra_linker_flags = str_lit("-fsanitize=thread");
  2960. } else {
  2961. build_context.extra_linker_flags = concatenate_strings(permanent_allocator(), build_context.extra_linker_flags, str_lit(" -fsanitize=thread"));
  2962. }
  2963. break;
  2964. }
  2965. }
  2966. array_sort(gen->foreign_libraries, foreign_library_cmp);
  2967. return true;
  2968. }