llvm_backend_general.cpp 102 KB

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