llvm_backend_general.cpp 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598
  1. void lb_add_debug_local_variable(lbProcedure *p, LLVMValueRef ptr, Type *type, Token const &token);
  2. gb_global Entity *lb_global_type_info_data_entity = {};
  3. gb_global lbAddr lb_global_type_info_member_types = {};
  4. gb_global lbAddr lb_global_type_info_member_names = {};
  5. gb_global lbAddr lb_global_type_info_member_offsets = {};
  6. gb_global lbAddr lb_global_type_info_member_usings = {};
  7. gb_global lbAddr lb_global_type_info_member_tags = {};
  8. gb_global isize lb_global_type_info_data_index = 0;
  9. gb_global isize lb_global_type_info_member_types_index = 0;
  10. gb_global isize lb_global_type_info_member_names_index = 0;
  11. gb_global isize lb_global_type_info_member_offsets_index = 0;
  12. gb_global isize lb_global_type_info_member_usings_index = 0;
  13. gb_global isize lb_global_type_info_member_tags_index = 0;
  14. void lb_init_module(lbModule *m, Checker *c) {
  15. m->info = &c->info;
  16. gbString module_name = gb_string_make(heap_allocator(), "odin_package");
  17. if (m->pkg) {
  18. module_name = gb_string_appendc(module_name, "-");
  19. module_name = gb_string_append_length(module_name, m->pkg->name.text, m->pkg->name.len);
  20. } else if (USE_SEPARATE_MODULES) {
  21. module_name = gb_string_appendc(module_name, "-builtin");
  22. }
  23. m->ctx = LLVMContextCreate();
  24. m->mod = LLVMModuleCreateWithNameInContext(module_name ? module_name : "odin_package", m->ctx);
  25. // m->debug_builder = nullptr;
  26. if (build_context.ODIN_DEBUG) {
  27. enum {DEBUG_METADATA_VERSION = 3};
  28. LLVMMetadataRef debug_ref = LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), DEBUG_METADATA_VERSION, true));
  29. LLVMAddModuleFlag(m->mod, LLVMModuleFlagBehaviorWarning, "Debug Info Version", 18, debug_ref);
  30. switch (build_context.metrics.os) {
  31. case TargetOs_windows:
  32. LLVMAddModuleFlag(m->mod,
  33. LLVMModuleFlagBehaviorWarning,
  34. "CodeView", 8,
  35. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 1, true)));
  36. break;
  37. case TargetOs_darwin:
  38. // NOTE(bill): Darwin only supports DWARF2 (that I know of)
  39. LLVMAddModuleFlag(m->mod,
  40. LLVMModuleFlagBehaviorWarning,
  41. "Dwarf Version", 13,
  42. LLVMValueAsMetadata(LLVMConstInt(LLVMInt32TypeInContext(m->ctx), 2, true)));
  43. break;
  44. }
  45. m->debug_builder = LLVMCreateDIBuilder(m->mod);
  46. }
  47. gbAllocator a = heap_allocator();
  48. map_init(&m->types, a);
  49. map_init(&m->llvm_types, a);
  50. map_init(&m->values, a);
  51. map_init(&m->soa_values, a);
  52. string_map_init(&m->members, a);
  53. map_init(&m->procedure_values, a);
  54. string_map_init(&m->procedures, a);
  55. string_map_init(&m->const_strings, a);
  56. map_init(&m->anonymous_proc_lits, a);
  57. map_init(&m->function_type_map, a);
  58. map_init(&m->equal_procs, a);
  59. map_init(&m->hasher_procs, a);
  60. array_init(&m->procedures_to_generate, a, 0, 1024);
  61. array_init(&m->foreign_library_paths, a, 0, 1024);
  62. array_init(&m->missing_procedures_to_check, a, 0, 16);
  63. map_init(&m->debug_values, a);
  64. array_init(&m->debug_incomplete_types, a, 0, 1024);
  65. }
  66. bool lb_init_generator(lbGenerator *gen, Checker *c) {
  67. if (global_error_collector.count != 0) {
  68. return false;
  69. }
  70. isize tc = c->parser->total_token_count;
  71. if (tc < 2) {
  72. return false;
  73. }
  74. String init_fullpath = c->parser->init_fullpath;
  75. if (build_context.out_filepath.len == 0) {
  76. gen->output_name = remove_directory_from_path(init_fullpath);
  77. gen->output_name = remove_extension_from_path(gen->output_name);
  78. gen->output_name = string_trim_whitespace(gen->output_name);
  79. if (gen->output_name.len == 0) {
  80. gen->output_name = c->info.init_scope->pkg->name;
  81. }
  82. gen->output_base = gen->output_name;
  83. } else {
  84. gen->output_name = build_context.out_filepath;
  85. gen->output_name = string_trim_whitespace(gen->output_name);
  86. if (gen->output_name.len == 0) {
  87. gen->output_name = c->info.init_scope->pkg->name;
  88. }
  89. isize pos = string_extension_position(gen->output_name);
  90. if (pos < 0) {
  91. gen->output_base = gen->output_name;
  92. } else {
  93. gen->output_base = substring(gen->output_name, 0, pos);
  94. }
  95. }
  96. gbAllocator ha = heap_allocator();
  97. array_init(&gen->output_object_paths, ha);
  98. array_init(&gen->output_temp_paths, ha);
  99. gen->output_base = path_to_full_path(ha, gen->output_base);
  100. gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len);
  101. output_file_path = gb_string_appendc(output_file_path, ".obj");
  102. defer (gb_string_free(output_file_path));
  103. gen->info = &c->info;
  104. map_init(&gen->modules, permanent_allocator(), gen->info->packages.entries.count*2);
  105. map_init(&gen->modules_through_ctx, permanent_allocator(), gen->info->packages.entries.count*2);
  106. map_init(&gen->anonymous_proc_lits, heap_allocator(), 1024);
  107. if (USE_SEPARATE_MODULES) {
  108. for_array(i, gen->info->packages.entries) {
  109. AstPackage *pkg = gen->info->packages.entries[i].value;
  110. auto m = gb_alloc_item(permanent_allocator(), lbModule);
  111. m->pkg = pkg;
  112. m->gen = gen;
  113. map_set(&gen->modules, hash_pointer(pkg), m);
  114. lb_init_module(m, c);
  115. }
  116. }
  117. gen->default_module.gen = gen;
  118. map_set(&gen->modules, hash_pointer(nullptr), &gen->default_module);
  119. lb_init_module(&gen->default_module, c);
  120. for_array(i, gen->modules.entries) {
  121. lbModule *m = gen->modules.entries[i].value;
  122. LLVMContextRef ctx = LLVMGetModuleContext(m->mod);
  123. map_set(&gen->modules_through_ctx, hash_pointer(ctx), m);
  124. }
  125. return true;
  126. }
  127. lbValue lb_global_type_info_data_ptr(lbModule *m) {
  128. lbValue v = lb_find_value_from_entity(m, lb_global_type_info_data_entity);
  129. return v;
  130. }
  131. struct lbLoopData {
  132. lbAddr idx_addr;
  133. lbValue idx;
  134. lbBlock *body;
  135. lbBlock *done;
  136. lbBlock *loop;
  137. };
  138. struct lbCompoundLitElemTempData {
  139. Ast * expr;
  140. lbValue value;
  141. i32 elem_index;
  142. lbValue gep;
  143. };
  144. lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32) {
  145. lbLoopData data = {};
  146. lbValue max = lb_const_int(p->module, t_int, count);
  147. data.idx_addr = lb_add_local_generated(p, index_type, true);
  148. data.body = lb_create_block(p, "loop.body");
  149. data.done = lb_create_block(p, "loop.done");
  150. data.loop = lb_create_block(p, "loop.loop");
  151. lb_emit_jump(p, data.loop);
  152. lb_start_block(p, data.loop);
  153. data.idx = lb_addr_load(p, data.idx_addr);
  154. lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max);
  155. lb_emit_if(p, cond, data.body, data.done);
  156. lb_start_block(p, data.body);
  157. return data;
  158. }
  159. void lb_loop_end(lbProcedure *p, lbLoopData const &data) {
  160. if (data.idx_addr.addr.value != nullptr) {
  161. lb_emit_increment(p, data.idx_addr.addr);
  162. lb_emit_jump(p, data.loop);
  163. lb_start_block(p, data.done);
  164. }
  165. }
  166. LLVMValueRef llvm_zero(lbModule *m) {
  167. return LLVMConstInt(lb_type(m, t_int), 0, false);
  168. }
  169. LLVMValueRef llvm_zero32(lbModule *m) {
  170. return LLVMConstInt(lb_type(m, t_i32), 0, false);
  171. }
  172. LLVMValueRef llvm_one(lbModule *m) {
  173. return LLVMConstInt(lb_type(m, t_i32), 1, false);
  174. }
  175. lbValue lb_zero(lbModule *m, Type *t) {
  176. lbValue v = {};
  177. v.value = LLVMConstInt(lb_type(m, t), 0, false);
  178. v.type = t;
  179. return v;
  180. }
  181. LLVMValueRef llvm_cstring(lbModule *m, String const &str) {
  182. lbValue v = lb_find_or_add_entity_string(m, str);
  183. unsigned indices[1] = {0};
  184. return LLVMConstExtractValue(v.value, indices, gb_count_of(indices));
  185. }
  186. bool lb_is_instr_terminating(LLVMValueRef instr) {
  187. if (instr != nullptr) {
  188. LLVMOpcode op = LLVMGetInstructionOpcode(instr);
  189. switch (op) {
  190. case LLVMRet:
  191. case LLVMBr:
  192. case LLVMSwitch:
  193. case LLVMIndirectBr:
  194. case LLVMInvoke:
  195. case LLVMUnreachable:
  196. case LLVMCallBr:
  197. return true;
  198. }
  199. }
  200. return false;
  201. }
  202. lbModule *lb_pkg_module(lbGenerator *gen, AstPackage *pkg) {
  203. auto *found = map_get(&gen->modules, hash_pointer(pkg));
  204. if (found) {
  205. return *found;
  206. }
  207. return &gen->default_module;
  208. }
  209. lbAddr lb_addr(lbValue addr) {
  210. lbAddr v = {lbAddr_Default, addr};
  211. if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) {
  212. GB_ASSERT(is_type_pointer(addr.type));
  213. v.kind = lbAddr_RelativePointer;
  214. } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) {
  215. GB_ASSERT(is_type_pointer(addr.type));
  216. v.kind = lbAddr_RelativeSlice;
  217. }
  218. return v;
  219. }
  220. lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) {
  221. lbAddr v = {lbAddr_Map, addr};
  222. v.map.key = map_key;
  223. v.map.type = map_type;
  224. v.map.result = map_result;
  225. return v;
  226. }
  227. lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) {
  228. lbAddr v = {lbAddr_SoaVariable, addr};
  229. v.soa.index = index;
  230. v.soa.index_expr = index_expr;
  231. return v;
  232. }
  233. lbAddr lb_addr_swizzle(lbValue addr, Type *array_type, u8 swizzle_count, u8 swizzle_indices[4]) {
  234. GB_ASSERT(is_type_array(array_type));
  235. GB_ASSERT(1 < swizzle_count && swizzle_count <= 4);
  236. lbAddr v = {lbAddr_Swizzle, addr};
  237. v.swizzle.type = array_type;
  238. v.swizzle.count = swizzle_count;
  239. gb_memmove(v.swizzle.indices, swizzle_indices, swizzle_count);
  240. return v;
  241. }
  242. lbAddr lb_addr_swizzle_large(lbValue addr, Type *array_type, Slice<i32> const &swizzle_indices) {
  243. GB_ASSERT_MSG(is_type_array(array_type), "%s", type_to_string(array_type));
  244. lbAddr v = {lbAddr_SwizzleLarge, addr};
  245. v.swizzle_large.type = array_type;
  246. v.swizzle_large.indices = swizzle_indices;
  247. return v;
  248. }
  249. Type *lb_addr_type(lbAddr const &addr) {
  250. if (addr.addr.value == nullptr) {
  251. return nullptr;
  252. }
  253. if (addr.kind == lbAddr_Map) {
  254. Type *t = base_type(addr.map.type);
  255. GB_ASSERT(is_type_map(t));
  256. return t->Map.value;
  257. }
  258. if (addr.kind == lbAddr_Swizzle) {
  259. return addr.swizzle.type;
  260. }
  261. if (addr.kind == lbAddr_SwizzleLarge) {
  262. return addr.swizzle_large.type;
  263. }
  264. return type_deref(addr.addr.type);
  265. }
  266. LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) {
  267. return LLVMGetElementType(LLVMTypeOf(addr.addr.value));
  268. }
  269. lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) {
  270. if (addr.addr.value == nullptr) {
  271. GB_PANIC("Illegal addr -> nullptr");
  272. return {};
  273. }
  274. switch (addr.kind) {
  275. case lbAddr_Map: {
  276. Type *map_type = base_type(addr.map.type);
  277. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  278. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  279. auto args = array_make<lbValue>(permanent_allocator(), 2);
  280. args[0] = h;
  281. args[1] = key;
  282. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  283. return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value));
  284. }
  285. case lbAddr_RelativePointer: {
  286. Type *rel_ptr = base_type(lb_addr_type(addr));
  287. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  288. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  289. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  290. offset = lb_emit_load(p, offset);
  291. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  292. offset = lb_emit_conv(p, offset, t_i64);
  293. }
  294. offset = lb_emit_conv(p, offset, t_uintptr);
  295. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  296. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  297. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  298. // NOTE(bill): nil check
  299. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  300. lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr);
  301. return final_ptr;
  302. }
  303. case lbAddr_SoaVariable:
  304. // TODO(bill): FIX THIS HACK
  305. return lb_address_from_load(p, lb_addr_load(p, addr));
  306. case lbAddr_Context:
  307. GB_PANIC("lbAddr_Context should be handled elsewhere");
  308. break;
  309. case lbAddr_Swizzle:
  310. case lbAddr_SwizzleLarge:
  311. // TOOD(bill): is this good enough logic?
  312. break;
  313. }
  314. return addr.addr;
  315. }
  316. lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) {
  317. lbAddr addr = lb_build_addr(p, expr);
  318. return lb_addr_get_ptr(p, addr);
  319. }
  320. void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue len) {
  321. if (build_context.no_bounds_check) {
  322. return;
  323. }
  324. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  325. return;
  326. }
  327. index = lb_emit_conv(p, index, t_int);
  328. len = lb_emit_conv(p, len, t_int);
  329. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  330. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  331. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  332. auto args = array_make<lbValue>(permanent_allocator(), 5);
  333. args[0] = file;
  334. args[1] = line;
  335. args[2] = column;
  336. args[3] = index;
  337. args[4] = len;
  338. lb_emit_runtime_call(p, "bounds_check_error", args);
  339. }
  340. void lb_emit_multi_pointer_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high) {
  341. if (build_context.no_bounds_check) {
  342. return;
  343. }
  344. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  345. return;
  346. }
  347. low = lb_emit_conv(p, low, t_int);
  348. high = lb_emit_conv(p, high, t_int);
  349. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  350. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  351. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  352. auto args = array_make<lbValue>(permanent_allocator(), 5);
  353. args[0] = file;
  354. args[1] = line;
  355. args[2] = column;
  356. args[3] = low;
  357. args[4] = high;
  358. lb_emit_runtime_call(p, "multi_pointer_slice_expr_error", args);
  359. }
  360. void lb_emit_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high, lbValue len, bool lower_value_used) {
  361. if (build_context.no_bounds_check) {
  362. return;
  363. }
  364. if ((p->state_flags & StateFlag_no_bounds_check) != 0) {
  365. return;
  366. }
  367. lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id));
  368. lbValue line = lb_const_int(p->module, t_i32, token.pos.line);
  369. lbValue column = lb_const_int(p->module, t_i32, token.pos.column);
  370. high = lb_emit_conv(p, high, t_int);
  371. if (!lower_value_used) {
  372. auto args = array_make<lbValue>(permanent_allocator(), 5);
  373. args[0] = file;
  374. args[1] = line;
  375. args[2] = column;
  376. args[3] = high;
  377. args[4] = len;
  378. lb_emit_runtime_call(p, "slice_expr_error_hi", args);
  379. } else {
  380. // No need to convert unless used
  381. low = lb_emit_conv(p, low, t_int);
  382. auto args = array_make<lbValue>(permanent_allocator(), 6);
  383. args[0] = file;
  384. args[1] = line;
  385. args[2] = column;
  386. args[3] = low;
  387. args[4] = high;
  388. args[5] = len;
  389. lb_emit_runtime_call(p, "slice_expr_error_lo_hi", args);
  390. }
  391. }
  392. bool lb_try_update_alignment(lbValue ptr, unsigned alignment) {
  393. LLVMValueRef addr_ptr = ptr.value;
  394. if (LLVMIsAGlobalValue(addr_ptr) || LLVMIsAAllocaInst(addr_ptr) || LLVMIsALoadInst(addr_ptr)) {
  395. if (LLVMGetAlignment(addr_ptr) < alignment) {
  396. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  397. LLVMSetAlignment(addr_ptr, alignment);
  398. }
  399. }
  400. return LLVMGetAlignment(addr_ptr) >= alignment;
  401. }
  402. return false;
  403. }
  404. bool lb_try_vector_cast(lbModule *m, lbValue ptr, LLVMTypeRef *vector_type_) {
  405. Type *array_type = base_type(type_deref(ptr.type));
  406. GB_ASSERT(is_type_array_like(array_type));
  407. i64 count = get_array_type_count(array_type);
  408. Type *elem_type = base_array_type(array_type);
  409. // TODO(bill): Determine what is the correct limit for doing vector arithmetic
  410. if (type_size_of(array_type) <= build_context.max_align &&
  411. is_type_valid_vector_elem(elem_type)) {
  412. // Try to treat it like a vector if possible
  413. bool possible = false;
  414. LLVMTypeRef vector_type = LLVMVectorType(lb_type(m, elem_type), cast(unsigned)count);
  415. unsigned vector_alignment = cast(unsigned)lb_alignof(vector_type);
  416. LLVMValueRef addr_ptr = ptr.value;
  417. if (LLVMIsAAllocaInst(addr_ptr) || LLVMIsAGlobalValue(addr_ptr)) {
  418. unsigned alignment = LLVMGetAlignment(addr_ptr);
  419. alignment = gb_max(alignment, vector_alignment);
  420. possible = true;
  421. LLVMSetAlignment(addr_ptr, alignment);
  422. } else if (LLVMIsALoadInst(addr_ptr)) {
  423. unsigned alignment = LLVMGetAlignment(addr_ptr);
  424. possible = alignment >= vector_alignment;
  425. }
  426. // NOTE: Due to alignment requirements, if the pointer is not correctly aligned
  427. // then it cannot be treated as a vector
  428. if (possible) {
  429. if (vector_type_) *vector_type_ =vector_type;
  430. return true;
  431. }
  432. }
  433. return false;
  434. }
  435. void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) {
  436. if (addr.addr.value == nullptr) {
  437. return;
  438. }
  439. GB_ASSERT(value.type != nullptr);
  440. if (is_type_untyped_undef(value.type)) {
  441. Type *t = lb_addr_type(addr);
  442. value.type = t;
  443. value.value = LLVMGetUndef(lb_type(p->module, t));
  444. } else if (is_type_untyped_nil(value.type)) {
  445. Type *t = lb_addr_type(addr);
  446. value.type = t;
  447. value.value = LLVMConstNull(lb_type(p->module, t));
  448. }
  449. if (addr.kind == lbAddr_RelativePointer && addr.relative.deref) {
  450. addr = lb_addr(lb_address_from_load(p, lb_addr_load(p, addr)));
  451. }
  452. if (addr.kind == lbAddr_RelativePointer) {
  453. Type *rel_ptr = base_type(lb_addr_type(addr));
  454. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  455. value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type);
  456. GB_ASSERT(is_type_pointer(addr.addr.type));
  457. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  458. lbValue val_ptr = lb_emit_conv(p, value, t_uintptr);
  459. lbValue offset = {};
  460. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  461. offset.type = t_uintptr;
  462. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  463. offset = lb_emit_conv(p, offset, t_i64);
  464. }
  465. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  466. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  467. offset = lb_emit_select(p,
  468. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  469. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  470. offset
  471. );
  472. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  473. return;
  474. } else if (addr.kind == lbAddr_RelativeSlice) {
  475. Type *rel_ptr = base_type(lb_addr_type(addr));
  476. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  477. value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type);
  478. GB_ASSERT(is_type_pointer(addr.addr.type));
  479. lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr);
  480. lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr);
  481. lbValue offset = {};
  482. offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, "");
  483. offset.type = t_uintptr;
  484. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  485. offset = lb_emit_conv(p, offset, t_i64);
  486. }
  487. offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer);
  488. lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  489. offset = lb_emit_select(p,
  490. lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)),
  491. lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer),
  492. offset
  493. );
  494. LLVMBuildStore(p->builder, offset.value, offset_ptr.value);
  495. lbValue len = lb_slice_len(p, value);
  496. len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer);
  497. lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1);
  498. LLVMBuildStore(p->builder, len.value, len_ptr.value);
  499. return;
  500. } else if (addr.kind == lbAddr_Map) {
  501. lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value, p->curr_stmt);
  502. return;
  503. } else if (addr.kind == lbAddr_Context) {
  504. lbAddr old_addr = lb_find_or_generate_context_ptr(p);
  505. // IMPORTANT NOTE(bill, 2021-04-22): reuse unused 'context' variables to minimize stack usage
  506. // This has to be done manually since the optimizer cannot determine when this is possible
  507. bool create_new = true;
  508. for_array(i, p->context_stack) {
  509. lbContextData *ctx_data = &p->context_stack[i];
  510. if (ctx_data->ctx.addr.value == old_addr.addr.value) {
  511. if (ctx_data->uses > 0) {
  512. create_new = true;
  513. } else if (p->scope_index > ctx_data->scope_index) {
  514. create_new = true;
  515. } else {
  516. // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses);
  517. create_new = false;
  518. }
  519. break;
  520. }
  521. }
  522. lbValue next = {};
  523. if (create_new) {
  524. lbValue old = lb_addr_load(p, old_addr);
  525. lbAddr next_addr = lb_add_local_generated(p, t_context, true);
  526. lb_addr_store(p, next_addr, old);
  527. lb_push_context_onto_stack(p, next_addr);
  528. next = next_addr.addr;
  529. } else {
  530. next = old_addr.addr;
  531. }
  532. if (addr.ctx.sel.index.count > 0) {
  533. lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel);
  534. lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type));
  535. lb_emit_store(p, lhs, rhs);
  536. } else {
  537. lbValue lhs = next;
  538. lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr));
  539. lb_emit_store(p, lhs, rhs);
  540. }
  541. return;
  542. } else if (addr.kind == lbAddr_SoaVariable) {
  543. Type *t = type_deref(addr.addr.type);
  544. t = base_type(t);
  545. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  546. Type *elem_type = t->Struct.soa_elem;
  547. value = lb_emit_conv(p, value, elem_type);
  548. elem_type = base_type(elem_type);
  549. lbValue index = addr.soa.index;
  550. if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) {
  551. Type *t = base_type(type_deref(addr.addr.type));
  552. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  553. lbValue len = lb_soa_struct_len(p, addr.addr);
  554. if (addr.soa.index_expr != nullptr) {
  555. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len);
  556. }
  557. }
  558. isize field_count = 0;
  559. switch (elem_type->kind) {
  560. case Type_Struct:
  561. field_count = elem_type->Struct.fields.count;
  562. break;
  563. case Type_Array:
  564. field_count = cast(isize)elem_type->Array.count;
  565. break;
  566. }
  567. for (isize i = 0; i < field_count; i++) {
  568. lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  569. lbValue src = lb_emit_struct_ev(p, value, cast(i32)i);
  570. if (t->Struct.soa_kind == StructSoa_Fixed) {
  571. dst = lb_emit_array_ep(p, dst, index);
  572. lb_emit_store(p, dst, src);
  573. } else {
  574. lbValue field = lb_emit_load(p, dst);
  575. dst = lb_emit_ptr_offset(p, field, index);
  576. lb_emit_store(p, dst, src);
  577. }
  578. }
  579. return;
  580. } else if (addr.kind == lbAddr_Swizzle) {
  581. GB_ASSERT(addr.swizzle.count <= 4);
  582. GB_ASSERT(value.value != nullptr);
  583. value = lb_emit_conv(p, value, lb_addr_type(addr));
  584. lbValue dst = lb_addr_get_ptr(p, addr);
  585. lbValue src = lb_address_from_load_or_generate_local(p, value);
  586. {
  587. lbValue src_ptrs[4] = {};
  588. lbValue src_loads[4] = {};
  589. lbValue dst_ptrs[4] = {};
  590. for (u8 i = 0; i < addr.swizzle.count; i++) {
  591. src_ptrs[i] = lb_emit_array_epi(p, src, i);
  592. }
  593. for (u8 i = 0; i < addr.swizzle.count; i++) {
  594. dst_ptrs[i] = lb_emit_array_epi(p, dst, addr.swizzle.indices[i]);
  595. }
  596. for (u8 i = 0; i < addr.swizzle.count; i++) {
  597. src_loads[i] = lb_emit_load(p, src_ptrs[i]);
  598. }
  599. for (u8 i = 0; i < addr.swizzle.count; i++) {
  600. lb_emit_store(p, dst_ptrs[i], src_loads[i]);
  601. }
  602. }
  603. return;
  604. } else if (addr.kind == lbAddr_SwizzleLarge) {
  605. GB_ASSERT(value.value != nullptr);
  606. value = lb_emit_conv(p, value, lb_addr_type(addr));
  607. lbValue dst = lb_addr_get_ptr(p, addr);
  608. lbValue src = lb_address_from_load_or_generate_local(p, value);
  609. for_array(i, addr.swizzle_large.indices) {
  610. lbValue src_ptr = lb_emit_array_epi(p, src, i);
  611. lbValue dst_ptr = lb_emit_array_epi(p, dst, addr.swizzle_large.indices[i]);
  612. lbValue src_load = lb_emit_load(p, src_ptr);
  613. lb_emit_store(p, dst_ptr, src_load);
  614. }
  615. return;
  616. }
  617. GB_ASSERT(value.value != nullptr);
  618. value = lb_emit_conv(p, value, lb_addr_type(addr));
  619. // if (lb_is_const_or_global(value)) {
  620. // // NOTE(bill): Just bypass the actual storage and set the initializer
  621. // if (LLVMGetValueKind(addr.addr.value) == LLVMGlobalVariableValueKind) {
  622. // LLVMValueRef dst = addr.addr.value;
  623. // LLVMValueRef src = value.value;
  624. // LLVMSetInitializer(dst, src);
  625. // return;
  626. // }
  627. // }
  628. lb_emit_store(p, addr.addr, value);
  629. }
  630. void lb_const_store(lbValue ptr, lbValue value) {
  631. GB_ASSERT(lb_is_const(ptr));
  632. GB_ASSERT(lb_is_const(value));
  633. GB_ASSERT(is_type_pointer(ptr.type));
  634. LLVMSetInitializer(ptr.value, value.value);
  635. }
  636. bool lb_is_type_proc_recursive(Type *t) {
  637. for (;;) {
  638. if (t == nullptr) {
  639. return false;
  640. }
  641. switch (t->kind) {
  642. case Type_Named:
  643. t = t->Named.base;
  644. break;
  645. case Type_Pointer:
  646. t = t->Pointer.elem;
  647. break;
  648. case Type_Array:
  649. t = t->Array.elem;
  650. break;
  651. case Type_EnumeratedArray:
  652. t = t->EnumeratedArray.elem;
  653. break;
  654. case Type_Slice:
  655. t = t->Slice.elem;
  656. break;
  657. case Type_DynamicArray:
  658. t = t->DynamicArray.elem;
  659. break;
  660. case Type_Proc:
  661. return true;
  662. default:
  663. return false;
  664. }
  665. }
  666. }
  667. void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) {
  668. GB_ASSERT(value.value != nullptr);
  669. Type *a = type_deref(ptr.type);
  670. if (is_type_boolean(a)) {
  671. // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily)
  672. value = lb_emit_conv(p, value, a);
  673. }
  674. Type *ca = core_type(a);
  675. if (ca->kind == Type_Basic) {
  676. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  677. }
  678. if (lb_is_type_proc_recursive(a)) {
  679. // NOTE(bill, 2020-11-11): Because of certain LLVM rules, a procedure value may be
  680. // stored as regular pointer with no procedure information
  681. LLVMTypeRef src_t = LLVMGetElementType(LLVMTypeOf(ptr.value));
  682. LLVMValueRef v = LLVMBuildPointerCast(p->builder, value.value, src_t, "");
  683. LLVMBuildStore(p->builder, v, ptr.value);
  684. } else {
  685. Type *ca = core_type(a);
  686. if (ca->kind == Type_Basic || ca->kind == Type_Proc) {
  687. GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type));
  688. } else {
  689. GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type));
  690. }
  691. LLVMBuildStore(p->builder, value.value, ptr.value);
  692. }
  693. }
  694. LLVMTypeRef llvm_addr_type(lbValue addr_val) {
  695. return LLVMGetElementType(LLVMTypeOf(addr_val.value));
  696. }
  697. lbValue lb_emit_load(lbProcedure *p, lbValue value) {
  698. GB_ASSERT(value.value != nullptr);
  699. if (is_type_multi_pointer(value.type)) {
  700. Type *vt = base_type(value.type);
  701. GB_ASSERT(vt->kind == Type_MultiPointer);
  702. Type *t = vt->MultiPointer.elem;
  703. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  704. return lbValue{v, t};
  705. }
  706. GB_ASSERT(is_type_pointer(value.type));
  707. Type *t = type_deref(value.type);
  708. LLVMValueRef v = LLVMBuildLoad2(p->builder, llvm_addr_type(value), value.value, "");
  709. return lbValue{v, t};
  710. }
  711. lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) {
  712. GB_ASSERT(addr.addr.value != nullptr);
  713. if (addr.kind == lbAddr_RelativePointer) {
  714. Type *rel_ptr = base_type(lb_addr_type(addr));
  715. GB_ASSERT(rel_ptr->kind == Type_RelativePointer);
  716. lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr);
  717. lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer));
  718. offset = lb_emit_load(p, offset);
  719. if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) {
  720. offset = lb_emit_conv(p, offset, t_i64);
  721. }
  722. offset = lb_emit_conv(p, offset, t_uintptr);
  723. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  724. absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type);
  725. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer));
  726. // NOTE(bill): nil check
  727. lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type);
  728. lbValue final_ptr = {};
  729. final_ptr.type = absolute_ptr.type;
  730. final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  731. return lb_emit_load(p, final_ptr);
  732. } else if (addr.kind == lbAddr_RelativeSlice) {
  733. Type *rel_ptr = base_type(lb_addr_type(addr));
  734. GB_ASSERT(rel_ptr->kind == Type_RelativeSlice);
  735. lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0);
  736. lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr);
  737. lbValue offset = lb_emit_load(p, offset_ptr);
  738. if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) {
  739. offset = lb_emit_conv(p, offset, t_i64);
  740. }
  741. offset = lb_emit_conv(p, offset, t_uintptr);
  742. lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr);
  743. Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type);
  744. GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice);
  745. Type *slice_elem = slice_type->Slice.elem;
  746. Type *slice_elem_ptr = alloc_type_pointer(slice_elem);
  747. absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr);
  748. lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer));
  749. // NOTE(bill): nil check
  750. lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr);
  751. lbValue data = {};
  752. data.type = absolute_ptr.type;
  753. data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, "");
  754. lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1));
  755. len = lb_emit_conv(p, len, t_int);
  756. lbAddr slice = lb_add_local_generated(p, slice_type, false);
  757. lb_fill_slice(p, slice, data, len);
  758. return lb_addr_load(p, slice);
  759. } else if (addr.kind == lbAddr_Map) {
  760. Type *map_type = base_type(addr.map.type);
  761. lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true);
  762. lbValue h = lb_gen_map_header(p, addr.addr, map_type);
  763. lbValue key = lb_gen_map_hash(p, addr.map.key, map_type->Map.key);
  764. auto args = array_make<lbValue>(permanent_allocator(), 2);
  765. args[0] = h;
  766. args[1] = key;
  767. lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args);
  768. lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool);
  769. lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok);
  770. lbBlock *then = lb_create_block(p, "map.get.then");
  771. lbBlock *done = lb_create_block(p, "map.get.done");
  772. lb_emit_if(p, ok, then, done);
  773. lb_start_block(p, then);
  774. {
  775. // TODO(bill): mem copy it instead?
  776. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  777. lbValue value = lb_emit_conv(p, ptr, gep0.type);
  778. lb_emit_store(p, gep0, lb_emit_load(p, value));
  779. }
  780. lb_emit_jump(p, done);
  781. lb_start_block(p, done);
  782. if (is_type_tuple(addr.map.result)) {
  783. return lb_addr_load(p, v);
  784. } else {
  785. lbValue single = lb_emit_struct_ep(p, v.addr, 0);
  786. return lb_emit_load(p, single);
  787. }
  788. } else if (addr.kind == lbAddr_Context) {
  789. lbValue a = addr.addr;
  790. for_array(i, p->context_stack) {
  791. lbContextData *ctx_data = &p->context_stack[i];
  792. if (ctx_data->ctx.addr.value == a.value) {
  793. ctx_data->uses += 1;
  794. break;
  795. }
  796. }
  797. a.value = LLVMBuildPointerCast(p->builder, a.value, lb_type(p->module, t_context_ptr), "");
  798. if (addr.ctx.sel.index.count > 0) {
  799. lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel);
  800. return lb_emit_load(p, b);
  801. } else {
  802. return lb_emit_load(p, a);
  803. }
  804. } else if (addr.kind == lbAddr_SoaVariable) {
  805. Type *t = type_deref(addr.addr.type);
  806. t = base_type(t);
  807. GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None);
  808. Type *elem = t->Struct.soa_elem;
  809. lbValue len = {};
  810. if (t->Struct.soa_kind == StructSoa_Fixed) {
  811. len = lb_const_int(p->module, t_int, t->Struct.soa_count);
  812. } else {
  813. lbValue v = lb_emit_load(p, addr.addr);
  814. len = lb_soa_struct_len(p, v);
  815. }
  816. lbAddr res = lb_add_local_generated(p, elem, true);
  817. if (addr.soa.index_expr != nullptr && (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed)) {
  818. lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len);
  819. }
  820. if (t->Struct.soa_kind == StructSoa_Fixed) {
  821. for_array(i, t->Struct.fields) {
  822. Entity *field = t->Struct.fields[i];
  823. Type *base_type = field->type;
  824. GB_ASSERT(base_type->kind == Type_Array);
  825. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  826. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  827. src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index);
  828. lbValue src = lb_emit_load(p, src_ptr);
  829. lb_emit_store(p, dst, src);
  830. }
  831. } else {
  832. isize field_count = t->Struct.fields.count;
  833. if (t->Struct.soa_kind == StructSoa_Slice) {
  834. field_count -= 1;
  835. } else if (t->Struct.soa_kind == StructSoa_Dynamic) {
  836. field_count -= 3;
  837. }
  838. for (isize i = 0; i < field_count; i++) {
  839. Entity *field = t->Struct.fields[i];
  840. Type *base_type = field->type;
  841. GB_ASSERT(base_type->kind == Type_Pointer);
  842. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  843. lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i);
  844. lbValue src = lb_emit_load(p, src_ptr);
  845. src = lb_emit_ptr_offset(p, src, addr.soa.index);
  846. src = lb_emit_load(p, src);
  847. lb_emit_store(p, dst, src);
  848. }
  849. }
  850. return lb_addr_load(p, res);
  851. } else if (addr.kind == lbAddr_Swizzle) {
  852. Type *array_type = base_type(addr.swizzle.type);
  853. GB_ASSERT(array_type->kind == Type_Array);
  854. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle.type);
  855. static u8 const ordered_indices[4] = {0, 1, 2, 3};
  856. if (gb_memcompare(ordered_indices, addr.swizzle.indices, addr.swizzle.count) == 0) {
  857. if (lb_try_update_alignment(addr.addr, res_align)) {
  858. Type *pt = alloc_type_pointer(addr.swizzle.type);
  859. lbValue res = {};
  860. res.value = LLVMBuildPointerCast(p->builder, addr.addr.value, lb_type(p->module, pt), "");
  861. res.type = pt;
  862. return lb_emit_load(p, res);
  863. }
  864. }
  865. lbAddr res = lb_add_local_generated(p, addr.swizzle.type, false);
  866. lbValue ptr = lb_addr_get_ptr(p, res);
  867. GB_ASSERT(is_type_pointer(ptr.type));
  868. LLVMTypeRef vector_type = nullptr;
  869. if (lb_try_vector_cast(p->module, addr.addr, &vector_type)) {
  870. LLVMSetAlignment(res.addr.value, cast(unsigned)lb_alignof(vector_type));
  871. LLVMValueRef vp = LLVMBuildPointerCast(p->builder, addr.addr.value, LLVMPointerType(vector_type, 0), "");
  872. LLVMValueRef v = LLVMBuildLoad2(p->builder, vector_type, vp, "");
  873. LLVMValueRef scalars[4] = {};
  874. for (u8 i = 0; i < addr.swizzle.count; i++) {
  875. scalars[i] = LLVMConstInt(lb_type(p->module, t_u32), addr.swizzle.indices[i], false);
  876. }
  877. LLVMValueRef mask = LLVMConstVector(scalars, addr.swizzle.count);
  878. LLVMValueRef sv = LLVMBuildShuffleVector(p->builder, v, LLVMGetUndef(vector_type), mask, "");
  879. LLVMValueRef dst = LLVMBuildPointerCast(p->builder, ptr.value, LLVMPointerType(LLVMTypeOf(sv), 0), "");
  880. LLVMBuildStore(p->builder, sv, dst);
  881. } else {
  882. for (u8 i = 0; i < addr.swizzle.count; i++) {
  883. u8 index = addr.swizzle.indices[i];
  884. lbValue dst = lb_emit_array_epi(p, ptr, i);
  885. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  886. lb_emit_store(p, dst, lb_emit_load(p, src));
  887. }
  888. }
  889. return lb_addr_load(p, res);
  890. } else if (addr.kind == lbAddr_SwizzleLarge) {
  891. Type *array_type = base_type(addr.swizzle_large.type);
  892. GB_ASSERT(array_type->kind == Type_Array);
  893. unsigned res_align = cast(unsigned)type_align_of(addr.swizzle_large.type);
  894. gb_unused(res_align);
  895. lbAddr res = lb_add_local_generated(p, addr.swizzle_large.type, false);
  896. lbValue ptr = lb_addr_get_ptr(p, res);
  897. GB_ASSERT(is_type_pointer(ptr.type));
  898. for_array(i, addr.swizzle_large.indices) {
  899. i32 index = addr.swizzle_large.indices[i];
  900. lbValue dst = lb_emit_array_epi(p, ptr, i);
  901. lbValue src = lb_emit_array_epi(p, addr.addr, index);
  902. lb_emit_store(p, dst, lb_emit_load(p, src));
  903. }
  904. return lb_addr_load(p, res);
  905. }
  906. if (is_type_proc(addr.addr.type)) {
  907. return addr.addr;
  908. }
  909. return lb_emit_load(p, addr.addr);
  910. }
  911. lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) {
  912. return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v)));
  913. }
  914. lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) {
  915. Type *t = u.type;
  916. GB_ASSERT_MSG(is_type_pointer(t) &&
  917. is_type_union(type_deref(t)), "%s", type_to_string(t));
  918. Type *ut = type_deref(t);
  919. GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut));
  920. GB_ASSERT(!is_type_union_maybe_pointer(ut));
  921. GB_ASSERT(type_size_of(ut) > 0);
  922. Type *tag_type = union_tag_type(ut);
  923. LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value));
  924. unsigned element_count = LLVMCountStructElementTypes(uvt);
  925. GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt));
  926. lbValue tag_ptr = {};
  927. tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, "");
  928. tag_ptr.type = alloc_type_pointer(tag_type);
  929. return tag_ptr;
  930. }
  931. lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) {
  932. lbValue ptr = lb_address_from_load_or_generate_local(p, u);
  933. lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr);
  934. return lb_emit_load(p, tag_ptr);
  935. }
  936. void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) {
  937. Type *t = type_deref(parent.type);
  938. if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) {
  939. // No tag needed!
  940. } else {
  941. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent);
  942. lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type));
  943. }
  944. }
  945. void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) {
  946. lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type));
  947. lb_emit_store(p, underlying, variant);
  948. lb_emit_store_union_variant_tag(p, parent, variant_type);
  949. }
  950. void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) {
  951. unsigned field_count = LLVMCountStructElementTypes(src);
  952. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  953. LLVMGetStructElementTypes(src, fields);
  954. LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src));
  955. }
  956. LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) {
  957. switch (alignment) {
  958. case 1:
  959. return LLVMArrayType(lb_type(m, t_u8), 0);
  960. case 2:
  961. return LLVMArrayType(lb_type(m, t_u16), 0);
  962. case 4:
  963. return LLVMArrayType(lb_type(m, t_u32), 0);
  964. case 8:
  965. return LLVMArrayType(lb_type(m, t_u64), 0);
  966. case 16:
  967. return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0);
  968. default:
  969. GB_PANIC("Invalid alignment %d", cast(i32)alignment);
  970. break;
  971. }
  972. return nullptr;
  973. }
  974. String lb_mangle_name(lbModule *m, Entity *e) {
  975. String name = e->token.string;
  976. AstPackage *pkg = e->pkg;
  977. GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name));
  978. String pkgn = pkg->name;
  979. GB_ASSERT(!rune_is_digit(pkgn[0]));
  980. if (pkgn == "llvm") {
  981. pkgn = str_lit("llvm$");
  982. }
  983. isize max_len = pkgn.len + 1 + name.len + 1;
  984. bool require_suffix_id = is_type_polymorphic(e->type, true);
  985. if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) {
  986. require_suffix_id = true;
  987. } else if (is_blank_ident(e->token)) {
  988. require_suffix_id = true;
  989. }if (e->flags & EntityFlag_NotExported) {
  990. require_suffix_id = true;
  991. }
  992. if (require_suffix_id) {
  993. max_len += 21;
  994. }
  995. char *new_name = gb_alloc_array(permanent_allocator(), char, max_len);
  996. isize new_name_len = gb_snprintf(
  997. new_name, max_len,
  998. "%.*s.%.*s", LIT(pkgn), LIT(name)
  999. );
  1000. if (require_suffix_id) {
  1001. char *str = new_name + new_name_len-1;
  1002. isize len = max_len-new_name_len;
  1003. isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id);
  1004. new_name_len += extra-1;
  1005. }
  1006. String mangled_name = make_string((u8 const *)new_name, new_name_len-1);
  1007. return mangled_name;
  1008. }
  1009. String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) {
  1010. // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration
  1011. // and as a result, the declaration does not have time to determine what it should be
  1012. GB_ASSERT(e != nullptr && e->kind == Entity_TypeName);
  1013. if (e->TypeName.ir_mangled_name.len != 0) {
  1014. return e->TypeName.ir_mangled_name;
  1015. }
  1016. GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0);
  1017. if (p == nullptr) {
  1018. Entity *proc = nullptr;
  1019. if (e->parent_proc_decl != nullptr) {
  1020. proc = e->parent_proc_decl->entity;
  1021. } else {
  1022. Scope *scope = e->scope;
  1023. while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) {
  1024. scope = scope->parent;
  1025. }
  1026. GB_ASSERT(scope != nullptr);
  1027. GB_ASSERT(scope->flags & ScopeFlag_Proc);
  1028. proc = scope->procedure_entity;
  1029. }
  1030. GB_ASSERT(proc->kind == Entity_Procedure);
  1031. if (proc->code_gen_procedure != nullptr) {
  1032. p = proc->code_gen_procedure;
  1033. }
  1034. }
  1035. // NOTE(bill): Generate a new name
  1036. // parent_proc.name-guid
  1037. String ts_name = e->token.string;
  1038. if (p != nullptr) {
  1039. isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1;
  1040. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  1041. u32 guid = ++p->module->nested_type_name_guid;
  1042. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid);
  1043. String name = make_string(cast(u8 *)name_text, name_len-1);
  1044. e->TypeName.ir_mangled_name = name;
  1045. return name;
  1046. } else {
  1047. // NOTE(bill): a nested type be required before its parameter procedure exists. Just give it a temp name for now
  1048. isize name_len = 9 + 1 + ts_name.len + 1 + 10 + 1;
  1049. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  1050. static u32 guid = 0;
  1051. guid += 1;
  1052. name_len = gb_snprintf(name_text, name_len, "_internal.%.*s-%u", LIT(ts_name), guid);
  1053. String name = make_string(cast(u8 *)name_text, name_len-1);
  1054. e->TypeName.ir_mangled_name = name;
  1055. return name;
  1056. }
  1057. }
  1058. String lb_get_entity_name(lbModule *m, Entity *e, String default_name) {
  1059. if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) {
  1060. return e->TypeName.ir_mangled_name;
  1061. }
  1062. GB_ASSERT(e != nullptr);
  1063. if (e->pkg == nullptr) {
  1064. return e->token.string;
  1065. }
  1066. if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) {
  1067. return lb_set_nested_type_name_ir_mangled_name(e, nullptr);
  1068. }
  1069. String name = {};
  1070. bool no_name_mangle = false;
  1071. if (e->kind == Entity_Variable) {
  1072. bool is_foreign = e->Variable.is_foreign;
  1073. bool is_export = e->Variable.is_export;
  1074. no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export;
  1075. if (e->Variable.link_name.len > 0) {
  1076. return e->Variable.link_name;
  1077. }
  1078. } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) {
  1079. return e->Procedure.link_name;
  1080. } else if (e->kind == Entity_Procedure && e->Procedure.is_export) {
  1081. no_name_mangle = true;
  1082. }
  1083. if (!no_name_mangle) {
  1084. name = lb_mangle_name(m, e);
  1085. }
  1086. if (name.len == 0) {
  1087. name = e->token.string;
  1088. }
  1089. if (e->kind == Entity_TypeName) {
  1090. e->TypeName.ir_mangled_name = name;
  1091. } else if (e->kind == Entity_Procedure) {
  1092. e->Procedure.link_name = name;
  1093. }
  1094. return name;
  1095. }
  1096. LLVMTypeRef lb_type_internal(lbModule *m, Type *type) {
  1097. LLVMContextRef ctx = m->ctx;
  1098. i64 size = type_size_of(type); // Check size
  1099. gb_unused(size);
  1100. GB_ASSERT(type != t_invalid);
  1101. switch (type->kind) {
  1102. case Type_Basic:
  1103. switch (type->Basic.kind) {
  1104. case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx);
  1105. case Basic_bool: return LLVMInt8TypeInContext(ctx);
  1106. case Basic_b8: return LLVMInt8TypeInContext(ctx);
  1107. case Basic_b16: return LLVMInt16TypeInContext(ctx);
  1108. case Basic_b32: return LLVMInt32TypeInContext(ctx);
  1109. case Basic_b64: return LLVMInt64TypeInContext(ctx);
  1110. case Basic_i8: return LLVMInt8TypeInContext(ctx);
  1111. case Basic_u8: return LLVMInt8TypeInContext(ctx);
  1112. case Basic_i16: return LLVMInt16TypeInContext(ctx);
  1113. case Basic_u16: return LLVMInt16TypeInContext(ctx);
  1114. case Basic_i32: return LLVMInt32TypeInContext(ctx);
  1115. case Basic_u32: return LLVMInt32TypeInContext(ctx);
  1116. case Basic_i64: return LLVMInt64TypeInContext(ctx);
  1117. case Basic_u64: return LLVMInt64TypeInContext(ctx);
  1118. case Basic_i128: return LLVMInt128TypeInContext(ctx);
  1119. case Basic_u128: return LLVMInt128TypeInContext(ctx);
  1120. case Basic_rune: return LLVMInt32TypeInContext(ctx);
  1121. case Basic_f16: return LLVMHalfTypeInContext(ctx);
  1122. case Basic_f32: return LLVMFloatTypeInContext(ctx);
  1123. case Basic_f64: return LLVMDoubleTypeInContext(ctx);
  1124. case Basic_f16le: return LLVMHalfTypeInContext(ctx);
  1125. case Basic_f32le: return LLVMFloatTypeInContext(ctx);
  1126. case Basic_f64le: return LLVMDoubleTypeInContext(ctx);
  1127. case Basic_f16be: return LLVMHalfTypeInContext(ctx);
  1128. case Basic_f32be: return LLVMFloatTypeInContext(ctx);
  1129. case Basic_f64be: return LLVMDoubleTypeInContext(ctx);
  1130. case Basic_complex32:
  1131. {
  1132. char const *name = "..complex32";
  1133. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1134. if (type != nullptr) {
  1135. return type;
  1136. }
  1137. type = LLVMStructCreateNamed(ctx, name);
  1138. LLVMTypeRef fields[2] = {
  1139. lb_type(m, t_f16),
  1140. lb_type(m, t_f16),
  1141. };
  1142. LLVMStructSetBody(type, fields, 2, false);
  1143. return type;
  1144. }
  1145. case Basic_complex64:
  1146. {
  1147. char const *name = "..complex64";
  1148. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1149. if (type != nullptr) {
  1150. return type;
  1151. }
  1152. type = LLVMStructCreateNamed(ctx, name);
  1153. LLVMTypeRef fields[2] = {
  1154. lb_type(m, t_f32),
  1155. lb_type(m, t_f32),
  1156. };
  1157. LLVMStructSetBody(type, fields, 2, false);
  1158. return type;
  1159. }
  1160. case Basic_complex128:
  1161. {
  1162. char const *name = "..complex128";
  1163. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1164. if (type != nullptr) {
  1165. return type;
  1166. }
  1167. type = LLVMStructCreateNamed(ctx, name);
  1168. LLVMTypeRef fields[2] = {
  1169. lb_type(m, t_f64),
  1170. lb_type(m, t_f64),
  1171. };
  1172. LLVMStructSetBody(type, fields, 2, false);
  1173. return type;
  1174. }
  1175. case Basic_quaternion64:
  1176. {
  1177. char const *name = "..quaternion64";
  1178. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1179. if (type != nullptr) {
  1180. return type;
  1181. }
  1182. type = LLVMStructCreateNamed(ctx, name);
  1183. LLVMTypeRef fields[4] = {
  1184. lb_type(m, t_f16),
  1185. lb_type(m, t_f16),
  1186. lb_type(m, t_f16),
  1187. lb_type(m, t_f16),
  1188. };
  1189. LLVMStructSetBody(type, fields, 4, false);
  1190. return type;
  1191. }
  1192. case Basic_quaternion128:
  1193. {
  1194. char const *name = "..quaternion128";
  1195. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1196. if (type != nullptr) {
  1197. return type;
  1198. }
  1199. type = LLVMStructCreateNamed(ctx, name);
  1200. LLVMTypeRef fields[4] = {
  1201. lb_type(m, t_f32),
  1202. lb_type(m, t_f32),
  1203. lb_type(m, t_f32),
  1204. lb_type(m, t_f32),
  1205. };
  1206. LLVMStructSetBody(type, fields, 4, false);
  1207. return type;
  1208. }
  1209. case Basic_quaternion256:
  1210. {
  1211. char const *name = "..quaternion256";
  1212. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1213. if (type != nullptr) {
  1214. return type;
  1215. }
  1216. type = LLVMStructCreateNamed(ctx, name);
  1217. LLVMTypeRef fields[4] = {
  1218. lb_type(m, t_f64),
  1219. lb_type(m, t_f64),
  1220. lb_type(m, t_f64),
  1221. lb_type(m, t_f64),
  1222. };
  1223. LLVMStructSetBody(type, fields, 4, false);
  1224. return type;
  1225. }
  1226. case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1227. case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1228. case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size);
  1229. case Basic_rawptr: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1230. case Basic_string:
  1231. {
  1232. char const *name = "..string";
  1233. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1234. if (type != nullptr) {
  1235. return type;
  1236. }
  1237. type = LLVMStructCreateNamed(ctx, name);
  1238. LLVMTypeRef fields[2] = {
  1239. LLVMPointerType(lb_type(m, t_u8), 0),
  1240. lb_type(m, t_int),
  1241. };
  1242. LLVMStructSetBody(type, fields, 2, false);
  1243. return type;
  1244. }
  1245. case Basic_cstring: return LLVMPointerType(LLVMInt8TypeInContext(ctx), 0);
  1246. case Basic_any:
  1247. {
  1248. char const *name = "..any";
  1249. LLVMTypeRef type = LLVMGetTypeByName(m->mod, name);
  1250. if (type != nullptr) {
  1251. return type;
  1252. }
  1253. type = LLVMStructCreateNamed(ctx, name);
  1254. LLVMTypeRef fields[2] = {
  1255. lb_type(m, t_rawptr),
  1256. lb_type(m, t_typeid),
  1257. };
  1258. LLVMStructSetBody(type, fields, 2, false);
  1259. return type;
  1260. }
  1261. case Basic_typeid: return LLVMIntTypeInContext(m->ctx, 8*cast(unsigned)build_context.word_size);
  1262. // Endian Specific Types
  1263. case Basic_i16le: return LLVMInt16TypeInContext(ctx);
  1264. case Basic_u16le: return LLVMInt16TypeInContext(ctx);
  1265. case Basic_i32le: return LLVMInt32TypeInContext(ctx);
  1266. case Basic_u32le: return LLVMInt32TypeInContext(ctx);
  1267. case Basic_i64le: return LLVMInt64TypeInContext(ctx);
  1268. case Basic_u64le: return LLVMInt64TypeInContext(ctx);
  1269. case Basic_i128le: return LLVMInt128TypeInContext(ctx);
  1270. case Basic_u128le: return LLVMInt128TypeInContext(ctx);
  1271. case Basic_i16be: return LLVMInt16TypeInContext(ctx);
  1272. case Basic_u16be: return LLVMInt16TypeInContext(ctx);
  1273. case Basic_i32be: return LLVMInt32TypeInContext(ctx);
  1274. case Basic_u32be: return LLVMInt32TypeInContext(ctx);
  1275. case Basic_i64be: return LLVMInt64TypeInContext(ctx);
  1276. case Basic_u64be: return LLVMInt64TypeInContext(ctx);
  1277. case Basic_i128be: return LLVMInt128TypeInContext(ctx);
  1278. case Basic_u128be: return LLVMInt128TypeInContext(ctx);
  1279. // Untyped types
  1280. case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break;
  1281. case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break;
  1282. case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break;
  1283. case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break;
  1284. case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break;
  1285. case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break;
  1286. case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break;
  1287. case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break;
  1288. case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break;
  1289. }
  1290. break;
  1291. case Type_Named:
  1292. {
  1293. Type *base = base_type(type->Named.base);
  1294. switch (base->kind) {
  1295. case Type_Basic:
  1296. return lb_type_internal(m, base);
  1297. case Type_Named:
  1298. case Type_Generic:
  1299. GB_PANIC("INVALID TYPE");
  1300. break;
  1301. case Type_Pointer:
  1302. case Type_Array:
  1303. case Type_EnumeratedArray:
  1304. case Type_Slice:
  1305. case Type_DynamicArray:
  1306. case Type_Map:
  1307. case Type_Enum:
  1308. case Type_BitSet:
  1309. case Type_SimdVector:
  1310. return lb_type_internal(m, base);
  1311. // TODO(bill): Deal with this correctly. Can this be named?
  1312. case Type_Proc:
  1313. return lb_type_internal(m, base);
  1314. case Type_Tuple:
  1315. return lb_type_internal(m, base);
  1316. }
  1317. LLVMTypeRef *found = map_get(&m->types, hash_type(base));
  1318. if (found) {
  1319. LLVMTypeKind kind = LLVMGetTypeKind(*found);
  1320. if (kind == LLVMStructTypeKind) {
  1321. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1322. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1323. if (llvm_type != nullptr) {
  1324. return llvm_type;
  1325. }
  1326. llvm_type = LLVMStructCreateNamed(ctx, name);
  1327. map_set(&m->types, hash_type(type), llvm_type);
  1328. lb_clone_struct_type(llvm_type, *found);
  1329. return llvm_type;
  1330. }
  1331. }
  1332. switch (base->kind) {
  1333. case Type_Struct:
  1334. case Type_Union:
  1335. {
  1336. char const *name = alloc_cstring(permanent_allocator(), lb_get_entity_name(m, type->Named.type_name));
  1337. LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name);
  1338. if (llvm_type != nullptr) {
  1339. return llvm_type;
  1340. }
  1341. llvm_type = LLVMStructCreateNamed(ctx, name);
  1342. map_set(&m->types, hash_type(type), llvm_type);
  1343. lb_clone_struct_type(llvm_type, lb_type(m, base));
  1344. return llvm_type;
  1345. }
  1346. }
  1347. return lb_type_internal(m, base);
  1348. }
  1349. case Type_Pointer:
  1350. return LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  1351. case Type_MultiPointer:
  1352. return LLVMPointerType(lb_type(m, type->Pointer.elem), 0);
  1353. case Type_Array: {
  1354. m->internal_type_level -= 1;
  1355. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count);
  1356. m->internal_type_level += 1;
  1357. return t;
  1358. }
  1359. case Type_EnumeratedArray: {
  1360. m->internal_type_level -= 1;
  1361. LLVMTypeRef t = LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count);
  1362. m->internal_type_level += 1;
  1363. return t;
  1364. }
  1365. case Type_Slice:
  1366. {
  1367. LLVMTypeRef fields[2] = {
  1368. LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data
  1369. lb_type(m, t_int), // len
  1370. };
  1371. return LLVMStructTypeInContext(ctx, fields, 2, false);
  1372. }
  1373. break;
  1374. case Type_DynamicArray:
  1375. {
  1376. LLVMTypeRef fields[4] = {
  1377. LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data
  1378. lb_type(m, t_int), // len
  1379. lb_type(m, t_int), // cap
  1380. lb_type(m, t_allocator), // allocator
  1381. };
  1382. return LLVMStructTypeInContext(ctx, fields, 4, false);
  1383. }
  1384. break;
  1385. case Type_Map:
  1386. init_map_internal_types(type);
  1387. {
  1388. Type *internal_type = type->Map.internal_type;
  1389. GB_ASSERT(internal_type->kind == Type_Struct);
  1390. m->internal_type_level -= 1;
  1391. defer (m->internal_type_level += 1);
  1392. unsigned field_count = cast(unsigned)(internal_type->Struct.fields.count);
  1393. GB_ASSERT(field_count == 2);
  1394. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1395. LLVMTypeRef entries_fields[4] = {
  1396. lb_type(m, t_rawptr),
  1397. lb_type(m, t_int), // len
  1398. lb_type(m, t_int), // cap
  1399. lb_type(m, t_allocator), // allocator
  1400. };
  1401. fields[0] = lb_type(m, internal_type->Struct.fields[0]->type);
  1402. fields[1] = LLVMStructTypeInContext(ctx, entries_fields, gb_count_of(entries_fields), false);
  1403. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1404. }
  1405. case Type_Struct:
  1406. {
  1407. if (type->Struct.is_raw_union) {
  1408. unsigned field_count = 2;
  1409. LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count);
  1410. i64 alignment = type_align_of(type);
  1411. unsigned size_of_union = cast(unsigned)type_size_of(type);
  1412. fields[0] = lb_alignment_prefix_type_hack(m, alignment);
  1413. fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union);
  1414. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1415. }
  1416. isize offset = 0;
  1417. if (type->Struct.custom_align > 0) {
  1418. offset = 1;
  1419. }
  1420. m->internal_type_level += 1;
  1421. defer (m->internal_type_level -= 1);
  1422. unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset);
  1423. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1424. for_array(i, type->Struct.fields) {
  1425. Entity *field = type->Struct.fields[i];
  1426. fields[i+offset] = lb_type(m, field->type);
  1427. }
  1428. if (type->Struct.custom_align > 0) {
  1429. fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align);
  1430. }
  1431. return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed);
  1432. }
  1433. break;
  1434. case Type_Union:
  1435. if (type->Union.variants.count == 0) {
  1436. return LLVMStructTypeInContext(ctx, nullptr, 0, false);
  1437. } else {
  1438. // NOTE(bill): The zero size array is used to fix the alignment used in a structure as
  1439. // LLVM takes the first element's alignment as the entire alignment (like C)
  1440. i64 align = type_align_of(type);
  1441. i64 size = type_size_of(type);
  1442. gb_unused(size);
  1443. if (is_type_union_maybe_pointer_original_alignment(type)) {
  1444. LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])};
  1445. return LLVMStructTypeInContext(ctx, fields, 1, false);
  1446. }
  1447. unsigned block_size = cast(unsigned)type->Union.variant_block_size;
  1448. LLVMTypeRef fields[3] = {};
  1449. unsigned field_count = 1;
  1450. fields[0] = lb_alignment_prefix_type_hack(m, align);
  1451. if (is_type_union_maybe_pointer(type)) {
  1452. field_count += 1;
  1453. fields[1] = lb_type(m, type->Union.variants[0]);
  1454. } else {
  1455. field_count += 2;
  1456. if (block_size == align) {
  1457. fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size);
  1458. } else {
  1459. fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size);
  1460. }
  1461. fields[2] = lb_type(m, union_tag_type(type));
  1462. }
  1463. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1464. }
  1465. break;
  1466. case Type_Enum:
  1467. return lb_type(m, base_enum_type(type));
  1468. case Type_Tuple:
  1469. if (type->Tuple.variables.count == 1) {
  1470. return lb_type(m, type->Tuple.variables[0]->type);
  1471. } else {
  1472. m->internal_type_level += 1;
  1473. defer (m->internal_type_level -= 1);
  1474. unsigned field_count = cast(unsigned)(type->Tuple.variables.count);
  1475. LLVMTypeRef *fields = gb_alloc_array(temporary_allocator(), LLVMTypeRef, field_count);
  1476. for_array(i, type->Tuple.variables) {
  1477. Entity *field = type->Tuple.variables[i];
  1478. LLVMTypeRef param_type = nullptr;
  1479. param_type = lb_type(m, field->type);
  1480. fields[i] = param_type;
  1481. }
  1482. return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed);
  1483. }
  1484. case Type_Proc:
  1485. // if (m->internal_type_level > 256) { // TODO HACK(bill): is this really enough?
  1486. if (m->internal_type_level > 1) { // TODO HACK(bill): is this really enough?
  1487. return LLVMPointerType(LLVMIntTypeInContext(m->ctx, 8), 0);
  1488. } else {
  1489. unsigned param_count = 0;
  1490. if (type->Proc.calling_convention == ProcCC_Odin) {
  1491. param_count += 1;
  1492. }
  1493. if (type->Proc.param_count != 0) {
  1494. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1495. for_array(i, type->Proc.params->Tuple.variables) {
  1496. Entity *e = type->Proc.params->Tuple.variables[i];
  1497. if (e->kind != Entity_Variable) {
  1498. continue;
  1499. }
  1500. if (e->flags & EntityFlag_CVarArg) {
  1501. continue;
  1502. }
  1503. param_count += 1;
  1504. }
  1505. }
  1506. m->internal_type_level += 1;
  1507. defer (m->internal_type_level -= 1);
  1508. LLVMTypeRef ret = nullptr;
  1509. LLVMTypeRef *params = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count);
  1510. if (type->Proc.result_count != 0) {
  1511. Type *single_ret = reduce_tuple_to_single_type(type->Proc.results);
  1512. ret = lb_type(m, single_ret);
  1513. if (ret != nullptr) {
  1514. if (is_type_boolean(single_ret) &&
  1515. is_calling_convention_none(type->Proc.calling_convention) &&
  1516. type_size_of(single_ret) <= 1) {
  1517. ret = LLVMInt1TypeInContext(m->ctx);
  1518. }
  1519. }
  1520. }
  1521. unsigned param_index = 0;
  1522. if (type->Proc.param_count != 0) {
  1523. GB_ASSERT(type->Proc.params->kind == Type_Tuple);
  1524. for_array(i, type->Proc.params->Tuple.variables) {
  1525. Entity *e = type->Proc.params->Tuple.variables[i];
  1526. if (e->kind != Entity_Variable) {
  1527. continue;
  1528. }
  1529. if (e->flags & EntityFlag_CVarArg) {
  1530. continue;
  1531. }
  1532. Type *e_type = reduce_tuple_to_single_type(e->type);
  1533. LLVMTypeRef param_type = nullptr;
  1534. if (is_type_boolean(e_type) &&
  1535. type_size_of(e_type) <= 1) {
  1536. param_type = LLVMInt1TypeInContext(m->ctx);
  1537. } else {
  1538. if (is_type_proc(e_type)) {
  1539. param_type = lb_type(m, t_rawptr);
  1540. } else {
  1541. param_type = lb_type(m, e_type);
  1542. }
  1543. }
  1544. params[param_index++] = param_type;
  1545. }
  1546. }
  1547. if (param_index < param_count) {
  1548. params[param_index++] = lb_type(m, t_rawptr);
  1549. }
  1550. GB_ASSERT(param_index == param_count);
  1551. lbFunctionType *ft = lb_get_abi_info(m->ctx, params, param_count, ret, ret != nullptr, type->Proc.calling_convention);
  1552. {
  1553. for_array(j, ft->args) {
  1554. auto arg = ft->args[j];
  1555. GB_ASSERT_MSG(LLVMGetTypeContext(arg.type) == ft->ctx,
  1556. "\n\t%s %td/%td"
  1557. "\n\tArgTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1558. LLVMPrintTypeToString(arg.type),
  1559. j, ft->args.count,
  1560. LLVMGetTypeContext(arg.type), ft->ctx, LLVMGetGlobalContext());
  1561. }
  1562. GB_ASSERT_MSG(LLVMGetTypeContext(ft->ret.type) == ft->ctx,
  1563. "\n\t%s"
  1564. "\n\tRetTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1565. LLVMPrintTypeToString(ft->ret.type),
  1566. LLVMGetTypeContext(ft->ret.type), ft->ctx, LLVMGetGlobalContext());
  1567. }
  1568. map_set(&m->function_type_map, hash_type(type), ft);
  1569. LLVMTypeRef new_abi_fn_ptr_type = lb_function_type_to_llvm_ptr(ft, type->Proc.c_vararg);
  1570. LLVMTypeRef new_abi_fn_type = LLVMGetElementType(new_abi_fn_ptr_type);
  1571. GB_ASSERT_MSG(LLVMGetTypeContext(new_abi_fn_type) == m->ctx,
  1572. "\n\tFuncTypeCtx: %p\n\tCurrentCtx: %p\n\tGlobalCtx: %p",
  1573. LLVMGetTypeContext(new_abi_fn_type), m->ctx, LLVMGetGlobalContext());
  1574. return new_abi_fn_ptr_type;
  1575. }
  1576. break;
  1577. case Type_BitSet:
  1578. {
  1579. Type *ut = bit_set_to_int(type);
  1580. return lb_type(m, ut);
  1581. }
  1582. case Type_SimdVector:
  1583. return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count);
  1584. case Type_RelativePointer:
  1585. return lb_type_internal(m, type->RelativePointer.base_integer);
  1586. case Type_RelativeSlice:
  1587. {
  1588. LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer);
  1589. unsigned field_count = 2;
  1590. LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count);
  1591. fields[0] = base_integer;
  1592. fields[1] = base_integer;
  1593. return LLVMStructTypeInContext(ctx, fields, field_count, false);
  1594. }
  1595. }
  1596. GB_PANIC("Invalid type %s", type_to_string(type));
  1597. return LLVMInt32TypeInContext(ctx);
  1598. }
  1599. LLVMTypeRef lb_type(lbModule *m, Type *type) {
  1600. type = default_type(type);
  1601. LLVMTypeRef *found = map_get(&m->types, hash_type(type));
  1602. if (found) {
  1603. return *found;
  1604. }
  1605. LLVMTypeRef llvm_type = nullptr;
  1606. m->internal_type_level += 1;
  1607. llvm_type = lb_type_internal(m, type);
  1608. m->internal_type_level -= 1;
  1609. if (m->internal_type_level == 0) {
  1610. map_set(&m->types, hash_type(type), llvm_type);
  1611. if (is_type_named(type)) {
  1612. map_set(&m->llvm_types, hash_pointer(llvm_type), type);
  1613. }
  1614. }
  1615. return llvm_type;
  1616. }
  1617. lbFunctionType *lb_get_function_type(lbModule *m, lbProcedure *p, Type *pt) {
  1618. lbFunctionType **ft_found = nullptr;
  1619. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1620. if (!ft_found) {
  1621. LLVMTypeRef llvm_proc_type = lb_type(p->module, pt);
  1622. gb_unused(llvm_proc_type);
  1623. ft_found = map_get(&m->function_type_map, hash_type(pt));
  1624. }
  1625. GB_ASSERT(ft_found != nullptr);
  1626. return *ft_found;
  1627. }
  1628. void lb_ensure_abi_function_type(lbModule *m, lbProcedure *p) {
  1629. if (p->abi_function_type != nullptr) {
  1630. return;
  1631. }
  1632. auto hash = hash_type(p->type);
  1633. lbFunctionType **ft_found = map_get(&m->function_type_map, hash);
  1634. if (ft_found == nullptr) {
  1635. LLVMTypeRef llvm_proc_type = lb_type(p->module, p->type);
  1636. gb_unused(llvm_proc_type);
  1637. ft_found = map_get(&m->function_type_map, hash);
  1638. }
  1639. GB_ASSERT(ft_found != nullptr);
  1640. p->abi_function_type = *ft_found;
  1641. GB_ASSERT(p->abi_function_type != nullptr);
  1642. }
  1643. void lb_add_entity(lbModule *m, Entity *e, lbValue val) {
  1644. if (e != nullptr) {
  1645. map_set(&m->values, hash_entity(e), val);
  1646. }
  1647. }
  1648. void lb_add_member(lbModule *m, String const &name, lbValue val) {
  1649. if (name.len > 0) {
  1650. string_map_set(&m->members, name, val);
  1651. }
  1652. }
  1653. void lb_add_member(lbModule *m, StringHashKey const &key, lbValue val) {
  1654. string_map_set(&m->members, key, val);
  1655. }
  1656. void lb_add_procedure_value(lbModule *m, lbProcedure *p) {
  1657. if (p->entity != nullptr) {
  1658. map_set(&m->procedure_values, hash_pointer(p->value), p->entity);
  1659. }
  1660. string_map_set(&m->procedures, p->name, p);
  1661. }
  1662. LLVMAttributeRef lb_create_enum_attribute_with_type(LLVMContextRef ctx, char const *name, LLVMTypeRef type) {
  1663. unsigned kind = 0;
  1664. String s = make_string_c(name);
  1665. #if (LLVM_VERSION_MAJOR > 12 || (LLVM_VERSION_MAJOR == 12 && (LLVM_VERSION_MINOR > 0 || LLVM_VERSION_PATCH >= 1)))
  1666. kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1667. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1668. return LLVMCreateTypeAttribute(ctx, kind, type);
  1669. #else
  1670. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1671. // and the current LLVM C API does not expose this functionality yet.
  1672. // It is better to ignore the attributes for the time being
  1673. if (s == "byval") {
  1674. // return nullptr;
  1675. } else if (s == "byref") {
  1676. return nullptr;
  1677. } else if (s == "preallocated") {
  1678. return nullptr;
  1679. } else if (s == "sret") {
  1680. // return nullptr;
  1681. }
  1682. kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1683. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1684. return LLVMCreateEnumAttribute(ctx, kind, 0);
  1685. #endif
  1686. }
  1687. LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) {
  1688. String s = make_string_c(name);
  1689. // NOTE(2021-02-25, bill); All this attributes require a type associated with them
  1690. // and the current LLVM C API does not expose this functionality yet.
  1691. // It is better to ignore the attributes for the time being
  1692. if (s == "byval") {
  1693. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1694. } else if (s == "byref") {
  1695. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1696. } else if (s == "preallocated") {
  1697. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1698. } else if (s == "sret") {
  1699. GB_PANIC("lb_create_enum_attribute_with_type should be used for %s", name);
  1700. }
  1701. unsigned kind = LLVMGetEnumAttributeKindForName(name, s.len);
  1702. GB_ASSERT_MSG(kind != 0, "unknown attribute: %s", name);
  1703. return LLVMCreateEnumAttribute(ctx, kind, value);
  1704. }
  1705. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) {
  1706. LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value);
  1707. GB_ASSERT(attr != nullptr);
  1708. LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr);
  1709. }
  1710. void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) {
  1711. lb_add_proc_attribute_at_index(p, index, name, 0);
  1712. }
  1713. void lb_add_attribute_to_proc(lbModule *m, LLVMValueRef proc_value, char const *name, u64 value=0) {
  1714. LLVMAddAttributeAtIndex(proc_value, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(m->ctx, name, value));
  1715. }
  1716. void lb_add_edge(lbBlock *from, lbBlock *to) {
  1717. LLVMValueRef instr = LLVMGetLastInstruction(from->block);
  1718. if (instr == nullptr || !LLVMIsATerminatorInst(instr)) {
  1719. array_add(&from->succs, to);
  1720. array_add(&to->preds, from);
  1721. }
  1722. }
  1723. lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) {
  1724. lbBlock *b = gb_alloc_item(permanent_allocator(), lbBlock);
  1725. b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name);
  1726. b->appended = false;
  1727. if (append) {
  1728. b->appended = true;
  1729. LLVMAppendExistingBasicBlock(p->value, b->block);
  1730. }
  1731. b->scope = p->curr_scope;
  1732. b->scope_index = p->scope_index;
  1733. b->preds.allocator = heap_allocator();
  1734. b->succs.allocator = heap_allocator();
  1735. array_add(&p->blocks, b);
  1736. return b;
  1737. }
  1738. void lb_emit_jump(lbProcedure *p, lbBlock *target_block) {
  1739. if (p->curr_block == nullptr) {
  1740. return;
  1741. }
  1742. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1743. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1744. return;
  1745. }
  1746. lb_add_edge(p->curr_block, target_block);
  1747. LLVMBuildBr(p->builder, target_block->block);
  1748. p->curr_block = nullptr;
  1749. }
  1750. void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) {
  1751. lbBlock *b = p->curr_block;
  1752. if (b == nullptr) {
  1753. return;
  1754. }
  1755. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1756. if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) {
  1757. return;
  1758. }
  1759. lb_add_edge(b, true_block);
  1760. lb_add_edge(b, false_block);
  1761. LLVMValueRef cv = cond.value;
  1762. cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), "");
  1763. LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block);
  1764. }
  1765. LLVMValueRef OdinLLVMBuildTransmute(lbProcedure *p, LLVMValueRef val, LLVMTypeRef dst_type) {
  1766. LLVMContextRef ctx = p->module->ctx;
  1767. LLVMTypeRef src_type = LLVMTypeOf(val);
  1768. if (src_type == dst_type) {
  1769. return val;
  1770. }
  1771. i64 src_size = lb_sizeof(src_type);
  1772. i64 dst_size = lb_sizeof(dst_type);
  1773. i64 src_align = lb_alignof(src_type);
  1774. i64 dst_align = lb_alignof(dst_type);
  1775. if (LLVMIsALoadInst(val)) {
  1776. src_align = gb_min(src_align, LLVMGetAlignment(val));
  1777. }
  1778. LLVMTypeKind src_kind = LLVMGetTypeKind(src_type);
  1779. LLVMTypeKind dst_kind = LLVMGetTypeKind(dst_type);
  1780. if (dst_type == LLVMInt1TypeInContext(ctx)) {
  1781. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  1782. return LLVMBuildICmp(p->builder, LLVMIntNE, val, LLVMConstNull(src_type), "");
  1783. } else if (src_type == LLVMInt1TypeInContext(ctx)) {
  1784. GB_ASSERT(lb_is_type_kind(src_type, LLVMIntegerTypeKind));
  1785. return LLVMBuildZExtOrBitCast(p->builder, val, dst_type, "");
  1786. }
  1787. if (src_size != dst_size) {
  1788. if ((lb_is_type_kind(src_type, LLVMVectorTypeKind) ^ lb_is_type_kind(dst_type, LLVMVectorTypeKind))) {
  1789. // Okay
  1790. } else {
  1791. goto general_end;
  1792. }
  1793. }
  1794. if (src_kind == dst_kind) {
  1795. if (src_kind == LLVMPointerTypeKind) {
  1796. return LLVMBuildPointerCast(p->builder, val, dst_type, "");
  1797. } else if (src_kind == LLVMArrayTypeKind) {
  1798. // ignore
  1799. } else if (src_kind != LLVMStructTypeKind) {
  1800. return LLVMBuildBitCast(p->builder, val, dst_type, "");
  1801. }
  1802. } else {
  1803. if (src_kind == LLVMPointerTypeKind && dst_kind == LLVMIntegerTypeKind) {
  1804. return LLVMBuildPtrToInt(p->builder, val, dst_type, "");
  1805. } else if (src_kind == LLVMIntegerTypeKind && dst_kind == LLVMPointerTypeKind) {
  1806. return LLVMBuildIntToPtr(p->builder, val, dst_type, "");
  1807. }
  1808. }
  1809. general_end:;
  1810. // make the alignment big if necessary
  1811. if (LLVMIsALoadInst(val) && src_align < dst_align) {
  1812. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  1813. if (LLVMGetInstructionOpcode(val_ptr) == LLVMAlloca) {
  1814. src_align = gb_max(LLVMGetAlignment(val_ptr), dst_align);
  1815. LLVMSetAlignment(val_ptr, cast(unsigned)src_align);
  1816. }
  1817. }
  1818. src_size = align_formula(src_size, src_align);
  1819. dst_size = align_formula(dst_size, dst_align);
  1820. if (LLVMIsALoadInst(val) && (src_size >= dst_size && src_align >= dst_align)) {
  1821. LLVMValueRef val_ptr = LLVMGetOperand(val, 0);
  1822. val_ptr = LLVMBuildPointerCast(p->builder, val_ptr, LLVMPointerType(dst_type, 0), "");
  1823. LLVMValueRef loaded_val = LLVMBuildLoad(p->builder, val_ptr, "");
  1824. // LLVMSetAlignment(loaded_val, gb_min(src_align, dst_align));
  1825. return loaded_val;
  1826. } else {
  1827. GB_ASSERT(p->decl_block != p->curr_block);
  1828. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  1829. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, dst_type, "");
  1830. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  1831. i64 max_align = gb_max(lb_alignof(src_type), lb_alignof(dst_type));
  1832. max_align = gb_max(max_align, 4);
  1833. LLVMSetAlignment(ptr, cast(unsigned)max_align);
  1834. LLVMValueRef nptr = LLVMBuildPointerCast(p->builder, ptr, LLVMPointerType(src_type, 0), "");
  1835. LLVMBuildStore(p->builder, val, nptr);
  1836. return LLVMBuildLoad(p->builder, ptr, "");
  1837. }
  1838. }
  1839. LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) {
  1840. StringHashKey key = string_hash_string(str);
  1841. LLVMValueRef *found = string_map_get(&m->const_strings, key);
  1842. if (found != nullptr) {
  1843. return *found;
  1844. } else {
  1845. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  1846. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  1847. cast(char const *)str.text,
  1848. cast(unsigned)str.len,
  1849. false);
  1850. isize max_len = 7+8+1;
  1851. char *name = gb_alloc_array(permanent_allocator(), char, max_len);
  1852. u32 id = m->gen->global_array_index.fetch_add(1);
  1853. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  1854. len -= 1;
  1855. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  1856. LLVMSetInitializer(global_data, data);
  1857. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  1858. LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  1859. string_map_set(&m->const_strings, key, ptr);
  1860. return ptr;
  1861. }
  1862. }
  1863. lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) {
  1864. LLVMValueRef ptr = nullptr;
  1865. if (str.len != 0) {
  1866. ptr = lb_find_or_add_entity_string_ptr(m, str);
  1867. } else {
  1868. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  1869. }
  1870. LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  1871. LLVMValueRef values[2] = {ptr, str_len};
  1872. lbValue res = {};
  1873. res.value = llvm_const_named_struct(lb_type(m, t_string), values, 2);
  1874. res.type = t_string;
  1875. return res;
  1876. }
  1877. lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) {
  1878. LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)};
  1879. LLVMValueRef data = LLVMConstStringInContext(m->ctx,
  1880. cast(char const *)str.text,
  1881. cast(unsigned)str.len,
  1882. false);
  1883. char *name = nullptr;
  1884. {
  1885. isize max_len = 7+8+1;
  1886. name = gb_alloc_array(permanent_allocator(), char, max_len);
  1887. u32 id = m->gen->global_array_index.fetch_add(1);
  1888. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  1889. len -= 1;
  1890. }
  1891. LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name);
  1892. LLVMSetInitializer(global_data, data);
  1893. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  1894. LLVMValueRef ptr = nullptr;
  1895. if (str.len != 0) {
  1896. ptr = LLVMConstInBoundsGEP(global_data, indices, 2);
  1897. } else {
  1898. ptr = LLVMConstNull(lb_type(m, t_u8_ptr));
  1899. }
  1900. LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true);
  1901. LLVMValueRef values[2] = {ptr, len};
  1902. lbValue res = {};
  1903. res.value = llvm_const_named_struct(lb_type(m, t_u8_slice), values, 2);
  1904. res.type = t_u8_slice;
  1905. return res;
  1906. }
  1907. lbValue lb_find_ident(lbProcedure *p, lbModule *m, Entity *e, Ast *expr) {
  1908. auto *found = map_get(&m->values, hash_entity(e));
  1909. if (found) {
  1910. auto v = *found;
  1911. // NOTE(bill): This is because pointers are already pointers in LLVM
  1912. if (is_type_proc(v.type)) {
  1913. return v;
  1914. }
  1915. return lb_emit_load(p, v);
  1916. } else if (e != nullptr && e->kind == Entity_Variable) {
  1917. return lb_addr_load(p, lb_build_addr(p, expr));
  1918. }
  1919. if (e->kind == Entity_Procedure) {
  1920. return lb_find_procedure_value_from_entity(m, e);
  1921. }
  1922. if (USE_SEPARATE_MODULES) {
  1923. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  1924. if (other_module != m) {
  1925. String name = lb_get_entity_name(other_module, e);
  1926. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  1927. lbValue g = {};
  1928. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  1929. g.type = alloc_type_pointer(e->type);
  1930. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  1931. lb_add_entity(m, e, g);
  1932. lb_add_member(m, name, g);
  1933. return lb_emit_load(p, g);
  1934. }
  1935. }
  1936. String pkg = {};
  1937. if (e->pkg) {
  1938. pkg = e->pkg->name;
  1939. }
  1940. gb_printf_err("Error in: %s\n", token_pos_to_string(ast_token(expr).pos));
  1941. 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);
  1942. return {};
  1943. }
  1944. lbValue lb_find_procedure_value_from_entity(lbModule *m, Entity *e) {
  1945. GB_ASSERT(is_type_proc(e->type));
  1946. e = strip_entity_wrapping(e);
  1947. GB_ASSERT(e != nullptr);
  1948. auto *found = map_get(&m->values, hash_entity(e));
  1949. if (found) {
  1950. return *found;
  1951. }
  1952. bool ignore_body = false;
  1953. lbModule *other_module = m;
  1954. if (USE_SEPARATE_MODULES) {
  1955. other_module = lb_pkg_module(m->gen, e->pkg);
  1956. }
  1957. if (other_module == m) {
  1958. debugf("Missing Procedure (lb_find_procedure_value_from_entity): %.*s\n", LIT(e->token.string));
  1959. }
  1960. ignore_body = other_module != m;
  1961. lbProcedure *missing_proc = lb_create_procedure(m, e, ignore_body);
  1962. if (!ignore_body) {
  1963. array_add(&m->missing_procedures_to_check, missing_proc);
  1964. }
  1965. found = map_get(&m->values, hash_entity(e));
  1966. if (found) {
  1967. return *found;
  1968. }
  1969. GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  1970. return {};
  1971. }
  1972. lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) {
  1973. GB_ASSERT(type != nullptr);
  1974. type = default_type(type);
  1975. isize max_len = 7+8+1;
  1976. u8 *str = cast(u8 *)gb_alloc_array(permanent_allocator(), u8, max_len);
  1977. u32 id = m->gen->global_generated_index.fetch_add(1);
  1978. isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", id);
  1979. String name = make_string(str, len-1);
  1980. Scope *scope = nullptr;
  1981. Entity *e = alloc_entity_variable(scope, make_token_ident(name), type);
  1982. lbValue g = {};
  1983. g.type = alloc_type_pointer(type);
  1984. g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str);
  1985. if (value.value != nullptr) {
  1986. GB_ASSERT_MSG(LLVMIsConstant(value.value), LLVMPrintValueToString(value.value));
  1987. LLVMSetInitializer(g.value, value.value);
  1988. } else {
  1989. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type)));
  1990. }
  1991. lb_add_entity(m, e, g);
  1992. lb_add_member(m, name, g);
  1993. return lb_addr(g);
  1994. }
  1995. lbValue lb_find_runtime_value(lbModule *m, String const &name) {
  1996. AstPackage *p = m->info->runtime_package;
  1997. Entity *e = scope_lookup_current(p->scope, name);
  1998. return lb_find_value_from_entity(m, e);
  1999. }
  2000. lbValue lb_find_package_value(lbModule *m, String const &pkg, String const &name) {
  2001. Entity *e = find_entity_in_pkg(m->info, pkg, name);
  2002. return lb_find_value_from_entity(m, e);
  2003. }
  2004. lbValue lb_generate_local_array(lbProcedure *p, Type *elem_type, i64 count, bool zero_init) {
  2005. lbAddr addr = lb_add_local_generated(p, alloc_type_array(elem_type, count), zero_init);
  2006. return lb_addr_get_ptr(p, addr);
  2007. }
  2008. lbValue lb_find_value_from_entity(lbModule *m, Entity *e) {
  2009. e = strip_entity_wrapping(e);
  2010. GB_ASSERT(e != nullptr);
  2011. GB_ASSERT(e->token.string != "_");
  2012. if (e->kind == Entity_Procedure) {
  2013. return lb_find_procedure_value_from_entity(m, e);
  2014. }
  2015. auto *found = map_get(&m->values, hash_entity(e));
  2016. if (found) {
  2017. return *found;
  2018. }
  2019. if (USE_SEPARATE_MODULES) {
  2020. lbModule *other_module = lb_pkg_module(m->gen, e->pkg);
  2021. // TODO(bill): correct this logic
  2022. bool is_external = other_module != m;
  2023. if (!is_external) {
  2024. if (e->code_gen_module != nullptr) {
  2025. other_module = e->code_gen_module;
  2026. } else {
  2027. other_module = nullptr;
  2028. }
  2029. is_external = other_module != m;
  2030. }
  2031. if (is_external) {
  2032. String name = lb_get_entity_name(other_module, e);
  2033. lbValue g = {};
  2034. g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(permanent_allocator(), name));
  2035. g.type = alloc_type_pointer(e->type);
  2036. lb_add_entity(m, e, g);
  2037. lb_add_member(m, name, g);
  2038. LLVMSetLinkage(g.value, LLVMExternalLinkage);
  2039. lb_set_entity_from_other_modules_linkage_correctly(other_module, e, name);
  2040. // LLVMSetLinkage(other_g.value, LLVMExternalLinkage);
  2041. if (e->Variable.thread_local_model != "") {
  2042. LLVMSetThreadLocal(g.value, true);
  2043. String m = e->Variable.thread_local_model;
  2044. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  2045. if (m == "default") {
  2046. mode = LLVMGeneralDynamicTLSModel;
  2047. } else if (m == "localdynamic") {
  2048. mode = LLVMLocalDynamicTLSModel;
  2049. } else if (m == "initialexec") {
  2050. mode = LLVMInitialExecTLSModel;
  2051. } else if (m == "localexec") {
  2052. mode = LLVMLocalExecTLSModel;
  2053. } else {
  2054. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  2055. }
  2056. LLVMSetThreadLocalMode(g.value, mode);
  2057. }
  2058. return g;
  2059. }
  2060. }
  2061. GB_PANIC("\n\tError in: %s, missing value '%.*s'\n", token_pos_to_string(e->token.pos), LIT(e->token.string));
  2062. return {};
  2063. }
  2064. lbValue lb_generate_global_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) {
  2065. Token token = {Token_Ident};
  2066. isize name_len = prefix.len + 1 + 20;
  2067. auto suffix_id = cast(unsigned long long)id;
  2068. char *text = gb_alloc_array(permanent_allocator(), char, name_len+1);
  2069. gb_snprintf(text, name_len,
  2070. "%.*s-%llu", LIT(prefix), suffix_id);
  2071. text[name_len] = 0;
  2072. String s = make_string_c(text);
  2073. Type *t = alloc_type_array(elem_type, count);
  2074. lbValue g = {};
  2075. g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text);
  2076. g.type = alloc_type_pointer(t);
  2077. LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t)));
  2078. LLVMSetLinkage(g.value, LLVMInternalLinkage);
  2079. string_map_set(&m->members, s, g);
  2080. return g;
  2081. }
  2082. lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) {
  2083. GB_ASSERT(cond != nullptr);
  2084. GB_ASSERT(true_block != nullptr);
  2085. GB_ASSERT(false_block != nullptr);
  2086. switch (cond->kind) {
  2087. case_ast_node(pe, ParenExpr, cond);
  2088. return lb_build_cond(p, pe->expr, true_block, false_block);
  2089. case_end;
  2090. case_ast_node(ue, UnaryExpr, cond);
  2091. if (ue->op.kind == Token_Not) {
  2092. return lb_build_cond(p, ue->expr, false_block, true_block);
  2093. }
  2094. case_end;
  2095. case_ast_node(be, BinaryExpr, cond);
  2096. if (be->op.kind == Token_CmpAnd) {
  2097. lbBlock *block = lb_create_block(p, "cmp.and");
  2098. lb_build_cond(p, be->left, block, false_block);
  2099. lb_start_block(p, block);
  2100. return lb_build_cond(p, be->right, true_block, false_block);
  2101. } else if (be->op.kind == Token_CmpOr) {
  2102. lbBlock *block = lb_create_block(p, "cmp.or");
  2103. lb_build_cond(p, be->left, true_block, block);
  2104. lb_start_block(p, block);
  2105. return lb_build_cond(p, be->right, true_block, false_block);
  2106. }
  2107. case_end;
  2108. }
  2109. lbValue v = {};
  2110. if (lb_is_expr_untyped_const(cond)) {
  2111. v = lb_expr_untyped_const_to_typed(p->module, cond, t_llvm_bool);
  2112. } else {
  2113. v = lb_build_expr(p, cond);
  2114. }
  2115. v = lb_emit_conv(p, v, t_llvm_bool);
  2116. lb_emit_if(p, v, true_block, false_block);
  2117. return v;
  2118. }
  2119. lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index, bool force_no_init) {
  2120. GB_ASSERT(p->decl_block != p->curr_block);
  2121. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  2122. char const *name = "";
  2123. if (e != nullptr) {
  2124. // name = alloc_cstring(permanent_allocator(), e->token.string);
  2125. }
  2126. LLVMTypeRef llvm_type = lb_type(p->module, type);
  2127. LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name);
  2128. // unsigned alignment = 16; // TODO(bill): Make this configurable
  2129. unsigned alignment = cast(unsigned)lb_alignof(llvm_type);
  2130. LLVMSetAlignment(ptr, alignment);
  2131. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  2132. if (!zero_init && !force_no_init) {
  2133. // If there is any padding of any kind, just zero init regardless of zero_init parameter
  2134. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  2135. if (kind == LLVMStructTypeKind) {
  2136. i64 sz = type_size_of(type);
  2137. if (type_size_of_struct_pretend_is_packed(type) != sz) {
  2138. zero_init = true;
  2139. }
  2140. } else if (kind == LLVMArrayTypeKind) {
  2141. zero_init = true;
  2142. }
  2143. }
  2144. if (zero_init) {
  2145. lb_mem_zero_ptr(p, ptr, type, alignment);
  2146. }
  2147. lbValue val = {};
  2148. val.value = ptr;
  2149. val.type = alloc_type_pointer(type);
  2150. if (e != nullptr) {
  2151. lb_add_entity(p->module, e, val);
  2152. lb_add_debug_local_variable(p, ptr, type, e->token);
  2153. }
  2154. return lb_addr(val);
  2155. }
  2156. lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) {
  2157. return lb_add_local(p, type, nullptr, zero_init);
  2158. }
  2159. lbAddr lb_add_local_generated_temp(lbProcedure *p, Type *type, i64 min_alignment) {
  2160. lbAddr res = lb_add_local(p, type, nullptr, false, 0, true);
  2161. lb_try_update_alignment(res.addr, cast(unsigned)min_alignment);
  2162. return res;
  2163. }