llvm_backend_general.cpp 100 KB

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