llvm_backend_general.cpp 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067
  1. gb_internal void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token);
  2. gb_internal LLVMValueRef llvm_const_string_internal(lbModule *m, Type *t, LLVMValueRef data, LLVMValueRef len);
  3. gb_global Entity *lb_global_type_info_data_entity = {};
  4. gb_global lbAddr lb_global_type_info_member_types = {};
  5. gb_global lbAddr lb_global_type_info_member_names = {};
  6. gb_global lbAddr lb_global_type_info_member_offsets = {};
  7. gb_global lbAddr lb_global_type_info_member_usings = {};
  8. gb_global lbAddr lb_global_type_info_member_tags = {};
  9. gb_global isize lb_global_type_info_data_index = 0;
  10. gb_global isize lb_global_type_info_member_types_index = 0;
  11. gb_global isize lb_global_type_info_member_names_index = 0;
  12. gb_global isize lb_global_type_info_member_offsets_index = 0;
  13. gb_global isize lb_global_type_info_member_usings_index = 0;
  14. gb_global isize lb_global_type_info_member_tags_index = 0;
  15. gb_internal void lb_init_module(lbModule *m, Checker *c) {
  16. m->info = &c->info;
  17. gbString module_name = gb_string_make(heap_allocator(), "odin_package");
  18. if (m->file) {
  19. module_name = gb_string_append_fmt(module_name, "-%u", m->file->id+1);
  20. } else if (m->pkg) {
  21. module_name = gb_string_appendc(module_name, "-");
  22. module_name = gb_string_append_length(module_name, m->pkg->name.text, m->pkg->name.len);
  23. } else if (USE_SEPARATE_MODULES) {
  24. module_name = gb_string_appendc(module_name, "-builtin");
  25. }
  26. m->module_name = module_name ? module_name : "odin_package";
  27. m->ctx = LLVMContextCreate();
  28. m->mod = LLVMModuleCreateWithNameInContext(m->module_name, m->ctx);
  29. // m->debug_builder = nullptr;
  30. if (build_context.ODIN_DEBUG) {
  31. enum {DEBUG_METADATA_VERSION = 3};
  32. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  33. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  34. switch (build_context.metrics.os) {
  35. case TargetOs_windows:
  36. LLVMAddModuleFlag(m->mod,
  37. LLVMModuleFlagBehaviorWarning,
  38. "CodeView", 8,
  39. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  40. break;
  41. case TargetOs_darwin:
  42. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  43. LLVMAddModuleFlag(m->mod,
  44. LLVMModuleFlagBehaviorWarning,
  45. "Dwarf Version", 13,
  46. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  47. break;
  48. }
  49. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  50. }
  51. gbAllocator a = heap_allocator();
  52. map_init(&m->types);
  53. map_init(&m->func_raw_types);
  54. map_init(&m->struct_field_remapping);
  55. map_init(&m->values);
  56. map_init(&m->soa_values);
  57. string_map_init(&m->members);
  58. string_map_init(&m->procedures);
  59. string_map_init(&m->const_strings);
  60. map_init(&m->function_type_map);
  61. string_map_init(&m->gen_procs);
  62. if (USE_SEPARATE_MODULES) {
  63. array_init(&m->procedures_to_generate, a, 0, 1<<10);
  64. map_init(&m->procedure_values, 1<<11);
  65. } else {
  66. array_init(&m->procedures_to_generate, a, 0, c->info.all_procedures.count);
  67. map_init(&m->procedure_values, c->info.all_procedures.count*2);
  68. }
  69. array_init(&m->global_procedures_to_create, a, 0, 1024);
  70. array_init(&m->global_types_to_create, a, 0, 1024);
  71. array_init(&m->missing_procedures_to_check, a, 0, 16);
  72. map_init(&m->debug_values);
  73. string_map_init(&m->objc_classes);
  74. string_map_init(&m->objc_selectors);
  75. map_init(&m->map_info_map, 0);
  76. map_init(&m->map_cell_info_map, 0);
  77. map_init(&m->exact_value_compound_literal_addr_map, 1024);
  78. array_init(&m->pad_types, heap_allocator());
  79. m->const_dummy_builder = LLVMCreateBuilderInContext(m->ctx);
  80. }
  81. gb_internal bool lb_init_generator(lbGenerator *gen, Checker *c) {
  82. if (global_error_collector.count != 0) {
  83. return false;
  84. }
  85. isize tc = c->parser->total_token_count;
  86. if (tc < 2) {
  87. return false;
  88. }
  89. String init_fullpath = c->parser->init_fullpath;
  90. linker_data_init(gen, &c->info, init_fullpath);
  91. #if defined(GB_SYSTEM_OSX) && (LLVM_VERSION_MAJOR < 14)
  92. linker_enable_system_library_linking(gen);
  93. #endif
  94. gen->info = &c->info;
  95. map_init(&gen->modules, gen->info->packages.count*2);
  96. map_init(&gen->modules_through_ctx, gen->info->packages.count*2);
  97. map_init(&gen->anonymous_proc_lits, 1024);
  98. if (USE_SEPARATE_MODULES) {
  99. bool module_per_file = build_context.module_per_file && build_context.optimization_level <= 0;
  100. for (auto const &entry : gen->info->packages) {
  101. AstPackage *pkg = entry.value;
  102. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  103. m->pkg = pkg;
  104. m->gen = gen;
  105. map_set(&gen->modules, cast(void *)pkg, m);
  106. lb_init_module(m, c);
  107. if (!module_per_file) {
  108. continue;
  109. }
  110. // NOTE(bill): Probably per file is not a good idea, so leave this for later
  111. for (AstFile *file : pkg->files) {
  112. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  113. m->file = file;
  114. m->pkg = pkg;
  115. m->gen = gen;
  116. map_set(&gen->modules, cast(void *)file, m);
  117. lb_init_module(m, c);
  118. }
  119. }
  120. }
  121. gen->default_module.gen = gen;
  122. map_set(&gen->modules, cast(void *)1, &gen->default_module);
  123. lb_init_module(&gen->default_module, c);
  124. for (auto const &entry : gen->modules) {
  125. lbModule *m = entry.value;
  126. LLVMContextRef ctx = LLVMGetModuleContext(m->mod);
  127. map_set(&gen->modules_through_ctx, ctx, m);
  128. }
  129. mpsc_init(&gen->entities_to_correct_linkage, heap_allocator());
  130. return true;
  131. }
  132. gb_internal lbValue lb_global_type_info_data_ptr(lbModule *m) {
  133. lbValue v = lb_find_value_from_entity(m, lb_global_type_info_data_entity);
  134. return v;
  135. }
  136. struct lbLoopData {
  137. lbAddr idx_addr;
  138. lbValue idx;
  139. lbBlock *body;
  140. lbBlock *done;
  141. lbBlock *loop;
  142. };
  143. struct lbCompoundLitElemTempData {
  144. Ast * expr;
  145. lbValue value;
  146. i64 elem_index;
  147. i64 elem_length;
  148. lbValue gep;
  149. };
  150. gb_internal lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32) {
  151. lbLoopData data = {};
  152. lbValue max = lb_const_int(p->module, t_int, count);
  153. data.idx_addr = lb_add_local_generated(p, index_type, true);
  154. data.body = lb_create_block(p, "loop.body");
  155. data.done = lb_create_block(p, "loop.done");
  156. data.loop = lb_create_block(p, "loop.loop");
  157. lb_emit_jump(p, data.loop);
  158. lb_start_block(p, data.loop);
  159. data.idx = lb_addr_load(p, data.idx_addr);
  160. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  161. lb_emit_if(p, cond, data.body, data.done);
  162. lb_start_block(p, data.body);
  163. return data;
  164. }
  165. gb_internal void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  166. if (data.idx_addr.addr.value != nullptr) {
  167. lb_emit_increment(p, data.idx_addr.addr);
  168. lb_emit_jump(p, data.loop);
  169. lb_start_block(p, data.done);
  170. }
  171. }
  172. gb_internal void lb_make_global_private_const(LLVMValueRef global_data) {
  173. LLVMSetLinkage(global_data, LLVMLinkerPrivateLinkage);
  174. LLVMSetUnnamedAddress(global_data, LLVMGlobalUnnamedAddr);
  175. LLVMSetGlobalConstant(global_data, true);
  176. }
  177. gb_internal void lb_make_global_private_const(lbAddr const &addr) {
  178. lb_make_global_private_const(addr.addr.value);
  179. }
  180. // This emits a GEP at 0, index
  181. gb_internal lbValue lb_emit_epi(lbProcedure *p, lbValue const &value, isize index) {
  182. GB_ASSERT(is_type_pointer(value.type));
  183. Type *type = type_deref(value.type);
  184. LLVMValueRef indices[2] = {
  185. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  186. LLVMConstInt(lb_type(p->module, t_int), cast(unsigned long long)index, false),
  187. };
  188. LLVMTypeRef llvm_type = lb_type(p->module, type);
  189. lbValue res = {};
  190. Type *ptr = base_array_type(type);
  191. res.type = alloc_type_pointer(ptr);
  192. if (LLVMIsConstant(value.value)) {
  193. res.value = LLVMConstGEP2(llvm_type, value.value, indices, gb_count_of(indices));
  194. } else {
  195. res.value = LLVMBuildGEP2(p->builder, llvm_type, value.value, indices, gb_count_of(indices), "");
  196. }
  197. return res;
  198. }
  199. // This emits a GEP at 0, index
  200. gb_internal lbValue lb_emit_epi(lbModule *m, lbValue const &value, isize index) {
  201. GB_ASSERT(is_type_pointer(value.type));
  202. GB_ASSERT(LLVMIsConstant(value.value));
  203. Type *type = type_deref(value.type);
  204. LLVMValueRef indices[2] = {
  205. LLVMConstInt(lb_type(m, t_int), 0, false),
  206. LLVMConstInt(lb_type(m, t_int), cast(unsigned long long)index, false),
  207. };
  208. lbValue res = {};
  209. Type *ptr = base_array_type(type);
  210. res.type = alloc_type_pointer(ptr);
  211. res.value = LLVMConstGEP2(lb_type(m, type), value.value, indices, gb_count_of(indices));
  212. return res;
  213. }
  214. gb_internal LLVMValueRef llvm_zero(lbModule *m) {
  215. return LLVMConstInt(lb_type(m, t_int), 0, false);
  216. }
  217. gb_internal LLVMValueRef llvm_alloca(lbProcedure *p, LLVMTypeRef llvm_type, isize alignment, char const *name) {
  218. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  219. LLVMValueRef val = LLVMBuildAlloca(p->builder, llvm_type, name);
  220. LLVMSetAlignment(val, cast(unsigned int)alignment);
  221. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  222. return val;
  223. }
  224. gb_internal lbValue lb_zero(lbModule *m, Type *t) {
  225. lbValue v = {};
  226. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  227. v.type = t;
  228. return v;
  229. }
  230. gb_internal LLVMValueRef llvm_const_extract_value(lbModule *m, LLVMValueRef agg, unsigned index) {
  231. LLVMValueRef res = agg;
  232. GB_ASSERT(LLVMIsConstant(res));
  233. res = LLVMBuildExtractValue(m->const_dummy_builder, res, index, "");
  234. GB_ASSERT(LLVMIsConstant(res));
  235. return res;
  236. }
  237. gb_internal LLVMValueRef llvm_const_extract_value(lbModule *m, LLVMValueRef agg, unsigned *indices, isize count) {
  238. // return LLVMConstExtractValue(value, indices, count);
  239. LLVMValueRef res = agg;
  240. GB_ASSERT(LLVMIsConstant(res));
  241. for (isize i = 0; i < count; i++) {
  242. res = LLVMBuildExtractValue(m->const_dummy_builder, res, indices[i], "");
  243. GB_ASSERT(LLVMIsConstant(res));
  244. }
  245. return res;
  246. }
  247. gb_internal LLVMValueRef llvm_const_insert_value(lbModule *m, LLVMValueRef agg, LLVMValueRef val, unsigned index) {
  248. GB_ASSERT(LLVMIsConstant(agg));
  249. GB_ASSERT(LLVMIsConstant(val));
  250. LLVMValueRef extracted_value = val;
  251. LLVMValueRef nested = llvm_const_extract_value(m, agg, index);
  252. GB_ASSERT(LLVMIsConstant(nested));
  253. extracted_value = LLVMBuildInsertValue(m->const_dummy_builder, nested, extracted_value, index, "");
  254. GB_ASSERT(LLVMIsConstant(extracted_value));
  255. return extracted_value;
  256. }
  257. gb_internal LLVMValueRef llvm_const_insert_value(lbModule *m, LLVMValueRef agg, LLVMValueRef val, unsigned *indices, isize count) {
  258. GB_ASSERT(LLVMIsConstant(agg));
  259. GB_ASSERT(LLVMIsConstant(val));
  260. GB_ASSERT(count > 0);
  261. LLVMValueRef extracted_value = val;
  262. for (isize i = count-1; i >= 0; i--) {
  263. LLVMValueRef nested = llvm_const_extract_value(m, agg, indices, i);
  264. GB_ASSERT(LLVMIsConstant(nested));
  265. extracted_value = LLVMBuildInsertValue(m->const_dummy_builder, nested, extracted_value, indices[i], "");
  266. }
  267. GB_ASSERT(LLVMIsConstant(extracted_value));
  268. return extracted_value;
  269. }
  270. gb_internal LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  271. lbValue v = lb_find_or_add_entity_string(m, str);
  272. unsigned indices[1] = {0};
  273. return llvm_const_extract_value(m, v.value, indices, gb_count_of(indices));
  274. }
  275. gb_internal bool lb_is_instr_terminating(LLVMValueRef instr) {
  276. if (instr != nullptr) {
  277. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  278. switch (op) {
  279. case LLVMRet:
  280. case LLVMBr:
  281. case LLVMSwitch:
  282. case LLVMIndirectBr:
  283. case LLVMInvoke:
  284. case LLVMUnreachable:
  285. case LLVMCallBr:
  286. return true;
  287. }
  288. }
  289. return false;
  290. }
  291. gb_internal lbModule *lb_module_of_expr(lbGenerator *gen, Ast *expr) {
  292. GB_ASSERT(expr != nullptr);
  293. lbModule **found = nullptr;
  294. AstFile *file = expr->file();
  295. if (file) {
  296. found = map_get(&gen->modules, cast(void *)file);
  297. if (found) {
  298. return *found;
  299. }
  300. if (file->pkg) {
  301. found = map_get(&gen->modules, cast(void *)file->pkg);
  302. if (found) {
  303. return *found;
  304. }
  305. }
  306. }
  307. return &gen->default_module;
  308. }
  309. gb_internal lbModule *lb_module_of_entity(lbGenerator *gen, Entity *e) {
  310. GB_ASSERT(e != nullptr);
  311. lbModule **found = nullptr;
  312. if (e->kind == Entity_Procedure &&
  313. e->decl_info &&
  314. e->decl_info->code_gen_module) {
  315. return e->decl_info->code_gen_module;
  316. }
  317. if (e->file) {
  318. found = map_get(&gen->modules, cast(void *)e->file);
  319. if (found) {
  320. GB_ASSERT(*found != nullptr);
  321. return *found;
  322. }
  323. }
  324. if (e->pkg) {
  325. found = map_get(&gen->modules, cast(void *)e->pkg);
  326. if (found) {
  327. GB_ASSERT(*found != nullptr);
  328. return *found;
  329. }
  330. }
  331. return &gen->default_module;
  332. }
  333. gb_internal lbAddr lb_addr(lbValue addr) {
  334. lbAddr v = {lbAddr_Default, addr};
  335. return v;
  336. }
  337. gb_internal lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  338. GB_ASSERT(is_type_pointer(addr.type));
  339. Type *mt = type_deref(addr.type);
  340. GB_ASSERT(is_type_map(mt));
  341. lbAddr v = {lbAddr_Map, addr};
  342. v.map.key = map_key;
  343. v.map.type = map_type;
  344. v.map.result = map_result;
  345. return v;
  346. }
  347. gb_internal lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  348. lbAddr v = {lbAddr_SoaVariable, addr};
  349. v.soa.index = index;
  350. v.soa.index_expr = index_expr;
  351. return v;
  352. }
  353. gb_internal lbAddr lb_addr_swizzle(lbValue addr, Type *array_type, u8 swizzle_count, u8 swizzle_indices[4]) {
  354. GB_ASSERT(is_type_array(array_type) || is_type_simd_vector(array_type));
  355. GB_ASSERT(1 < swizzle_count && swizzle_count <= 4);
  356. lbAddr v = {lbAddr_Swizzle, addr};
  357. v.swizzle.type = array_type;
  358. v.swizzle.count = swizzle_count;
  359. gb_memmove(v.swizzle.indices, swizzle_indices, swizzle_count);
  360. return v;
  361. }
  362. gb_internal lbAddr lb_addr_swizzle_large(lbValue addr, Type *array_type, Slice<i32> const &swizzle_indices) {
  363. GB_ASSERT_MSG(is_type_array(array_type), "%s", type_to_string(array_type));
  364. lbAddr v = {lbAddr_SwizzleLarge, addr};
  365. v.swizzle_large.type = array_type;
  366. v.swizzle_large.indices = swizzle_indices;
  367. return v;
  368. }
  369. gb_internal lbAddr lb_addr_bit_field(lbValue addr, Type *type, i64 bit_offset, i64 bit_size) {
  370. GB_ASSERT(is_type_pointer(addr.type));
  371. Type *mt = type_deref(addr.type);
  372. GB_ASSERT_MSG(is_type_bit_field(mt), "%s", type_to_string(mt));
  373. lbAddr v = {lbAddr_BitField, addr};
  374. v.bitfield.type = type;
  375. v.bitfield.bit_offset = bit_offset;
  376. v.bitfield.bit_size = bit_size;
  377. return v;
  378. }
  379. gb_internal Type *lb_addr_type(lbAddr const &addr) {
  380. if (addr.addr.value == nullptr) {
  381. return nullptr;
  382. }
  383. switch (addr.kind) {
  384. case lbAddr_Map:
  385. {
  386. Type *t = base_type(addr.map.type);
  387. GB_ASSERT(is_type_map(t));
  388. return t->Map.value;
  389. }
  390. case lbAddr_Swizzle:
  391. return addr.swizzle.type;
  392. case lbAddr_SwizzleLarge:
  393. return addr.swizzle_large.type;
  394. case lbAddr_Context:
  395. if (addr.ctx.sel.index.count > 0) {
  396. Type *t = t_context;
  397. for_array(i, addr.ctx.sel.index) {
  398. GB_ASSERT(is_type_struct(t));
  399. t = base_type(t)->Struct.fields[addr.ctx.sel.index[i]]->type;
  400. }
  401. return t;
  402. }
  403. break;
  404. }
  405. return type_deref(addr.addr.type);
  406. }
  407. gb_internal lbValue lb_make_soa_pointer(lbProcedure *p, Type *type, lbValue const &addr, lbValue const &index) {
  408. lbAddr v = lb_add_local_generated(p, type, false);
  409. lbValue ptr = lb_emit_struct_ep(p, v.addr, 0);
  410. lbValue idx = lb_emit_struct_ep(p, v.addr, 1);
  411. lb_emit_store(p, ptr, addr);
  412. lb_emit_store(p, idx, lb_emit_conv(p, index, t_int));
  413. return lb_addr_load(p, v);
  414. }
  415. gb_internal lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  416. if (addr.addr.value == nullptr) {
  417. GB_PANIC("Illegal addr -> nullptr");
  418. return {};
  419. }
  420. switch (addr.kind) {
  421. case lbAddr_Map:
  422. return lb_internal_dynamic_map_get_ptr(p, addr.addr, addr.map.key);
  423. case lbAddr_SoaVariable:
  424. {
  425. Type *soa_ptr_type = alloc_type_soa_pointer(lb_addr_type(addr));
  426. return lb_address_from_load_or_generate_local(p, lb_make_soa_pointer(p, soa_ptr_type, addr.addr, addr.soa.index));
  427. // TODO(bill): FIX THIS HACK
  428. // return lb_address_from_load(p, lb_addr_load(p, addr));
  429. }
  430. case lbAddr_Context:
  431. GB_PANIC("lbAddr_Context should be handled elsewhere");
  432. break;
  433. case lbAddr_Swizzle:
  434. case lbAddr_SwizzleLarge:
  435. // TOOD(bill): is this good enough logic?
  436. break;
  437. }
  438. return addr.addr;
  439. }
  440. gb_internal lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  441. lbAddr addr = lb_build_addr(p, expr);
  442. return lb_addr_get_ptr(p, addr);
  443. }
  444. gb_internal void lb_set_file_line_col(lbProcedure *p, Array<lbValue> arr, TokenPos pos) {
  445. String file = get_file_path_string(pos.file_id);
  446. i32 line = pos.line;
  447. i32 col = pos.column;
  448. if (build_context.obfuscate_source_code_locations) {
  449. file = obfuscate_string(file, "F");
  450. line = obfuscate_i32(line);
  451. col = obfuscate_i32(col);
  452. }
  453. arr[0] = lb_find_or_add_entity_string(p->module, file);
  454. arr[1] = lb_const_int(p->module, t_i32, line);
  455. arr[2] = lb_const_int(p->module, t_i32, col);
  456. }
  457. gb_internal void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  458. if (build_context.no_bounds_check) {
  459. return;
  460. }
  461. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  462. return;
  463. }
  464. TEMPORARY_ALLOCATOR_GUARD();
  465. index = lb_emit_conv(p, index, t_int);
  466. len = lb_emit_conv(p, len, t_int);
  467. auto args = array_make<lbValue>(temporary_allocator(), 5);
  468. lb_set_file_line_col(p, args, token.pos);
  469. args[3] = index;
  470. args[4] = len;
  471. lb_emit_runtime_call(p, "bounds_check_error", args);
  472. }
  473. gb_internal void lb_emit_matrix_bounds_check(lbProcedure *p, Token token, lbValue row_index, lbValue column_index, lbValue row_count, lbValue column_count) {
  474. if (build_context.no_bounds_check) {
  475. return;
  476. }
  477. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  478. return;
  479. }
  480. TEMPORARY_ALLOCATOR_GUARD();
  481. row_index = lb_emit_conv(p, row_index, t_int);
  482. column_index = lb_emit_conv(p, column_index, t_int);
  483. row_count = lb_emit_conv(p, row_count, t_int);
  484. column_count = lb_emit_conv(p, column_count, t_int);
  485. auto args = array_make<lbValue>(temporary_allocator(), 7);
  486. lb_set_file_line_col(p, args, token.pos);
  487. args[3] = row_index;
  488. args[4] = column_index;
  489. args[5] = row_count;
  490. args[6] = column_count;
  491. lb_emit_runtime_call(p, "matrix_bounds_check_error", args);
  492. }
  493. gb_internal void lb_emit_multi_pointer_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high) {
  494. if (build_context.no_bounds_check) {
  495. return;
  496. }
  497. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  498. return;
  499. }
  500. low = lb_emit_conv(p, low, t_int);
  501. high = lb_emit_conv(p, high, t_int);
  502. auto args = array_make<lbValue>(permanent_allocator(), 5);
  503. lb_set_file_line_col(p, args, token.pos);
  504. args[3] = low;
  505. args[4] = high;
  506. lb_emit_runtime_call(p, "multi_pointer_slice_expr_error", args);
  507. }
  508. gb_internal void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  509. if (build_context.no_bounds_check) {
  510. return;
  511. }
  512. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  513. return;
  514. }
  515. high = lb_emit_conv(p, high, t_int);
  516. if (!lower_value_used) {
  517. auto args = array_make<lbValue>(permanent_allocator(), 5);
  518. lb_set_file_line_col(p, args, token.pos);
  519. args[3] = high;
  520. args[4] = len;
  521. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  522. } else {
  523. // No need to convert unless used
  524. low = lb_emit_conv(p, low, t_int);
  525. auto args = array_make<lbValue>(permanent_allocator(), 6);
  526. lb_set_file_line_col(p, args, token.pos);
  527. args[3] = low;
  528. args[4] = high;
  529. args[5] = len;
  530. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  531. }
  532. }
  533. gb_internal unsigned lb_try_get_alignment(LLVMValueRef addr_ptr, unsigned default_alignment) {
  534. if (LLVMIsAGlobalValue(addr_ptr) || LLVMIsAAllocaInst(addr_ptr) || LLVMIsALoadInst(addr_ptr)) {
  535. return LLVMGetAlignment(addr_ptr);
  536. }
  537. return default_alignment;
  538. }
  539. gb_internal bool lb_try_update_alignment(LLVMValueRef addr_ptr, unsigned alignment) {
  540. if (LLVMIsAGlobalValue(addr_ptr) || LLVMIsAAllocaInst(addr_ptr) || LLVMIsALoadInst(addr_ptr)) {
  541. if (LLVMGetAlignment(addr_ptr) < alignment) {
  542. if (LLVMIsAAllocaInst(addr_ptr)) {
  543. LLVMSetAlignment(addr_ptr, alignment);
  544. } else if (LLVMIsAGlobalValue(addr_ptr) && LLVMGetLinkage(addr_ptr) != LLVMExternalLinkage) {
  545. // NOTE(laytan): setting alignment of an external global just changes the alignment we expect it to be.
  546. LLVMSetAlignment(addr_ptr, alignment);
  547. }
  548. }
  549. return LLVMGetAlignment(addr_ptr) >= alignment;
  550. }
  551. return false;
  552. }
  553. gb_internal bool lb_try_update_alignment(lbValue ptr, unsigned alignment) {
  554. return lb_try_update_alignment(ptr.value, alignment);
  555. }
  556. gb_internal bool lb_can_try_to_inline_array_arith(Type *t) {
  557. return type_size_of(t) <= build_context.max_simd_align;
  558. }
  559. gb_internal bool lb_try_vector_cast(lbModule *m, lbValue ptr, LLVMTypeRef *vector_type_) {
  560. Type *array_type = base_type(type_deref(ptr.type));
  561. GB_ASSERT(is_type_array_like(array_type));
  562. i64 count = get_array_type_count(array_type);
  563. Type *elem_type = base_array_type(array_type);
  564. // TODO(bill): Determine what is the correct limit for doing vector arithmetic
  565. if (lb_can_try_to_inline_array_arith(array_type) &&
  566. is_type_valid_vector_elem(elem_type)) {
  567. // Try to treat it like a vector if possible
  568. bool possible = false;
  569. LLVMTypeRef vector_type = LLVMVectorType(lb_type(m, elem_type), cast(unsigned)count);
  570. unsigned vector_alignment = cast(unsigned)lb_alignof(vector_type);
  571. LLVMValueRef addr_ptr = ptr.value;
  572. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  573. possible = lb_try_update_alignment(addr_ptr, vector_alignment);
  574. } else if (LLVMIsALoadInst(addr_ptr)) {
  575. unsigned alignment = LLVMGetAlignment(addr_ptr);
  576. possible = alignment >= vector_alignment;
  577. }
  578. // NOTE: Due to alignment requirements, if the pointer is not correctly aligned
  579. // then it cannot be treated as a vector
  580. if (possible) {
  581. if (vector_type_) *vector_type_ =vector_type;
  582. return true;
  583. }
  584. }
  585. return false;
  586. }
  587. gb_internal LLVMValueRef OdinLLVMBuildLoad(lbProcedure *p, LLVMTypeRef type, LLVMValueRef value) {
  588. LLVMValueRef result = LLVMBuildLoad2(p->builder, type, value, "");
  589. // If it is not an instruction it isn't a GEP, so we don't need to track alignment in the metadata,
  590. // which is not possible anyway (only LLVM instructions can have metadata).
  591. if (LLVMIsAInstruction(value)) {
  592. u64 is_packed = lb_get_metadata_custom_u64(p->module, value, ODIN_METADATA_IS_PACKED);
  593. if (is_packed != 0) {
  594. LLVMSetAlignment(result, 1);
  595. }
  596. u64 align = LLVMGetAlignment(result);
  597. u64 align_min = lb_get_metadata_custom_u64(p->module, value, ODIN_METADATA_MIN_ALIGN);
  598. u64 align_max = lb_get_metadata_custom_u64(p->module, value, ODIN_METADATA_MAX_ALIGN);
  599. if (align_min != 0 && align < align_min) {
  600. align = align_min;
  601. }
  602. if (align_max != 0 && align > align_max) {
  603. align = align_max;
  604. }
  605. GB_ASSERT(align <= UINT_MAX);
  606. LLVMSetAlignment(result, (unsigned int)align);
  607. }
  608. return result;
  609. }
  610. gb_internal LLVMValueRef OdinLLVMBuildLoadAligned(lbProcedure *p, LLVMTypeRef type, LLVMValueRef value, i64 alignment) {
  611. LLVMValueRef result = LLVMBuildLoad2(p->builder, type, value, "");
  612. LLVMSetAlignment(result, cast(unsigned)alignment);
  613. if (LLVMIsAInstruction(value)) {
  614. u64 is_packed = lb_get_metadata_custom_u64(p->module, value, ODIN_METADATA_IS_PACKED);
  615. if (is_packed != 0) {
  616. LLVMSetAlignment(result, 1);
  617. }
  618. }
  619. return result;
  620. }
  621. gb_internal void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  622. if (addr.addr.value == nullptr) {
  623. return;
  624. }
  625. GB_ASSERT(value.type != nullptr);
  626. if (is_type_untyped_uninit(value.type)) {
  627. Type *t = lb_addr_type(addr);
  628. value.type = t;
  629. value.value = LLVMGetUndef(lb_type(p->module, t));
  630. } else if (is_type_untyped_nil(value.type)) {
  631. Type *t = lb_addr_type(addr);
  632. value.type = t;
  633. value.value = LLVMConstNull(lb_type(p->module, t));
  634. }
  635. if (addr.kind == lbAddr_BitField) {
  636. lbValue dst = addr.addr;
  637. if (is_type_endian_big(addr.bitfield.type)) {
  638. i64 shift_amount = 8*type_size_of(value.type) - addr.bitfield.bit_size;
  639. lbValue shifted_value = value;
  640. shifted_value.value = LLVMBuildLShr(p->builder,
  641. shifted_value.value,
  642. LLVMConstInt(LLVMTypeOf(shifted_value.value), shift_amount, false), "");
  643. lbValue src = lb_address_from_load_or_generate_local(p, shifted_value);
  644. auto args = array_make<lbValue>(temporary_allocator(), 4);
  645. args[0] = dst;
  646. args[1] = src;
  647. args[2] = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_offset);
  648. args[3] = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_size);
  649. lb_emit_runtime_call(p, "__write_bits", args);
  650. } else if ((addr.bitfield.bit_offset % 8) == 0 &&
  651. (addr.bitfield.bit_size % 8) == 0) {
  652. lbValue src = lb_address_from_load_or_generate_local(p, value);
  653. lbValue byte_offset = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_offset/8);
  654. lbValue byte_size = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_size/8);
  655. lbValue dst_offset = lb_emit_conv(p, dst, t_u8_ptr);
  656. dst_offset = lb_emit_ptr_offset(p, dst_offset, byte_offset);
  657. lb_mem_copy_non_overlapping(p, dst_offset, src, byte_size);
  658. } else {
  659. lbValue src = lb_address_from_load_or_generate_local(p, value);
  660. auto args = array_make<lbValue>(temporary_allocator(), 4);
  661. args[0] = dst;
  662. args[1] = src;
  663. args[2] = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_offset);
  664. args[3] = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_size);
  665. lb_emit_runtime_call(p, "__write_bits", args);
  666. }
  667. return;
  668. } else if (addr.kind == lbAddr_Map) {
  669. lb_internal_dynamic_map_set(p, addr.addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  670. return;
  671. } else if (addr.kind == lbAddr_Context) {
  672. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  673. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  674. // This has to be done manually since the optimizer cannot determine when this is possible
  675. bool create_new = true;
  676. for_array(i, p->context_stack) {
  677. lbContextData *ctx_data = &p->context_stack[i];
  678. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  679. if (ctx_data->uses > 0) {
  680. create_new = true;
  681. } else if (p->scope_index > ctx_data->scope_index) {
  682. create_new = true;
  683. } else {
  684. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  685. create_new = false;
  686. }
  687. break;
  688. }
  689. }
  690. lbValue next = {};
  691. if (create_new) {
  692. lbValue old = lb_addr_load(p, old_addr);
  693. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  694. lb_addr_store(p, next_addr, old);
  695. lb_push_context_onto_stack(p, next_addr);
  696. next = next_addr.addr;
  697. } else {
  698. next = old_addr.addr;
  699. }
  700. if (addr.ctx.sel.index.count > 0) {
  701. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  702. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  703. lb_emit_store(p, lhs, rhs);
  704. } else {
  705. lbValue lhs = next;
  706. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  707. lb_emit_store(p, lhs, rhs);
  708. }
  709. return;
  710. } else if (addr.kind == lbAddr_SoaVariable) {
  711. Type *t = type_deref(addr.addr.type);
  712. t = base_type(t);
  713. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  714. Type *elem_type = t->Struct.soa_elem;
  715. value = lb_emit_conv(p, value, elem_type);
  716. elem_type = base_type(elem_type);
  717. lbValue index = addr.soa.index;
  718. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  719. Type *t = base_type(type_deref(addr.addr.type));
  720. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  721. lbValue len = lb_soa_struct_len(p, addr.addr);
  722. if (addr.soa.index_expr != nullptr) {
  723. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  724. }
  725. }
  726. isize field_count = 0;
  727. switch (elem_type->kind) {
  728. case Type_Struct:
  729. field_count = elem_type->Struct.fields.count;
  730. break;
  731. case Type_Array:
  732. field_count = cast(isize)elem_type->Array.count;
  733. break;
  734. }
  735. for (isize i = 0; i < field_count; i++) {
  736. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  737. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  738. if (t->Struct.soa_kind == StructSoa_Fixed) {
  739. dst = lb_emit_array_ep(p, dst, index);
  740. lb_emit_store(p, dst, src);
  741. } else {
  742. lbValue field = lb_emit_load(p, dst);
  743. dst = lb_emit_ptr_offset(p, field, index);
  744. lb_emit_store(p, dst, src);
  745. }
  746. }
  747. return;
  748. } else if (addr.kind == lbAddr_Swizzle) {
  749. GB_ASSERT(addr.swizzle.count <= 4);
  750. GB_ASSERT(value.value != nullptr);
  751. value = lb_emit_conv(p, value, lb_addr_type(addr));
  752. lbValue dst = lb_addr_get_ptr(p, addr);
  753. lbValue src = lb_address_from_load_or_generate_local(p, value);
  754. {
  755. lbValue src_ptrs[4] = {};
  756. lbValue src_loads[4] = {};
  757. lbValue dst_ptrs[4] = {};
  758. for (u8 i = 0; i < addr.swizzle.count; i++) {
  759. src_ptrs[i] = lb_emit_array_epi(p, src, i);
  760. }
  761. for (u8 i = 0; i < addr.swizzle.count; i++) {
  762. dst_ptrs[i] = lb_emit_array_epi(p, dst, addr.swizzle.indices[i]);
  763. }
  764. for (u8 i = 0; i < addr.swizzle.count; i++) {
  765. src_loads[i] = lb_emit_load(p, src_ptrs[i]);
  766. }
  767. for (u8 i = 0; i < addr.swizzle.count; i++) {
  768. lb_emit_store(p, dst_ptrs[i], src_loads[i]);
  769. }
  770. }
  771. return;
  772. } else if (addr.kind == lbAddr_SwizzleLarge) {
  773. GB_ASSERT(value.value != nullptr);
  774. value = lb_emit_conv(p, value, lb_addr_type(addr));
  775. lbValue dst = lb_addr_get_ptr(p, addr);
  776. lbValue src = lb_address_from_load_or_generate_local(p, value);
  777. for_array(i, addr.swizzle_large.indices) {
  778. lbValue src_ptr = lb_emit_array_epi(p, src, i);
  779. lbValue dst_ptr = lb_emit_array_epi(p, dst, addr.swizzle_large.indices[i]);
  780. lbValue src_load = lb_emit_load(p, src_ptr);
  781. lb_emit_store(p, dst_ptr, src_load);
  782. }
  783. return;
  784. }
  785. GB_ASSERT(value.value != nullptr);
  786. value = lb_emit_conv(p, value, lb_addr_type(addr));
  787. lb_emit_store(p, addr.addr, value);
  788. }
  789. gb_internal bool lb_is_type_proc_recursive(Type *t) {
  790. for (;;) {
  791. if (t == nullptr) {
  792. return false;
  793. }
  794. switch (t->kind) {
  795. case Type_Named:
  796. t = t->Named.base;
  797. break;
  798. case Type_Pointer:
  799. t = t->Pointer.elem;
  800. break;
  801. case Type_Proc:
  802. return true;
  803. default:
  804. return false;
  805. }
  806. }
  807. }
  808. gb_internal void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  809. GB_ASSERT(value.value != nullptr);
  810. if (LLVMIsUndef(value.value)) {
  811. return;
  812. }
  813. Type *a = type_deref(ptr.type, true);
  814. if (LLVMIsNull(value.value)) {
  815. LLVMTypeRef src_t = llvm_addr_type(p->module, ptr);
  816. if (is_type_proc(a)) {
  817. LLVMTypeRef rawptr_type = lb_type(p->module, t_rawptr);
  818. LLVMTypeRef rawptr_ptr_type = LLVMPointerType(rawptr_type, 0);
  819. LLVMBuildStore(p->builder, LLVMConstNull(rawptr_type), LLVMBuildBitCast(p->builder, ptr.value, rawptr_ptr_type, ""));
  820. } else if (is_type_bit_set(a)) {
  821. lb_mem_zero_ptr(p, ptr.value, a, 1);
  822. } else if (lb_sizeof(src_t) <= lb_max_zero_init_size()) {
  823. LLVMBuildStore(p->builder, LLVMConstNull(src_t), ptr.value);
  824. } else {
  825. lb_mem_zero_ptr(p, ptr.value, a, 1);
  826. }
  827. return;
  828. }
  829. if (is_type_boolean(a)) {
  830. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  831. value = lb_emit_conv(p, value, a);
  832. }
  833. Type *ca = core_type(a);
  834. if (ca->kind == Type_Basic) {
  835. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  836. }
  837. enum {MAX_STORE_SIZE = 64};
  838. if (lb_sizeof(LLVMTypeOf(value.value)) > MAX_STORE_SIZE) {
  839. if (!p->in_multi_assignment && LLVMIsALoadInst(value.value)) {
  840. LLVMValueRef dst_ptr = ptr.value;
  841. LLVMValueRef src_ptr_original = LLVMGetOperand(value.value, 0);
  842. LLVMValueRef src_ptr = LLVMBuildPointerCast(p->builder, src_ptr_original, LLVMTypeOf(dst_ptr), "");
  843. LLVMBuildMemMove(p->builder,
  844. dst_ptr, lb_try_get_alignment(dst_ptr, 1),
  845. src_ptr, lb_try_get_alignment(src_ptr_original, 1),
  846. LLVMConstInt(LLVMInt64TypeInContext(p->module->ctx), lb_sizeof(LLVMTypeOf(value.value)), false));
  847. return;
  848. } else if (LLVMIsConstant(value.value)) {
  849. lbAddr addr = lb_add_global_generated_from_procedure(p, value.type, value);
  850. lb_make_global_private_const(addr);
  851. LLVMValueRef dst_ptr = ptr.value;
  852. LLVMValueRef src_ptr = addr.addr.value;
  853. src_ptr = LLVMBuildPointerCast(p->builder, src_ptr, LLVMTypeOf(dst_ptr), "");
  854. LLVMBuildMemMove(p->builder,
  855. dst_ptr, lb_try_get_alignment(dst_ptr, 1),
  856. src_ptr, lb_try_get_alignment(src_ptr, 1),
  857. LLVMConstInt(LLVMInt64TypeInContext(p->module->ctx), lb_sizeof(LLVMTypeOf(value.value)), false));
  858. return;
  859. }
  860. }
  861. LLVMValueRef instr = nullptr;
  862. if (lb_is_type_proc_recursive(a)) {
  863. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  864. // stored as regular pointer with no procedure information
  865. LLVMTypeRef rawptr_type = lb_type(p->module, t_rawptr);
  866. LLVMTypeRef rawptr_ptr_type = LLVMPointerType(rawptr_type, 0);
  867. instr = LLVMBuildStore(p->builder,
  868. LLVMBuildPointerCast(p->builder, value.value, rawptr_type, ""),
  869. LLVMBuildPointerCast(p->builder, ptr.value, rawptr_ptr_type, ""));
  870. } else {
  871. Type *ca = core_type(a);
  872. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  873. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  874. } else {
  875. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  876. }
  877. instr = LLVMBuildStore(p->builder, value.value, ptr.value);
  878. }
  879. // LLVMSetVolatile(instr, p->in_multi_assignment);
  880. }
  881. gb_internal LLVMTypeRef llvm_addr_type(lbModule *module, lbValue addr_val) {
  882. return lb_type(module, type_deref(addr_val.type));
  883. }
  884. gb_internal lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  885. GB_ASSERT(value.value != nullptr);
  886. if (is_type_multi_pointer(value.type)) {
  887. Type *vt = base_type(value.type);
  888. GB_ASSERT(vt->kind == Type_MultiPointer);
  889. Type *t = vt->MultiPointer.elem;
  890. LLVMValueRef v = OdinLLVMBuildLoad(p, lb_type(p->module, t), value.value);
  891. return lbValue{v, t};
  892. } else if (is_type_soa_pointer(value.type)) {
  893. lbValue ptr = lb_emit_struct_ev(p, value, 0);
  894. lbValue idx = lb_emit_struct_ev(p, value, 1);
  895. lbAddr addr = lb_addr_soa_variable(ptr, idx, nullptr);
  896. return lb_addr_load(p, addr);
  897. }
  898. GB_ASSERT_MSG(is_type_pointer(value.type), "%s", type_to_string(value.type));
  899. Type *t = type_deref(value.type);
  900. LLVMValueRef v = OdinLLVMBuildLoad(p, lb_type(p->module, t), value.value);
  901. return lbValue{v, t};
  902. }
  903. gb_internal lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  904. GB_ASSERT(addr.addr.value != nullptr);
  905. if (addr.kind == lbAddr_BitField) {
  906. Type *ct = core_type(addr.bitfield.type);
  907. bool do_mask = false;
  908. if (is_type_unsigned(ct) || is_type_boolean(ct)) {
  909. // Mask
  910. if (addr.bitfield.bit_size != 8*type_size_of(ct)) {
  911. do_mask = true;
  912. }
  913. }
  914. i64 total_bitfield_bit_size = 8*type_size_of(lb_addr_type(addr));
  915. i64 dst_byte_size = type_size_of(addr.bitfield.type);
  916. lbAddr dst = lb_add_local_generated(p, addr.bitfield.type, true);
  917. lbValue src = addr.addr;
  918. lbValue bit_offset = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_offset);
  919. lbValue bit_size = lb_const_int(p->module, t_uintptr, addr.bitfield.bit_size);
  920. lbValue byte_offset = lb_const_int(p->module, t_uintptr, (addr.bitfield.bit_offset+7)/8);
  921. lbValue byte_size = lb_const_int(p->module, t_uintptr, (addr.bitfield.bit_size+7)/8);
  922. GB_ASSERT(type_size_of(addr.bitfield.type) >= ((addr.bitfield.bit_size+7)/8));
  923. lbValue r = {};
  924. if (is_type_endian_big(addr.bitfield.type)) {
  925. auto args = array_make<lbValue>(temporary_allocator(), 4);
  926. args[0] = dst.addr;
  927. args[1] = src;
  928. args[2] = bit_offset;
  929. args[3] = bit_size;
  930. lb_emit_runtime_call(p, "__read_bits", args);
  931. LLVMValueRef shift_amount = LLVMConstInt(
  932. lb_type(p->module, lb_addr_type(dst)),
  933. 8*dst_byte_size - addr.bitfield.bit_size,
  934. false
  935. );
  936. r = lb_addr_load(p, dst);
  937. r.value = LLVMBuildShl(p->builder, r.value, shift_amount, "");
  938. } else if ((addr.bitfield.bit_offset % 8) == 0) {
  939. do_mask = 8*dst_byte_size != addr.bitfield.bit_size;
  940. lbValue copy_size = byte_size;
  941. lbValue src_offset = lb_emit_conv(p, src, t_u8_ptr);
  942. src_offset = lb_emit_ptr_offset(p, src_offset, byte_offset);
  943. if (addr.bitfield.bit_offset + 8*dst_byte_size <= total_bitfield_bit_size) {
  944. copy_size = lb_const_int(p->module, t_uintptr, dst_byte_size);
  945. }
  946. lb_mem_copy_non_overlapping(p, dst.addr, src_offset, copy_size, false);
  947. r = lb_addr_load(p, dst);
  948. } else {
  949. auto args = array_make<lbValue>(temporary_allocator(), 4);
  950. args[0] = dst.addr;
  951. args[1] = src;
  952. args[2] = bit_offset;
  953. args[3] = bit_size;
  954. lb_emit_runtime_call(p, "__read_bits", args);
  955. r = lb_addr_load(p, dst);
  956. }
  957. Type *t = addr.bitfield.type;
  958. if (do_mask) {
  959. GB_ASSERT(addr.bitfield.bit_size <= 8*type_size_of(ct));
  960. lbValue mask = lb_const_int(p->module, t, (1ull<<cast(u64)addr.bitfield.bit_size)-1);
  961. r = lb_emit_arith(p, Token_And, r, mask, t);
  962. }
  963. if (!is_type_unsigned(ct) && !is_type_boolean(ct)) {
  964. // Sign extension
  965. // m := 1<<(bit_size-1)
  966. // r = (r XOR m) - m
  967. lbValue m = lb_const_int(p->module, t, 1ull<<(addr.bitfield.bit_size-1));
  968. r = lb_emit_arith(p, Token_Xor, r, m, t);
  969. r = lb_emit_arith(p, Token_Sub, r, m, t);
  970. }
  971. return r;
  972. } else if (addr.kind == lbAddr_Map) {
  973. Type *map_type = base_type(type_deref(addr.addr.type));
  974. GB_ASSERT(map_type->kind == Type_Map);
  975. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  976. lbValue ptr = lb_internal_dynamic_map_get_ptr(p, addr.addr, addr.map.key);
  977. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  978. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  979. lbBlock *then = lb_create_block(p, "map.get.then");
  980. lbBlock *done = lb_create_block(p, "map.get.done");
  981. lb_emit_if(p, ok, then, done);
  982. lb_start_block(p, then);
  983. {
  984. // TODO(bill): mem copy it instead?
  985. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  986. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  987. lb_emit_store(p, gep0, lb_emit_load(p, value));
  988. }
  989. lb_emit_jump(p, done);
  990. lb_start_block(p, done);
  991. if (is_type_tuple(addr.map.result)) {
  992. return lb_addr_load(p, v);
  993. } else {
  994. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  995. return lb_emit_load(p, single);
  996. }
  997. } else if (addr.kind == lbAddr_Context) {
  998. lbValue a = addr.addr;
  999. for_array(i, p->context_stack) {
  1000. lbContextData *ctx_data = &p->context_stack[i];
  1001. if (ctx_data->ctx.addr.value == a.value) {
  1002. ctx_data->uses += 1;
  1003. break;
  1004. }
  1005. }
  1006. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  1007. if (addr.ctx.sel.index.count > 0) {
  1008. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  1009. return lb_emit_load(p, b);
  1010. } else {
  1011. return lb_emit_load(p, a);
  1012. }
  1013. } else if (addr.kind == lbAddr_SoaVariable) {
  1014. Type *t = type_deref(addr.addr.type);
  1015. t = base_type(t);
  1016. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  1017. Type *elem = t->Struct.soa_elem;
  1018. lbValue len = {};
  1019. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1020. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  1021. } else {
  1022. lbValue v = lb_emit_load(p, addr.addr);
  1023. len = lb_soa_struct_len(p, v);
  1024. }
  1025. lbAddr res = lb_add_local_generated(p, elem, true);
  1026. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  1027. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  1028. }
  1029. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1030. for_array(i, t->Struct.fields) {
  1031. Entity *field = t->Struct.fields[i];
  1032. Type *base_type = field->type;
  1033. GB_ASSERT(base_type->kind == Type_Array);
  1034. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  1035. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  1036. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  1037. lbValue src = lb_emit_load(p, src_ptr);
  1038. lb_emit_store(p, dst, src);
  1039. }
  1040. } else {
  1041. isize field_count = t->Struct.fields.count;
  1042. if (t->Struct.soa_kind == StructSoa_Slice) {
  1043. field_count -= 1;
  1044. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  1045. field_count -= 3;
  1046. }
  1047. for (isize i = 0; i < field_count; i++) {
  1048. Entity *field = t->Struct.fields[i];
  1049. Type *base_type = field->type;
  1050. GB_ASSERT(base_type->kind == Type_MultiPointer);
  1051. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  1052. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  1053. lbValue src = lb_emit_load(p, src_ptr);
  1054. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  1055. src = lb_emit_load(p, src);
  1056. lb_emit_store(p, dst, src);
  1057. }
  1058. }
  1059. return lb_addr_load(p, res);
  1060. } else if (addr.kind == lbAddr_Swizzle) {
  1061. Type *array_type = base_type(addr.swizzle.type);
  1062. if (array_type->kind == Type_SimdVector) {
  1063. lbValue vec = lb_emit_load(p, addr.addr);
  1064. u8 index_count = addr.swizzle.count;
  1065. if (index_count == 0) {
  1066. return vec;
  1067. }
  1068. unsigned mask_len = cast(unsigned)index_count;
  1069. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  1070. for (isize i = 0; i < index_count; i++) {
  1071. mask_elems[i] = LLVMConstInt(lb_type(p->module, t_u32), addr.swizzle.indices[i], false);
  1072. }
  1073. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  1074. LLVMValueRef v1 = vec.value;
  1075. LLVMValueRef v2 = vec.value;
  1076. lbValue res = {};
  1077. res.type = addr.swizzle.type;
  1078. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  1079. return res;
  1080. }
  1081. GB_ASSERT(array_type->kind == Type_Array);
  1082. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle.type);
  1083. static u8 const ordered_indices[4] = {0, 1, 2, 3};
  1084. if (gb_memcompare(ordered_indices, addr.swizzle.indices, addr.swizzle.count) == 0) {
  1085. if (lb_try_update_alignment(addr.addr, res_align)) {
  1086. Type *pt = alloc_type_pointer(addr.swizzle.type);
  1087. lbValue res = {};
  1088. res.value = LLVMBuildPointerCast(p->builder, addr.addr.value, lb_type(p->module, pt), "");
  1089. res.type = pt;
  1090. return lb_emit_load(p, res);
  1091. }
  1092. }
  1093. lbAddr res = lb_add_local_generated(p, addr.swizzle.type, false);
  1094. lbValue ptr = lb_addr_get_ptr(p, res);
  1095. GB_ASSERT(is_type_pointer(ptr.type));
  1096. LLVMTypeRef vector_type = nullptr;
  1097. if (lb_try_vector_cast(p->module, addr.addr, &vector_type)) {
  1098. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, addr.addr.value, LLVMPointerType(vector_type, 0), "");
  1099. LLVMValueRef v = OdinLLVMBuildLoad(p, vector_type, vp);
  1100. LLVMValueRef scalars[4] = {};
  1101. for (u8 i = 0; i < addr.swizzle.count; i++) {
  1102. scalars[i] = LLVMConstInt(lb_type(p->module, t_u32), addr.swizzle.indices[i], false);
  1103. }
  1104. LLVMValueRef mask = LLVMConstVector(scalars, addr.swizzle.count);
  1105. LLVMValueRef sv = llvm_basic_shuffle(p, v, mask);
  1106. LLVMSetAlignment(res.addr.value, cast(unsigned)lb_alignof(LLVMTypeOf(sv)));
  1107. LLVMValueRef dst = LLVMBuildPointerCast(p->builder, ptr.value, LLVMPointerType(LLVMTypeOf(sv), 0), "");
  1108. LLVMBuildStore(p->builder, sv, dst);
  1109. } else {
  1110. for (u8 i = 0; i < addr.swizzle.count; i++) {
  1111. u8 index = addr.swizzle.indices[i];
  1112. lbValue dst = lb_emit_array_epi(p, ptr, i);
  1113. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  1114. lb_emit_store(p, dst, lb_emit_load(p, src));
  1115. }
  1116. }
  1117. return lb_addr_load(p, res);
  1118. } else if (addr.kind == lbAddr_SwizzleLarge) {
  1119. Type *array_type = base_type(addr.swizzle_large.type);
  1120. GB_ASSERT(array_type->kind == Type_Array);
  1121. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle_large.type);
  1122. gb_unused(res_align);
  1123. lbAddr res = lb_add_local_generated(p, addr.swizzle_large.type, false);
  1124. lbValue ptr = lb_addr_get_ptr(p, res);
  1125. GB_ASSERT(is_type_pointer(ptr.type));
  1126. for_array(i, addr.swizzle_large.indices) {
  1127. i32 index = addr.swizzle_large.indices[i];
  1128. lbValue dst = lb_emit_array_epi(p, ptr, i);
  1129. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  1130. lb_emit_store(p, dst, lb_emit_load(p, src));
  1131. }
  1132. return lb_addr_load(p, res);
  1133. }
  1134. if (is_type_proc(addr.addr.type)) {
  1135. return addr.addr;
  1136. }
  1137. return lb_emit_load(p, addr.addr);
  1138. }
  1139. gb_internal lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  1140. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  1141. }
  1142. gb_internal lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  1143. Type *t = u.type;
  1144. GB_ASSERT_MSG(is_type_pointer(t) &&
  1145. is_type_union(type_deref(t)), "%s", type_to_string(t));
  1146. Type *ut = type_deref(t);
  1147. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  1148. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  1149. GB_ASSERT(type_size_of(ut) > 0);
  1150. Type *tag_type = union_tag_type(ut);
  1151. LLVMTypeRef uvt = llvm_addr_type(p->module, u);
  1152. unsigned element_count = LLVMCountStructElementTypes(uvt);
  1153. GB_ASSERT_MSG(element_count >= 2, "element_count=%u (%s) != (%s)", element_count, type_to_string(ut), LLVMPrintTypeToString(uvt));
  1154. lbValue tag_ptr = {};
  1155. tag_ptr.value = LLVMBuildStructGEP2(p->builder, uvt, u.value, 1, "");
  1156. tag_ptr.type = alloc_type_pointer(tag_type);
  1157. return tag_ptr;
  1158. }
  1159. gb_internal lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  1160. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  1161. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  1162. return lb_emit_load(p, tag_ptr);
  1163. }
  1164. gb_internal void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  1165. Type *t = type_deref(parent.type);
  1166. GB_ASSERT(is_type_union(t));
  1167. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  1168. // No tag needed!
  1169. } else {
  1170. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  1171. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  1172. }
  1173. }
  1174. gb_internal void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  1175. Type *pt = base_type(type_deref(parent.type));
  1176. GB_ASSERT(pt->kind == Type_Union);
  1177. if (pt->Union.kind == UnionType_shared_nil) {
  1178. GB_ASSERT(type_size_of(variant_type));
  1179. lbBlock *if_nil = lb_create_block(p, "shared_nil.if_nil");
  1180. lbBlock *if_not_nil = lb_create_block(p, "shared_nil.if_not_nil");
  1181. lbBlock *done = lb_create_block(p, "shared_nil.done");
  1182. lbValue cond_is_nil = lb_emit_comp_against_nil(p, Token_CmpEq, variant);
  1183. lb_emit_if(p, cond_is_nil, if_nil, if_not_nil);
  1184. lb_start_block(p, if_nil);
  1185. lb_emit_store(p, parent, lb_const_nil(p->module, type_deref(parent.type)));
  1186. lb_emit_jump(p, done);
  1187. lb_start_block(p, if_not_nil);
  1188. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  1189. lb_emit_store(p, underlying, variant);
  1190. lb_emit_store_union_variant_tag(p, parent, variant_type);
  1191. lb_emit_jump(p, done);
  1192. lb_start_block(p, done);
  1193. } else {
  1194. if (type_size_of(variant_type) == 0) {
  1195. unsigned alignment = 1;
  1196. lb_mem_zero_ptr_internal(p, parent.value, pt->Union.variant_block_size, alignment, false);
  1197. } else {
  1198. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  1199. lb_emit_store(p, underlying, variant);
  1200. }
  1201. lb_emit_store_union_variant_tag(p, parent, variant_type);
  1202. }
  1203. }
  1204. gb_internal void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  1205. TEMPORARY_ALLOCATOR_GUARD();
  1206. unsigned field_count = LLVMCountStructElementTypes(src);
  1207. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1208. LLVMGetStructElementTypes(src, fields);
  1209. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  1210. }
  1211. gb_internal String lb_get_entity_name(lbModule *m, Entity *e) {
  1212. GB_ASSERT(m != nullptr);
  1213. GB_ASSERT(e != nullptr);
  1214. if (e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  1215. return e->TypeName.ir_mangled_name;
  1216. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len != 0) {
  1217. return e->Procedure.link_name;
  1218. }
  1219. if (e->pkg == nullptr) {
  1220. return e->token.string;
  1221. }
  1222. gbString w = string_canonical_entity_name(heap_allocator(), e);
  1223. defer (gb_string_free(w));
  1224. String name = copy_string(permanent_allocator(), make_string(cast(u8 const *)w, gb_string_length(w)));
  1225. if (e->kind == Entity_TypeName) {
  1226. e->TypeName.ir_mangled_name = name;
  1227. } else if (e->kind == Entity_Procedure) {
  1228. e->Procedure.link_name = name;
  1229. } else if (e->kind == Entity_Variable) {
  1230. e->Variable.link_name = name;
  1231. }
  1232. return name;
  1233. }
  1234. gb_internal LLVMTypeRef lb_type_internal_for_procedures_raw(lbModule *m, Type *type) {
  1235. Type *original_type = type;
  1236. type = base_type(original_type);
  1237. GB_ASSERT(type->kind == Type_Proc);
  1238. mutex_lock(&m->func_raw_types_mutex);
  1239. defer (mutex_unlock(&m->func_raw_types_mutex));
  1240. LLVMTypeRef *found = map_get(&m->func_raw_types, type);
  1241. if (found) {
  1242. return *found;
  1243. }
  1244. unsigned param_count = 0;
  1245. if (type->Proc.param_count != 0) {
  1246. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1247. for_array(i, type->Proc.params->Tuple.variables) {
  1248. Entity *e = type->Proc.params->Tuple.variables[i];
  1249. if (e->kind != Entity_Variable) {
  1250. continue;
  1251. }
  1252. if (e->flags & EntityFlag_CVarArg) {
  1253. continue;
  1254. }
  1255. param_count += 1;
  1256. }
  1257. }
  1258. m->internal_type_level += 1;
  1259. defer (m->internal_type_level -= 1);
  1260. bool return_is_tuple = false;
  1261. LLVMTypeRef ret = nullptr;
  1262. LLVMTypeRef *params = gb_alloc_array(permanent_allocator(), LLVMTypeRef, param_count);
  1263. bool *params_by_ptr = gb_alloc_array(permanent_allocator(), bool, param_count);
  1264. if (type->Proc.result_count != 0) {
  1265. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1266. if (is_type_proc(single_ret)) {
  1267. single_ret = t_rawptr;
  1268. }
  1269. ret = lb_type(m, single_ret);
  1270. if (is_type_tuple(single_ret)) {
  1271. return_is_tuple = true;
  1272. }
  1273. if (is_type_boolean(single_ret) &&
  1274. is_calling_convention_none(type->Proc.calling_convention) &&
  1275. type_size_of(single_ret) <= 1) {
  1276. ret = LLVMInt1TypeInContext(m->ctx);
  1277. }
  1278. }
  1279. unsigned param_index = 0;
  1280. if (type->Proc.param_count != 0) {
  1281. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1282. for_array(i, type->Proc.params->Tuple.variables) {
  1283. Entity *e = type->Proc.params->Tuple.variables[i];
  1284. if (e->kind != Entity_Variable) {
  1285. continue;
  1286. }
  1287. if (e->flags & EntityFlag_CVarArg) {
  1288. continue;
  1289. }
  1290. Type *e_type = reduce_tuple_to_single_type(e->type);
  1291. bool param_is_by_ptr = false;
  1292. LLVMTypeRef param_type = nullptr;
  1293. if (e->flags & EntityFlag_ByPtr) {
  1294. // it will become a pointer afterwards by making it indirect
  1295. param_type = lb_type(m, e_type);
  1296. param_is_by_ptr = true;
  1297. } else if (is_type_boolean(e_type) &&
  1298. type_size_of(e_type) <= 1) {
  1299. param_type = LLVMInt1TypeInContext(m->ctx);
  1300. } else {
  1301. if (is_type_proc(e_type)) {
  1302. param_type = lb_type(m, t_rawptr);
  1303. } else {
  1304. param_type = lb_type(m, e_type);
  1305. }
  1306. }
  1307. params_by_ptr[param_index] = param_is_by_ptr;
  1308. params[param_index++] = param_type;
  1309. }
  1310. }
  1311. GB_ASSERT(param_index == param_count);
  1312. lbFunctionType *ft = lb_get_abi_info(m, params, param_count, ret, ret != nullptr, return_is_tuple, type->Proc.calling_convention, type);
  1313. {
  1314. for_array(j, ft->args) {
  1315. auto arg = ft->args[j];
  1316. GB_ASSERT_MSG(LLVMGetTypeContext(arg.type) == ft->ctx,
  1317. "\n\t%s %td/%td"
  1318. "\n\tArgTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1319. LLVMPrintTypeToString(arg.type),
  1320. j, ft->args.count,
  1321. LLVMGetTypeContext(arg.type), ft->ctx, LLVMGetGlobalContext());
  1322. }
  1323. GB_ASSERT_MSG(LLVMGetTypeContext(ft->ret.type) == ft->ctx,
  1324. "\n\t%s"
  1325. "\n\tRetTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1326. LLVMPrintTypeToString(ft->ret.type),
  1327. LLVMGetTypeContext(ft->ret.type), ft->ctx, LLVMGetGlobalContext());
  1328. }
  1329. for (unsigned i = 0; i < param_count; i++) {
  1330. if (params_by_ptr[i]) {
  1331. // NOTE(bill): The parameter needs to be passed "indirectly", override it
  1332. ft->args[i].kind = lbArg_Indirect;
  1333. ft->args[i].attribute = nullptr;
  1334. ft->args[i].align_attribute = nullptr;
  1335. ft->args[i].byval_alignment = 0;
  1336. ft->args[i].is_byval = false;
  1337. }
  1338. }
  1339. map_set(&m->function_type_map, type, ft);
  1340. LLVMTypeRef new_abi_fn_type = lb_function_type_to_llvm_raw(ft, type->Proc.c_vararg);
  1341. GB_ASSERT_MSG(LLVMGetTypeContext(new_abi_fn_type) == m->ctx,
  1342. "\n\tFuncTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1343. LLVMGetTypeContext(new_abi_fn_type), m->ctx, LLVMGetGlobalContext());
  1344. map_set(&m->func_raw_types, type, new_abi_fn_type);
  1345. return new_abi_fn_type;
  1346. }
  1347. gb_internal LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  1348. LLVMContextRef ctx = m->ctx;
  1349. i64 size = type_size_of(type); // Check size
  1350. gb_unused(size);
  1351. GB_ASSERT(type != t_invalid);
  1352. bool bigger_int = build_context.ptr_size != build_context.int_size;
  1353. switch (type->kind) {
  1354. case Type_Basic:
  1355. switch (type->Basic.kind) {
  1356. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  1357. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  1358. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  1359. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  1360. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  1361. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  1362. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  1363. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  1364. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  1365. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  1366. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  1367. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  1368. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  1369. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  1370. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  1371. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  1372. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  1373. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  1374. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  1375. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  1376. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  1377. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  1378. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  1379. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  1380. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  1381. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  1382. case Basic_complex32:
  1383. {
  1384. char const *name = "..complex32";
  1385. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1386. if (type != nullptr) {
  1387. return type;
  1388. }
  1389. type = LLVMStructCreateNamed(ctx, name);
  1390. LLVMTypeRef fields[2] = {
  1391. lb_type(m, t_f16),
  1392. lb_type(m, t_f16),
  1393. };
  1394. LLVMStructSetBody(type, fields, 2, false);
  1395. return type;
  1396. }
  1397. case Basic_complex64:
  1398. {
  1399. char const *name = "..complex64";
  1400. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1401. if (type != nullptr) {
  1402. return type;
  1403. }
  1404. type = LLVMStructCreateNamed(ctx, name);
  1405. LLVMTypeRef fields[2] = {
  1406. lb_type(m, t_f32),
  1407. lb_type(m, t_f32),
  1408. };
  1409. LLVMStructSetBody(type, fields, 2, false);
  1410. return type;
  1411. }
  1412. case Basic_complex128:
  1413. {
  1414. char const *name = "..complex128";
  1415. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1416. if (type != nullptr) {
  1417. return type;
  1418. }
  1419. type = LLVMStructCreateNamed(ctx, name);
  1420. LLVMTypeRef fields[2] = {
  1421. lb_type(m, t_f64),
  1422. lb_type(m, t_f64),
  1423. };
  1424. LLVMStructSetBody(type, fields, 2, false);
  1425. return type;
  1426. }
  1427. case Basic_quaternion64:
  1428. {
  1429. char const *name = "..quaternion64";
  1430. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1431. if (type != nullptr) {
  1432. return type;
  1433. }
  1434. type = LLVMStructCreateNamed(ctx, name);
  1435. LLVMTypeRef fields[4] = {
  1436. lb_type(m, t_f16),
  1437. lb_type(m, t_f16),
  1438. lb_type(m, t_f16),
  1439. lb_type(m, t_f16),
  1440. };
  1441. LLVMStructSetBody(type, fields, 4, false);
  1442. return type;
  1443. }
  1444. case Basic_quaternion128:
  1445. {
  1446. char const *name = "..quaternion128";
  1447. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1448. if (type != nullptr) {
  1449. return type;
  1450. }
  1451. type = LLVMStructCreateNamed(ctx, name);
  1452. LLVMTypeRef fields[4] = {
  1453. lb_type(m, t_f32),
  1454. lb_type(m, t_f32),
  1455. lb_type(m, t_f32),
  1456. lb_type(m, t_f32),
  1457. };
  1458. LLVMStructSetBody(type, fields, 4, false);
  1459. return type;
  1460. }
  1461. case Basic_quaternion256:
  1462. {
  1463. char const *name = "..quaternion256";
  1464. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1465. if (type != nullptr) {
  1466. return type;
  1467. }
  1468. type = LLVMStructCreateNamed(ctx, name);
  1469. LLVMTypeRef fields[4] = {
  1470. lb_type(m, t_f64),
  1471. lb_type(m, t_f64),
  1472. lb_type(m, t_f64),
  1473. lb_type(m, t_f64),
  1474. };
  1475. LLVMStructSetBody(type, fields, 4, false);
  1476. return type;
  1477. }
  1478. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.int_size);
  1479. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.int_size);
  1480. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.ptr_size);
  1481. case Basic_rawptr: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1482. case Basic_string:
  1483. {
  1484. char const *name = "..string";
  1485. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1486. if (type != nullptr) {
  1487. return type;
  1488. }
  1489. type = LLVMStructCreateNamed(ctx, name);
  1490. if (build_context.metrics.ptr_size < build_context.metrics.int_size) {
  1491. GB_ASSERT(build_context.metrics.ptr_size == 4);
  1492. GB_ASSERT(build_context.metrics.int_size == 8);
  1493. LLVMTypeRef fields[3] = {
  1494. LLVMPointerType(lb_type(m, t_u8), 0),
  1495. lb_type(m, t_i32),
  1496. lb_type(m, t_int),
  1497. };
  1498. LLVMStructSetBody(type, fields, 3, false);
  1499. } else {
  1500. LLVMTypeRef fields[2] = {
  1501. LLVMPointerType(lb_type(m, t_u8), 0),
  1502. lb_type(m, t_int),
  1503. };
  1504. LLVMStructSetBody(type, fields, 2, false);
  1505. }
  1506. return type;
  1507. }
  1508. case Basic_cstring: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1509. case Basic_any:
  1510. {
  1511. char const *name = "..any";
  1512. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1513. if (type != nullptr) {
  1514. return type;
  1515. }
  1516. type = LLVMStructCreateNamed(ctx, name);
  1517. if (build_context.ptr_size == 4) {
  1518. LLVMTypeRef fields[3] = {
  1519. lb_type(m, t_rawptr),
  1520. lb_type_padding_filler(m, build_context.ptr_size, build_context.ptr_size), // padding
  1521. lb_type(m, t_typeid),
  1522. };
  1523. LLVMStructSetBody(type, fields, 3, false);
  1524. } else {
  1525. LLVMTypeRef fields[2] = {
  1526. lb_type(m, t_rawptr),
  1527. lb_type(m, t_typeid),
  1528. };
  1529. LLVMStructSetBody(type, fields, 2, false);
  1530. }
  1531. return type;
  1532. }
  1533. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 64);
  1534. // Endian Specific Types
  1535. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  1536. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  1537. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  1538. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  1539. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  1540. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  1541. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  1542. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  1543. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  1544. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  1545. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  1546. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  1547. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  1548. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  1549. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  1550. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  1551. // Untyped types
  1552. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1553. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1554. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1555. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1556. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1557. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1558. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1559. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1560. case Basic_UntypedUninit: GB_PANIC("Basic_UntypedUninit"); break;
  1561. }
  1562. break;
  1563. case Type_Named:
  1564. {
  1565. Type *base = base_type(type->Named.base);
  1566. switch (base->kind) {
  1567. case Type_Basic:
  1568. return lb_type_internal(m, base);
  1569. case Type_Named:
  1570. case Type_Generic:
  1571. GB_PANIC("INVALID TYPE");
  1572. break;
  1573. case Type_Pointer:
  1574. case Type_Array:
  1575. case Type_EnumeratedArray:
  1576. case Type_Slice:
  1577. case Type_DynamicArray:
  1578. case Type_Map:
  1579. case Type_Enum:
  1580. case Type_BitSet:
  1581. case Type_SimdVector:
  1582. return lb_type_internal(m, base);
  1583. case Type_Proc:
  1584. // TODO(bill): Deal with this correctly. Can this be named?
  1585. return lb_type_internal(m, base);
  1586. case Type_Tuple:
  1587. return lb_type_internal(m, base);
  1588. }
  1589. LLVMTypeRef *found = map_get(&m->types, base);
  1590. if (found) {
  1591. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1592. if (kind == LLVMStructTypeKind) {
  1593. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1594. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1595. if (llvm_type != nullptr) {
  1596. return llvm_type;
  1597. }
  1598. llvm_type = LLVMStructCreateNamed(ctx, name);
  1599. LLVMTypeRef found_val = *found;
  1600. map_set(&m->types, type, llvm_type);
  1601. lb_clone_struct_type(llvm_type, found_val);
  1602. return llvm_type;
  1603. }
  1604. }
  1605. switch (base->kind) {
  1606. case Type_Struct:
  1607. case Type_Union:
  1608. {
  1609. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1610. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1611. if (llvm_type != nullptr) {
  1612. return llvm_type;
  1613. }
  1614. llvm_type = LLVMStructCreateNamed(ctx, name);
  1615. map_set(&m->types, type, llvm_type);
  1616. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1617. if (base->kind == Type_Struct) {
  1618. map_set(&m->struct_field_remapping, cast(void *)llvm_type, lb_get_struct_remapping(m, base));
  1619. map_set(&m->struct_field_remapping, cast(void *)type, lb_get_struct_remapping(m, base));
  1620. }
  1621. return llvm_type;
  1622. }
  1623. }
  1624. return lb_type_internal(m, base);
  1625. }
  1626. case Type_Pointer:
  1627. return LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  1628. case Type_MultiPointer:
  1629. return LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  1630. case Type_Array: {
  1631. m->internal_type_level += 1;
  1632. LLVMTypeRef t = llvm_array_type(lb_type(m, type->Array.elem), type->Array.count);
  1633. m->internal_type_level -= 1;
  1634. return t;
  1635. }
  1636. case Type_EnumeratedArray: {
  1637. m->internal_type_level += 1;
  1638. LLVMTypeRef t = llvm_array_type(lb_type(m, type->EnumeratedArray.elem), type->EnumeratedArray.count);
  1639. m->internal_type_level -= 1;
  1640. return t;
  1641. }
  1642. case Type_Slice:
  1643. {
  1644. if (bigger_int) {
  1645. LLVMTypeRef fields[3] = {
  1646. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1647. lb_type_padding_filler(m, build_context.ptr_size, build_context.ptr_size), // padding
  1648. lb_type(m, t_int), // len
  1649. };
  1650. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1651. } else {
  1652. LLVMTypeRef fields[2] = {
  1653. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1654. lb_type(m, t_int), // len
  1655. };
  1656. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1657. }
  1658. }
  1659. break;
  1660. case Type_DynamicArray:
  1661. {
  1662. if (bigger_int) {
  1663. LLVMTypeRef fields[5] = {
  1664. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1665. lb_type_padding_filler(m, build_context.ptr_size, build_context.ptr_size), // padding
  1666. lb_type(m, t_int), // len
  1667. lb_type(m, t_int), // cap
  1668. lb_type(m, t_allocator), // allocator
  1669. };
  1670. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1671. } else {
  1672. LLVMTypeRef fields[4] = {
  1673. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1674. lb_type(m, t_int), // len
  1675. lb_type(m, t_int), // cap
  1676. lb_type(m, t_allocator), // allocator
  1677. };
  1678. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1679. }
  1680. }
  1681. break;
  1682. case Type_Map:
  1683. init_map_internal_debug_types(type);
  1684. GB_ASSERT(t_raw_map != nullptr);
  1685. return lb_type_internal(m, t_raw_map);
  1686. case Type_Struct:
  1687. {
  1688. type_set_offsets(type);
  1689. i64 full_type_size = type_size_of(type);
  1690. i64 full_type_align = type_align_of(type);
  1691. GB_ASSERT(full_type_size % full_type_align == 0);
  1692. if (type->Struct.is_raw_union) {
  1693. lbStructFieldRemapping field_remapping = {};
  1694. slice_init(&field_remapping, permanent_allocator(), 1);
  1695. LLVMTypeRef fields[1] = {};
  1696. fields[0] = lb_type_padding_filler(m, full_type_size, full_type_align);
  1697. field_remapping[0] = 0;
  1698. LLVMTypeRef struct_type = LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1699. map_set(&m->struct_field_remapping, cast(void *)struct_type, field_remapping);
  1700. map_set(&m->struct_field_remapping, cast(void *)type, field_remapping);
  1701. return struct_type;
  1702. }
  1703. lbStructFieldRemapping field_remapping = {};
  1704. slice_init(&field_remapping, permanent_allocator(), type->Struct.fields.count);
  1705. m->internal_type_level += 1;
  1706. defer (m->internal_type_level -= 1);
  1707. auto fields = array_make<LLVMTypeRef>(temporary_allocator(), 0, type->Struct.fields.count*2 + 2);
  1708. if (are_struct_fields_reordered(type)) {
  1709. // NOTE(bill, 2021-10-02): Minor hack to enforce `llvm_const_named_struct` usage correctly
  1710. LLVMTypeRef padding_type = lb_type_padding_filler(m, 0, type_align_of(type));
  1711. array_add(&fields, padding_type);
  1712. }
  1713. i64 prev_offset = 0;
  1714. bool requires_packing = type->Struct.is_packed;
  1715. for (i32 field_index : struct_fields_index_by_increasing_offset(temporary_allocator(), type)) {
  1716. Entity *field = type->Struct.fields[field_index];
  1717. i64 offset = type->Struct.offsets[field_index];
  1718. GB_ASSERT(offset >= prev_offset);
  1719. i64 padding = offset - prev_offset;
  1720. if (padding != 0) {
  1721. LLVMTypeRef padding_type = lb_type_padding_filler(m, padding, type_align_of(field->type));
  1722. array_add(&fields, padding_type);
  1723. }
  1724. field_remapping[field_index] = cast(i32)fields.count;
  1725. Type *field_type = field->type;
  1726. if (is_type_proc(field_type)) {
  1727. // NOTE(bill, 2022-11-23): Prevent type cycle declaration (e.g. vtable) of procedures
  1728. // because LLVM is dumb with procedure types
  1729. field_type = t_rawptr;
  1730. }
  1731. // max_field_align might misalign items in a way that requires packing
  1732. // so check the alignment of all fields to see if packing is required.
  1733. requires_packing = requires_packing || ((offset % type_align_of(field_type)) != 0);
  1734. array_add(&fields, lb_type(m, field_type));
  1735. prev_offset = offset + type_size_of(field->type);
  1736. }
  1737. i64 end_padding = full_type_size-prev_offset;
  1738. if (end_padding > 0) {
  1739. array_add(&fields, lb_type_padding_filler(m, end_padding, 1));
  1740. }
  1741. for_array(i, fields) {
  1742. GB_ASSERT(fields[i] != nullptr);
  1743. }
  1744. LLVMTypeRef struct_type = LLVMStructTypeInContext(ctx, fields.data, cast(unsigned)fields.count, requires_packing);
  1745. map_set(&m->struct_field_remapping, cast(void *)struct_type, field_remapping);
  1746. map_set(&m->struct_field_remapping, cast(void *)type, field_remapping);
  1747. #if 0
  1748. GB_ASSERT_MSG(lb_sizeof(struct_type) == full_type_size,
  1749. "(%lld) %s vs (%lld) %s",
  1750. cast(long long)lb_sizeof(struct_type), LLVMPrintTypeToString(struct_type),
  1751. cast(long long)full_type_size, type_to_string(type));
  1752. #endif
  1753. return struct_type;
  1754. }
  1755. break;
  1756. case Type_Union:
  1757. if (type->Union.variants.count == 0) {
  1758. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1759. } else {
  1760. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1761. // LLVM takes the first element's alignment as the entire alignment (like C)
  1762. i64 align = type_align_of(type);
  1763. i64 size = type_size_of(type);
  1764. gb_unused(size);
  1765. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1766. LLVMTypeRef fields[] = {lb_type(m, type->Union.variants[0])};
  1767. return LLVMStructTypeInContext(ctx, fields, gb_count_of(fields), false);
  1768. }
  1769. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1770. auto fields = array_make<LLVMTypeRef>(temporary_allocator(), 0, 3);
  1771. if (is_type_union_maybe_pointer(type)) {
  1772. LLVMTypeRef variant = lb_type(m, type->Union.variants[0]);
  1773. array_add(&fields, variant);
  1774. } else {
  1775. LLVMTypeRef block_type = lb_type_padding_filler(m, block_size, align);
  1776. LLVMTypeRef tag_type = lb_type(m, union_tag_type(type));
  1777. array_add(&fields, block_type);
  1778. array_add(&fields, tag_type);
  1779. i64 used_size = lb_sizeof(block_type) + lb_sizeof(tag_type);
  1780. i64 padding = size - used_size;
  1781. if (padding > 0) {
  1782. LLVMTypeRef padding_type = lb_type_padding_filler(m, padding, align);
  1783. array_add(&fields, padding_type);
  1784. }
  1785. }
  1786. return LLVMStructTypeInContext(ctx, fields.data, cast(unsigned)fields.count, false);
  1787. }
  1788. break;
  1789. case Type_Enum:
  1790. return lb_type(m, base_enum_type(type));
  1791. case Type_Tuple:
  1792. if (type->Tuple.variables.count == 1) {
  1793. return lb_type(m, type->Tuple.variables[0]->type);
  1794. } else {
  1795. m->internal_type_level += 1;
  1796. defer (m->internal_type_level -= 1);
  1797. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1798. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1799. for_array(i, type->Tuple.variables) {
  1800. Entity *field = type->Tuple.variables[i];
  1801. LLVMTypeRef param_type = nullptr;
  1802. param_type = lb_type(m, field->type);
  1803. fields[i] = param_type;
  1804. }
  1805. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1806. }
  1807. case Type_Proc:
  1808. {
  1809. LLVMTypeRef proc_raw_type = lb_type_internal_for_procedures_raw(m, type);
  1810. gb_unused(proc_raw_type);
  1811. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1812. }
  1813. break;
  1814. case Type_BitSet:
  1815. {
  1816. Type *ut = bit_set_to_int(type);
  1817. return lb_type(m, ut);
  1818. }
  1819. case Type_SimdVector:
  1820. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1821. case Type_Matrix:
  1822. {
  1823. i64 size = type_size_of(type);
  1824. i64 elem_size = type_size_of(type->Matrix.elem);
  1825. GB_ASSERT(elem_size > 0);
  1826. i64 elem_count = size/elem_size;
  1827. GB_ASSERT_MSG(elem_count > 0, "%s", type_to_string(type));
  1828. m->internal_type_level -= 1;
  1829. LLVMTypeRef elem = lb_type(m, type->Matrix.elem);
  1830. LLVMTypeRef t = llvm_array_type(elem, elem_count);
  1831. m->internal_type_level += 1;
  1832. return t;
  1833. }
  1834. case Type_SoaPointer:
  1835. {
  1836. unsigned field_count = 2;
  1837. if (bigger_int) {
  1838. field_count = 3;
  1839. }
  1840. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1841. fields[0] = LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  1842. if (bigger_int) {
  1843. fields[1] = lb_type_padding_filler(m, build_context.ptr_size, build_context.ptr_size);
  1844. fields[2] = LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.int_size);
  1845. } else {
  1846. fields[1] = LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.int_size);
  1847. }
  1848. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1849. }
  1850. case Type_BitField:
  1851. return lb_type_internal(m, type->BitField.backing_type);
  1852. }
  1853. GB_PANIC("Invalid type %s", type_to_string(type));
  1854. return LLVMInt32TypeInContext(ctx);
  1855. }
  1856. gb_internal LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1857. type = default_type(type);
  1858. mutex_lock(&m->types_mutex);
  1859. defer (mutex_unlock(&m->types_mutex));
  1860. LLVMTypeRef *found = map_get(&m->types, type);
  1861. if (found) {
  1862. return *found;
  1863. }
  1864. LLVMTypeRef llvm_type = nullptr;
  1865. m->internal_type_level += 1;
  1866. llvm_type = lb_type_internal(m, type);
  1867. m->internal_type_level -= 1;
  1868. if (m->internal_type_level == 0) {
  1869. map_set(&m->types, type, llvm_type);
  1870. }
  1871. return llvm_type;
  1872. }
  1873. gb_internal lbFunctionType *lb_get_function_type(lbModule *m, Type *pt) {
  1874. lbFunctionType **ft_found = nullptr;
  1875. ft_found = map_get(&m->function_type_map, pt);
  1876. if (!ft_found) {
  1877. LLVMTypeRef llvm_proc_type = lb_type(m, pt);
  1878. gb_unused(llvm_proc_type);
  1879. ft_found = map_get(&m->function_type_map, pt);
  1880. }
  1881. GB_ASSERT(ft_found != nullptr);
  1882. return *ft_found;
  1883. }
  1884. gb_internal void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  1885. if (p->abi_function_type != nullptr) {
  1886. return;
  1887. }
  1888. lbFunctionType **ft_found = map_get(&m->function_type_map, p->type);
  1889. if (ft_found == nullptr) {
  1890. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  1891. gb_unused(llvm_proc_type);
  1892. ft_found = map_get(&m->function_type_map, p->type);
  1893. }
  1894. GB_ASSERT(ft_found != nullptr);
  1895. p->abi_function_type = *ft_found;
  1896. GB_ASSERT(p->abi_function_type != nullptr);
  1897. }
  1898. gb_internal void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1899. if (e != nullptr) {
  1900. rw_mutex_lock(&m->values_mutex);
  1901. map_set(&m->values, e, val);
  1902. rw_mutex_unlock(&m->values_mutex);
  1903. }
  1904. }
  1905. gb_internal void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1906. if (name.len > 0) {
  1907. rw_mutex_lock(&m->values_mutex);
  1908. string_map_set(&m->members, name, val);
  1909. rw_mutex_unlock(&m->values_mutex);
  1910. }
  1911. }
  1912. gb_internal void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1913. rw_mutex_lock(&m->values_mutex);
  1914. if (p->entity != nullptr) {
  1915. map_set(&m->procedure_values, p->value, p->entity);
  1916. }
  1917. string_map_set(&m->procedures, p->name, p);
  1918. rw_mutex_unlock(&m->values_mutex);
  1919. }
  1920. gb_internal LLVMAttributeRef lb_create_enum_attribute_with_type(LLVMContextRef ctx, char const *name, LLVMTypeRef type) {
  1921. unsigned kind = 0;
  1922. String s = make_string_c(name);
  1923. #if ODIN_LLVM_MINIMUM_VERSION_12
  1924. kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1925. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1926. return LLVMCreateTypeAttribute(ctx, kind, type);
  1927. #else
  1928. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1929. // and the current LLVM C API does not expose this functionality yet.
  1930. // It is better to ignore the attributes for the time being
  1931. if (s == "byval") {
  1932. // return nullptr;
  1933. } else if (s == "byref") {
  1934. return nullptr;
  1935. } else if (s == "preallocated") {
  1936. return nullptr;
  1937. } else if (s == "sret") {
  1938. // return nullptr;
  1939. }
  1940. kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1941. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1942. return LLVMCreateEnumAttribute(ctx, kind, 0);
  1943. #endif
  1944. }
  1945. gb_internal LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1946. String s = make_string_c(name);
  1947. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1948. // and the current LLVM C API does not expose this functionality yet.
  1949. // It is better to ignore the attributes for the time being
  1950. if (s == "byval") {
  1951. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1952. } else if (s == "byref") {
  1953. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1954. } else if (s == "preallocated") {
  1955. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1956. } else if (s == "sret") {
  1957. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1958. }
  1959. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1960. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1961. return LLVMCreateEnumAttribute(ctx, kind, value);
  1962. }
  1963. gb_internal LLVMAttributeRef lb_create_string_attribute(LLVMContextRef ctx, String const &key, String const &value) {
  1964. LLVMAttributeRef attr = LLVMCreateStringAttribute(
  1965. ctx,
  1966. cast(char const *)key.text, cast(unsigned)key.len,
  1967. cast(char const *)value.text, cast(unsigned)value.len);
  1968. return attr;
  1969. }
  1970. gb_internal void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1971. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1972. GB_ASSERT(attr != nullptr);
  1973. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1974. }
  1975. gb_internal void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1976. lb_add_proc_attribute_at_index(p, index, name, 0);
  1977. }
  1978. gb_internal void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  1979. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  1980. }
  1981. gb_internal bool lb_proc_has_attribute(lbModule *m, LLVMValueRef proc_value, char const *name) {
  1982. LLVMAttributeRef ref = LLVMGetEnumAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, LLVMGetEnumAttributeKindForName(name, gb_strlen(name)));
  1983. return ref != nullptr;
  1984. }
  1985. gb_internal void lb_add_attribute_to_proc_with_string(lbModule *m, LLVMValueRef proc_value, String const &name, String const &value) {
  1986. LLVMAttributeRef attr = lb_create_string_attribute(m->ctx, name, value);
  1987. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, attr);
  1988. }
  1989. gb_internal void lb_add_edge(lbBlock *from, lbBlock *to) {
  1990. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  1991. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  1992. array_add(&from->succs, to);
  1993. array_add(&to->preds, from);
  1994. }
  1995. }
  1996. gb_internal lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  1997. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  1998. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  1999. b->appended = false;
  2000. if (append) {
  2001. b->appended = true;
  2002. LLVMAppendExistingBasicBlock(p->value, b->block);
  2003. }
  2004. b->scope = p->curr_scope;
  2005. b->scope_index = p->scope_index;
  2006. b->preds.allocator = heap_allocator();
  2007. b->succs.allocator = heap_allocator();
  2008. array_add(&p->blocks, b);
  2009. return b;
  2010. }
  2011. gb_internal void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  2012. if (p->curr_block == nullptr) {
  2013. return;
  2014. }
  2015. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2016. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2017. return;
  2018. }
  2019. lb_add_edge(p->curr_block, target_block);
  2020. LLVMBuildBr(p->builder, target_block->block);
  2021. p->curr_block = nullptr;
  2022. }
  2023. gb_internal void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  2024. lbBlock *b = p->curr_block;
  2025. if (b == nullptr) {
  2026. return;
  2027. }
  2028. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2029. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  2030. return;
  2031. }
  2032. lb_add_edge(b, true_block);
  2033. lb_add_edge(b, false_block);
  2034. LLVMValueRef cv = cond.value;
  2035. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  2036. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  2037. }
  2038. gb_internal gb_inline LLVMTypeRef OdinLLVMGetInternalElementType(LLVMTypeRef type) {
  2039. return LLVMGetElementType(type);
  2040. }
  2041. gb_internal LLVMTypeRef OdinLLVMGetArrayElementType(LLVMTypeRef type) {
  2042. GB_ASSERT(lb_is_type_kind(type, LLVMArrayTypeKind));
  2043. return OdinLLVMGetInternalElementType(type);
  2044. }
  2045. gb_internal LLVMTypeRef OdinLLVMGetVectorElementType(LLVMTypeRef type) {
  2046. GB_ASSERT(lb_is_type_kind(type, LLVMVectorTypeKind));
  2047. return OdinLLVMGetInternalElementType(type);
  2048. }
  2049. gb_internal LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  2050. LLVMContextRef ctx = p->module->ctx;
  2051. LLVMTypeRef src_type = LLVMTypeOf(val);
  2052. if (src_type == dst_type) {
  2053. return val;
  2054. }
  2055. i64 src_size = lb_sizeof(src_type);
  2056. i64 dst_size = lb_sizeof(dst_type);
  2057. i64 src_align = lb_alignof(src_type);
  2058. i64 dst_align = lb_alignof(dst_type);
  2059. if (LLVMIsALoadInst(val)) {
  2060. src_align = gb_min(src_align, LLVMGetAlignment(val));
  2061. }
  2062. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  2063. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  2064. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  2065. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2066. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  2067. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  2068. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  2069. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  2070. }
  2071. if (src_size != dst_size) {
  2072. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  2073. // Okay
  2074. } else {
  2075. goto general_end;
  2076. }
  2077. }
  2078. if (src_kind == dst_kind) {
  2079. if (src_kind == LLVMPointerTypeKind) {
  2080. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  2081. } else if (src_kind == LLVMArrayTypeKind) {
  2082. // ignore
  2083. } else if (src_kind != LLVMStructTypeKind) {
  2084. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  2085. }
  2086. } else {
  2087. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  2088. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  2089. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  2090. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  2091. }
  2092. }
  2093. general_end:;
  2094. // make the alignment big if necessary
  2095. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  2096. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2097. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  2098. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  2099. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  2100. }
  2101. }
  2102. src_size = align_formula(src_size, src_align);
  2103. dst_size = align_formula(dst_size, dst_align);
  2104. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  2105. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  2106. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  2107. LLVMValueRef loaded_val = OdinLLVMBuildLoad(p, dst_type, val_ptr);
  2108. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  2109. return loaded_val;
  2110. } else {
  2111. GB_ASSERT(p->decl_block != p->curr_block);
  2112. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  2113. max_align = gb_max(max_align, 16);
  2114. LLVMValueRef ptr = llvm_alloca(p, dst_type, max_align);
  2115. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  2116. LLVMBuildStore(p->builder, val, nptr);
  2117. return OdinLLVMBuildLoad(p, dst_type, ptr);
  2118. }
  2119. }
  2120. gb_internal LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  2121. StringHashKey key = string_hash_string(str);
  2122. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  2123. if (found != nullptr) {
  2124. return *found;
  2125. } else {
  2126. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  2127. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  2128. cast(char const *)str.text,
  2129. cast(unsigned)str.len,
  2130. false);
  2131. isize max_len = 7+8+1;
  2132. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  2133. u32 id = m->gen->global_array_index.fetch_add(1);
  2134. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  2135. len -= 1;
  2136. LLVMTypeRef type = LLVMTypeOf(data);
  2137. LLVMValueRef global_data = LLVMAddGlobal(m->mod, type, name);
  2138. LLVMSetInitializer(global_data, data);
  2139. lb_make_global_private_const(global_data);
  2140. LLVMSetAlignment(global_data, 1);
  2141. LLVMValueRef ptr = LLVMConstInBoundsGEP2(type, global_data, indices, 2);
  2142. string_map_set(&m->const_strings, key, ptr);
  2143. return ptr;
  2144. }
  2145. }
  2146. gb_internal lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  2147. LLVMValueRef ptr = nullptr;
  2148. if (str.len != 0) {
  2149. ptr = lb_find_or_add_entity_string_ptr(m, str);
  2150. } else {
  2151. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  2152. }
  2153. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  2154. lbValue res = {};
  2155. res.value = llvm_const_string_internal(m, t_string, ptr, str_len);
  2156. res.type = t_string;
  2157. return res;
  2158. }
  2159. gb_internal lbValue lb_find_or_add_entity_string_byte_slice_with_type(lbModule *m, String const &str, Type *slice_type) {
  2160. GB_ASSERT(is_type_slice(slice_type));
  2161. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  2162. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  2163. cast(char const *)str.text,
  2164. cast(unsigned)str.len,
  2165. false);
  2166. char *name = nullptr;
  2167. {
  2168. isize max_len = 7+8+1;
  2169. name = gb_alloc_array(permanent_allocator(), char, max_len);
  2170. u32 id = m->gen->global_array_index.fetch_add(1);
  2171. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  2172. len -= 1;
  2173. }
  2174. LLVMTypeRef type = LLVMTypeOf(data);
  2175. LLVMValueRef global_data = LLVMAddGlobal(m->mod, type, name);
  2176. LLVMSetInitializer(global_data, data);
  2177. lb_make_global_private_const(global_data);
  2178. LLVMSetAlignment(global_data, 1);
  2179. i64 data_len = str.len;
  2180. LLVMValueRef ptr = nullptr;
  2181. if (data_len != 0) {
  2182. ptr = LLVMConstInBoundsGEP2(type, global_data, indices, 2);
  2183. } else {
  2184. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  2185. }
  2186. if (!is_type_u8_slice(slice_type)) {
  2187. Type *bt = base_type(slice_type);
  2188. Type *elem = bt->Slice.elem;
  2189. i64 sz = type_size_of(elem);
  2190. GB_ASSERT(sz > 0);
  2191. ptr = LLVMConstPointerCast(ptr, lb_type(m, alloc_type_pointer(elem)));
  2192. data_len /= sz;
  2193. }
  2194. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), data_len, true);
  2195. LLVMValueRef values[2] = {ptr, len};
  2196. lbValue res = {};
  2197. res.value = llvm_const_named_struct(m, slice_type, values, 2);
  2198. res.type = slice_type;
  2199. return res;
  2200. }
  2201. gb_internal lbValue lb_find_ident(lbProcedure *p, lbModule *m, Entity *e, Ast *expr) {
  2202. if (e->flags & EntityFlag_Param) {
  2203. // NOTE(bill): Bypass the stack copied variable for
  2204. // direct parameters as there is no need for the direct load
  2205. auto *found = map_get(&p->direct_parameters, e);
  2206. if (found) {
  2207. return *found;
  2208. }
  2209. }
  2210. lbValue *found = nullptr;
  2211. rw_mutex_shared_lock(&m->values_mutex);
  2212. found = map_get(&m->values, e);
  2213. rw_mutex_shared_unlock(&m->values_mutex);
  2214. if (found) {
  2215. auto v = *found;
  2216. // NOTE(bill): This is because pointers are already pointers in LLVM
  2217. if (is_type_proc(v.type)) {
  2218. return v;
  2219. }
  2220. return lb_emit_load(p, v);
  2221. } else if (e != nullptr && e->kind == Entity_Variable) {
  2222. return lb_addr_load(p, lb_build_addr(p, expr));
  2223. }
  2224. if (e->kind == Entity_Procedure) {
  2225. return lb_find_procedure_value_from_entity(m, e);
  2226. }
  2227. if (USE_SEPARATE_MODULES) {
  2228. lbModule *other_module = lb_module_of_entity(m->gen, e);
  2229. if (other_module != m) {
  2230. String name = lb_get_entity_name(other_module, e);
  2231. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  2232. lbValue g = {};
  2233. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2234. g.type = alloc_type_pointer(e->type);
  2235. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2236. lb_add_entity(m, e, g);
  2237. lb_add_member(m, name, g);
  2238. return lb_emit_load(p, g);
  2239. }
  2240. }
  2241. String pkg = {};
  2242. if (e->pkg) {
  2243. pkg = e->pkg->name;
  2244. }
  2245. gb_printf_err("Error in: %s\n", token_pos_to_string(ast_token(expr).pos));
  2246. GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(pkg), LIT(e->token.string), e, type_to_string(e->type), expr);
  2247. return {};
  2248. }
  2249. gb_internal lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  2250. lbGenerator *gen = m->gen;
  2251. GB_ASSERT(is_type_proc(e->type));
  2252. e = strip_entity_wrapping(e);
  2253. GB_ASSERT(e != nullptr);
  2254. GB_ASSERT(e->kind == Entity_Procedure);
  2255. lbValue *found = nullptr;
  2256. rw_mutex_shared_lock(&m->values_mutex);
  2257. found = map_get(&m->values, e);
  2258. rw_mutex_shared_unlock(&m->values_mutex);
  2259. if (found) {
  2260. return *found;
  2261. }
  2262. bool ignore_body = false;
  2263. lbModule *other_module = m;
  2264. if (USE_SEPARATE_MODULES) {
  2265. other_module = lb_module_of_entity(gen, e);
  2266. }
  2267. if (other_module == m) {
  2268. debugf("Missing Procedure (lb_find_procedure_value_from_entity): %.*s module %p\n", LIT(e->token.string), m);
  2269. }
  2270. ignore_body = other_module != m;
  2271. lbProcedure *missing_proc = lb_create_procedure(m, e, ignore_body);
  2272. if (ignore_body) {
  2273. mutex_lock(&gen->anonymous_proc_lits_mutex);
  2274. defer (mutex_unlock(&gen->anonymous_proc_lits_mutex));
  2275. GB_ASSERT(other_module != nullptr);
  2276. rw_mutex_shared_lock(&other_module->values_mutex);
  2277. auto *found = map_get(&other_module->values, e);
  2278. rw_mutex_shared_unlock(&other_module->values_mutex);
  2279. if (found == nullptr) {
  2280. // THIS IS THE RACE CONDITION
  2281. lbProcedure *missing_proc_in_other_module = lb_create_procedure(other_module, e, false);
  2282. array_add(&other_module->missing_procedures_to_check, missing_proc_in_other_module);
  2283. }
  2284. } else {
  2285. array_add(&m->missing_procedures_to_check, missing_proc);
  2286. }
  2287. rw_mutex_shared_lock(&m->values_mutex);
  2288. found = map_get(&m->values, e);
  2289. rw_mutex_shared_unlock(&m->values_mutex);
  2290. if (found) {
  2291. return *found;
  2292. }
  2293. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  2294. return {};
  2295. }
  2296. gb_internal lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) {
  2297. lbGenerator *gen = m->gen;
  2298. mutex_lock(&gen->anonymous_proc_lits_mutex);
  2299. defer (mutex_unlock(&gen->anonymous_proc_lits_mutex));
  2300. TokenPos pos = ast_token(expr).pos;
  2301. lbProcedure **found = map_get(&gen->anonymous_proc_lits, expr);
  2302. if (found) {
  2303. return lb_find_procedure_value_from_entity(m, (*found)->entity);
  2304. }
  2305. ast_node(pl, ProcLit, expr);
  2306. // NOTE(bill): Generate a new name
  2307. // parent$count
  2308. isize name_len = prefix_name.len + 6 + 11;
  2309. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  2310. static std::atomic<i32> name_id;
  2311. name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), 1+name_id.fetch_add(1));
  2312. String name = make_string((u8 *)name_text, name_len-1);
  2313. Type *type = type_of_expr(expr);
  2314. GB_ASSERT(pl->decl->entity == nullptr);
  2315. Token token = {};
  2316. token.pos = ast_token(expr).pos;
  2317. token.kind = Token_Ident;
  2318. token.string = name;
  2319. Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags);
  2320. e->file = expr->file();
  2321. // NOTE(bill): this is to prevent a race condition since these procedure literals can be created anywhere at any time
  2322. pl->decl->code_gen_module = m;
  2323. e->decl_info = pl->decl;
  2324. pl->decl->entity = e;
  2325. e->parent_proc_decl = pl->decl->parent;
  2326. e->Procedure.is_anonymous = true;
  2327. e->flags |= EntityFlag_ProcBodyChecked;
  2328. lbProcedure *p = lb_create_procedure(m, e);
  2329. GB_ASSERT(e->code_gen_module == m);
  2330. lbValue value = {};
  2331. value.value = p->value;
  2332. value.type = p->type;
  2333. map_set(&gen->anonymous_proc_lits, expr, p);
  2334. array_add(&m->procedures_to_generate, p);
  2335. if (parent != nullptr) {
  2336. array_add(&parent->children, p);
  2337. } else {
  2338. string_map_set(&m->members, name, value);
  2339. }
  2340. return value;
  2341. }
  2342. gb_internal lbAddr lb_add_global_generated_with_name(lbModule *m, Type *type, lbValue value, String name, Entity **entity_) {
  2343. GB_ASSERT(type != nullptr);
  2344. type = default_type(type);
  2345. isize max_len = 7+8+1;
  2346. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  2347. Scope *scope = nullptr;
  2348. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  2349. lbValue g = {};
  2350. g.type = alloc_type_pointer(type);
  2351. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  2352. if (value.value != nullptr) {
  2353. GB_ASSERT_MSG(LLVMIsConstant(value.value), LLVMPrintValueToString(value.value));
  2354. LLVMSetInitializer(g.value, value.value);
  2355. } else {
  2356. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  2357. }
  2358. lb_add_entity(m, e, g);
  2359. lb_add_member(m, name, g);
  2360. if (entity_) *entity_ = e;
  2361. return lb_addr(g);
  2362. }
  2363. gb_internal lbAddr lb_add_global_generated_from_procedure(lbProcedure *p, Type *type, lbValue value) {
  2364. GB_ASSERT(type != nullptr);
  2365. type = default_type(type);
  2366. u32 index = ++p->global_generated_index;
  2367. gbString s = gb_string_make(temporary_allocator(), "ggv$");
  2368. s = gb_string_append_length(s, p->name.text, p->name.len);
  2369. s = gb_string_append_fmt(s, "$%u", index);
  2370. String name = make_string(cast(u8 const *)s, gb_string_length(s));
  2371. return lb_add_global_generated_with_name(p->module, type, value, name);
  2372. }
  2373. gb_internal lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  2374. AstPackage *p = m->info->runtime_package;
  2375. Entity *e = scope_lookup_current(p->scope, name);
  2376. return lb_find_value_from_entity(m, e);
  2377. }
  2378. gb_internal lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  2379. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  2380. return lb_find_value_from_entity(m, e);
  2381. }
  2382. gb_internal lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  2383. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  2384. return lb_addr_get_ptr(p, addr);
  2385. }
  2386. gb_internal lbValue lb_find_value_from_entity(lbModule *m, Entity *e) {
  2387. e = strip_entity_wrapping(e);
  2388. GB_ASSERT(e != nullptr);
  2389. GB_ASSERT(e->token.string != "_");
  2390. if (e->kind == Entity_Procedure) {
  2391. return lb_find_procedure_value_from_entity(m, e);
  2392. }
  2393. lbValue *found = nullptr;
  2394. rw_mutex_shared_lock(&m->values_mutex);
  2395. found = map_get(&m->values, e);
  2396. rw_mutex_shared_unlock(&m->values_mutex);
  2397. if (found) {
  2398. return *found;
  2399. }
  2400. if (USE_SEPARATE_MODULES) {
  2401. lbModule *other_module = lb_module_of_entity(m->gen, e);
  2402. bool is_external = other_module != m;
  2403. if (!is_external) {
  2404. if (e->code_gen_module != nullptr) {
  2405. other_module = e->code_gen_module;
  2406. } else {
  2407. other_module = &m->gen->default_module;
  2408. }
  2409. is_external = other_module != m;
  2410. }
  2411. if (is_external) {
  2412. String name = lb_get_entity_name(other_module, e);
  2413. lbValue g = {};
  2414. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2415. g.type = alloc_type_pointer(e->type);
  2416. lb_add_entity(m, e, g);
  2417. lb_add_member(m, name, g);
  2418. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2419. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  2420. if (e->Variable.thread_local_model != "") {
  2421. LLVMSetThreadLocal(g.value, true);
  2422. String m = e->Variable.thread_local_model;
  2423. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  2424. if (m == "default") {
  2425. mode = LLVMGeneralDynamicTLSModel;
  2426. } else if (m == "localdynamic") {
  2427. mode = LLVMLocalDynamicTLSModel;
  2428. } else if (m == "initialexec") {
  2429. mode = LLVMInitialExecTLSModel;
  2430. } else if (m == "localexec") {
  2431. mode = LLVMLocalExecTLSModel;
  2432. } else {
  2433. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  2434. }
  2435. LLVMSetThreadLocalMode(g.value, mode);
  2436. }
  2437. return g;
  2438. }
  2439. }
  2440. GB_PANIC("\n\tError in: %s, missing value '%.*s' in module %s\n",
  2441. token_pos_to_string(e->token.pos), LIT(e->token.string), m->module_name);
  2442. return {};
  2443. }
  2444. gb_internal lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  2445. Token token = {Token_Ident};
  2446. isize name_len = prefix.len + 1 + 20;
  2447. auto suffix_id = cast(unsigned long long)id;
  2448. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  2449. gb_snprintf(text, name_len,
  2450. "%.*s-%llu", LIT(prefix), suffix_id);
  2451. text[name_len] = 0;
  2452. String s = make_string_c(text);
  2453. Type *t = alloc_type_array(elem_type, count);
  2454. lbValue g = {};
  2455. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  2456. g.type = alloc_type_pointer(t);
  2457. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  2458. LLVMSetLinkage(g.value, LLVMPrivateLinkage);
  2459. LLVMSetUnnamedAddress(g.value, LLVMGlobalUnnamedAddr);
  2460. string_map_set(&m->members, s, g);
  2461. return g;
  2462. }
  2463. gb_internal lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2464. GB_ASSERT(cond != nullptr);
  2465. GB_ASSERT(true_block != nullptr);
  2466. GB_ASSERT(false_block != nullptr);
  2467. // Use to signal not to do compile time short circuit for consts
  2468. lbValue no_comptime_short_circuit = {};
  2469. switch (cond->kind) {
  2470. case_ast_node(pe, ParenExpr, cond);
  2471. return lb_build_cond(p, pe->expr, true_block, false_block);
  2472. case_end;
  2473. case_ast_node(ue, UnaryExpr, cond);
  2474. if (ue->op.kind == Token_Not) {
  2475. lbValue cond_val = lb_build_cond(p, ue->expr, false_block, true_block);
  2476. if (cond_val.value && LLVMIsConstant(cond_val.value)) {
  2477. return lb_const_bool(p->module, cond_val.type, LLVMConstIntGetZExtValue(cond_val.value) == 0);
  2478. }
  2479. return no_comptime_short_circuit;
  2480. }
  2481. case_end;
  2482. case_ast_node(be, BinaryExpr, cond);
  2483. if (be->op.kind == Token_CmpAnd) {
  2484. lbBlock *block = lb_create_block(p, "cmp.and");
  2485. lb_build_cond(p, be->left, block, false_block);
  2486. lb_start_block(p, block);
  2487. lb_build_cond(p, be->right, true_block, false_block);
  2488. return no_comptime_short_circuit;
  2489. } else if (be->op.kind == Token_CmpOr) {
  2490. lbBlock *block = lb_create_block(p, "cmp.or");
  2491. lb_build_cond(p, be->left, true_block, block);
  2492. lb_start_block(p, block);
  2493. lb_build_cond(p, be->right, true_block, false_block);
  2494. return no_comptime_short_circuit;
  2495. }
  2496. case_end;
  2497. }
  2498. lbValue v = {};
  2499. if (lb_is_expr_untyped_const(cond)) {
  2500. v = lb_expr_untyped_const_to_typed(p->module, cond, t_llvm_bool);
  2501. } else {
  2502. v = lb_build_expr(p, cond);
  2503. }
  2504. v = lb_emit_conv(p, v, t_llvm_bool);
  2505. lb_emit_if(p, v, true_block, false_block);
  2506. return v;
  2507. }
  2508. gb_internal lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, bool force_no_init) {
  2509. GB_ASSERT(p->decl_block != p->curr_block);
  2510. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2511. char const *name = "";
  2512. if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") {
  2513. // NOTE(bill): for debugging purposes only
  2514. name = alloc_cstring(permanent_allocator(), e->token.string);
  2515. }
  2516. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2517. unsigned alignment = cast(unsigned)gb_max(type_align_of(type), lb_alignof(llvm_type));
  2518. if (is_type_matrix(type)) {
  2519. alignment *= 2; // NOTE(bill): Just in case
  2520. }
  2521. LLVMValueRef ptr = llvm_alloca(p, llvm_type, alignment, name);
  2522. if (!zero_init && !force_no_init) {
  2523. // If there is any padding of any kind, just zero init regardless of zero_init parameter
  2524. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2525. if (kind == LLVMArrayTypeKind) {
  2526. kind = LLVMGetTypeKind(lb_type(p->module, core_array_type(type)));
  2527. }
  2528. if (kind == LLVMStructTypeKind) {
  2529. i64 sz = type_size_of(type);
  2530. if (type_size_of_struct_pretend_is_packed(type) != sz) {
  2531. zero_init = true;
  2532. }
  2533. }
  2534. }
  2535. lbValue val = {};
  2536. val.value = ptr;
  2537. val.type = alloc_type_pointer(type);
  2538. if (e != nullptr) {
  2539. lb_add_entity(p->module, e, val);
  2540. lb_add_debug_local_variable(p, ptr, type, e->token);
  2541. }
  2542. if (zero_init) {
  2543. lb_mem_zero_ptr(p, ptr, type, alignment);
  2544. }
  2545. return lb_addr(val);
  2546. }
  2547. gb_internal lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2548. return lb_add_local(p, type, nullptr, zero_init);
  2549. }
  2550. gb_internal lbAddr lb_add_local_generated_temp(lbProcedure *p, Type *type, i64 min_alignment) {
  2551. lbAddr res = lb_add_local(p, type, nullptr, false, true);
  2552. lb_try_update_alignment(res.addr, cast(unsigned)min_alignment);
  2553. return res;
  2554. }
  2555. gb_internal void lb_set_linkage_from_entity_flags(lbModule *m, LLVMValueRef value, u64 flags) {
  2556. if (flags & EntityFlag_CustomLinkage_Internal) {
  2557. LLVMSetLinkage(value, LLVMInternalLinkage);
  2558. } else if (flags & EntityFlag_CustomLinkage_Strong) {
  2559. LLVMSetLinkage(value, LLVMExternalLinkage);
  2560. } else if (flags & EntityFlag_CustomLinkage_Weak) {
  2561. LLVMSetLinkage(value, LLVMExternalWeakLinkage);
  2562. } else if (flags & EntityFlag_CustomLinkage_LinkOnce) {
  2563. LLVMSetLinkage(value, LLVMLinkOnceAnyLinkage);
  2564. }
  2565. }