llvm_backend_general.cpp 102 KB

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