llvm_backend_utility.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023
  1. lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name);
  2. bool lb_is_type_aggregate(Type *t) {
  3. t = base_type(t);
  4. switch (t->kind) {
  5. case Type_Basic:
  6. switch (t->Basic.kind) {
  7. case Basic_string:
  8. case Basic_any:
  9. return true;
  10. case Basic_complex32:
  11. case Basic_complex64:
  12. case Basic_complex128:
  13. case Basic_quaternion64:
  14. case Basic_quaternion128:
  15. case Basic_quaternion256:
  16. return true;
  17. }
  18. break;
  19. case Type_Pointer:
  20. return false;
  21. case Type_Array:
  22. case Type_Slice:
  23. case Type_Struct:
  24. case Type_Union:
  25. case Type_Tuple:
  26. case Type_DynamicArray:
  27. case Type_Map:
  28. case Type_SimdVector:
  29. return true;
  30. case Type_Named:
  31. return lb_is_type_aggregate(t->Named.base);
  32. }
  33. return false;
  34. }
  35. void lb_emit_unreachable(lbProcedure *p) {
  36. LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block);
  37. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  38. lb_call_intrinsic(p, "llvm.trap", nullptr, 0, nullptr, 0);
  39. LLVMBuildUnreachable(p->builder);
  40. }
  41. }
  42. lbValue lb_correct_endianness(lbProcedure *p, lbValue value) {
  43. Type *src = core_type(value.type);
  44. GB_ASSERT(is_type_integer(src) || is_type_float(src));
  45. if (is_type_different_to_arch_endianness(src)) {
  46. Type *platform_src_type = integer_endian_type_to_platform_type(src);
  47. value = lb_emit_byte_swap(p, value, platform_src_type);
  48. }
  49. return value;
  50. }
  51. LLVMValueRef lb_mem_zero_ptr_internal(lbProcedure *p, LLVMValueRef ptr, LLVMValueRef len, unsigned alignment, bool is_volatile) {
  52. bool is_inlinable = false;
  53. i64 const_len = 0;
  54. if (LLVMIsConstant(len)) {
  55. const_len = cast(i64)LLVMConstIntGetSExtValue(len);
  56. // TODO(bill): Determine when it is better to do the `*.inline` versions
  57. if (const_len <= lb_max_zero_init_size()) {
  58. is_inlinable = true;
  59. }
  60. }
  61. char const *name = "llvm.memset";
  62. if (is_inlinable) {
  63. name = "llvm.memset.inline";
  64. }
  65. LLVMTypeRef types[2] = {
  66. lb_type(p->module, t_rawptr),
  67. lb_type(p->module, t_int)
  68. };
  69. if (true || is_inlinable) {
  70. LLVMValueRef args[4] = {};
  71. args[0] = LLVMBuildPointerCast(p->builder, ptr, types[0], "");
  72. args[1] = LLVMConstInt(LLVMInt8TypeInContext(p->module->ctx), 0, false);
  73. args[2] = LLVMBuildIntCast2(p->builder, len, types[1], /*signed*/false, "");
  74. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), is_volatile, false);
  75. return lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  76. } else {
  77. lbValue pr = lb_lookup_runtime_procedure(p->module, str_lit("memset"));
  78. LLVMValueRef args[3] = {};
  79. args[0] = LLVMBuildPointerCast(p->builder, ptr, types[0], "");
  80. args[1] = LLVMConstInt(LLVMInt32TypeInContext(p->module->ctx), 0, false);
  81. args[2] = LLVMBuildIntCast2(p->builder, len, types[1], /*signed*/false, "");
  82. // We always get the function pointer type rather than the function and there is apparently no way around that?
  83. LLVMTypeRef type = lb_type_internal_for_procedures_raw(p->module, pr.type);
  84. return LLVMBuildCall2(p->builder, type, pr.value, args, gb_count_of(args), "");
  85. }
  86. }
  87. void lb_mem_zero_ptr(lbProcedure *p, LLVMValueRef ptr, Type *type, unsigned alignment) {
  88. LLVMTypeRef llvm_type = lb_type(p->module, type);
  89. LLVMTypeKind kind = LLVMGetTypeKind(llvm_type);
  90. switch (kind) {
  91. case LLVMStructTypeKind:
  92. case LLVMArrayTypeKind:
  93. {
  94. // NOTE(bill): Enforce zeroing through memset to make sure padding is zeroed too
  95. i32 sz = cast(i32)type_size_of(type);
  96. lb_mem_zero_ptr_internal(p, ptr, lb_const_int(p->module, t_int, sz).value, alignment, false);
  97. }
  98. break;
  99. default:
  100. LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr);
  101. break;
  102. }
  103. }
  104. lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) {
  105. cond = lb_emit_conv(p, cond, t_llvm_bool);
  106. lbValue res = {};
  107. res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, "");
  108. res.type = x.type;
  109. return res;
  110. }
  111. lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  112. x = lb_emit_conv(p, x, t);
  113. y = lb_emit_conv(p, y, t);
  114. return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y);
  115. }
  116. lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) {
  117. x = lb_emit_conv(p, x, t);
  118. y = lb_emit_conv(p, y, t);
  119. return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y);
  120. }
  121. lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) {
  122. lbValue z = {};
  123. z = lb_emit_max(p, t, x, min);
  124. z = lb_emit_min(p, t, z, max);
  125. return z;
  126. }
  127. lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) {
  128. if (false && lb_is_const(str_elem) && lb_is_const(str_len)) {
  129. LLVMValueRef values[2] = {
  130. str_elem.value,
  131. str_len.value,
  132. };
  133. lbValue res = {};
  134. res.type = t_string;
  135. res.value = llvm_const_named_struct(p->module, t_string, values, gb_count_of(values));
  136. return res;
  137. } else {
  138. lbAddr res = lb_add_local_generated(p, t_string, false);
  139. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem);
  140. lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len);
  141. return lb_addr_load(p, res);
  142. }
  143. }
  144. lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) {
  145. Type *src_type = value.type;
  146. if (are_types_identical(t, src_type)) {
  147. return value;
  148. }
  149. lbValue res = {};
  150. res.type = t;
  151. Type *src = base_type(src_type);
  152. Type *dst = base_type(t);
  153. lbModule *m = p->module;
  154. i64 sz = type_size_of(src);
  155. i64 dz = type_size_of(dst);
  156. if (sz != dz) {
  157. LLVMTypeRef s = lb_type(m, src);
  158. LLVMTypeRef d = lb_type(m, dst);
  159. i64 llvm_sz = lb_sizeof(s);
  160. i64 llvm_dz = lb_sizeof(d);
  161. GB_ASSERT_MSG(llvm_sz == llvm_dz, "%s %s", LLVMPrintTypeToString(s), LLVMPrintTypeToString(d));
  162. }
  163. GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t));
  164. // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast
  165. if (is_type_uintptr(src) && is_type_internally_pointer_like(dst)) {
  166. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  167. return res;
  168. }
  169. if (is_type_internally_pointer_like(src) && is_type_uintptr(dst)) {
  170. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  171. return res;
  172. }
  173. if (is_type_integer(src) && is_type_internally_pointer_like(dst)) {
  174. res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), "");
  175. return res;
  176. } else if (is_type_internally_pointer_like(src) && is_type_integer(dst)) {
  177. res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), "");
  178. return res;
  179. }
  180. if (is_type_internally_pointer_like(src) && is_type_internally_pointer_like(dst)) {
  181. res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), "");
  182. return res;
  183. }
  184. if (is_type_simd_vector(src) && is_type_simd_vector(dst)) {
  185. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  186. return res;
  187. }
  188. if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) {
  189. lbValue s = lb_address_from_load_or_generate_local(p, value);
  190. lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t));
  191. return lb_emit_load(p, d);
  192. }
  193. res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), "");
  194. return res;
  195. }
  196. lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) {
  197. i64 type_alignment = type_align_of(new_type);
  198. if (alignment < type_alignment) {
  199. alignment = type_alignment;
  200. }
  201. GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type));
  202. lbAddr ptr = lb_add_local_generated(p, new_type, false);
  203. LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment);
  204. lb_addr_store(p, ptr, val);
  205. // ptr.kind = lbAddr_Context;
  206. return ptr.addr;
  207. }
  208. lbValue lb_soa_zip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  209. GB_ASSERT(ce->args.count > 0);
  210. auto slices = slice_make<lbValue>(temporary_allocator(), ce->args.count);
  211. for_array(i, slices) {
  212. Ast *arg = ce->args[i];
  213. if (arg->kind == Ast_FieldValue) {
  214. arg = arg->FieldValue.value;
  215. }
  216. slices[i] = lb_build_expr(p, arg);
  217. }
  218. lbValue len = lb_slice_len(p, slices[0]);
  219. for (isize i = 1; i < slices.count; i++) {
  220. lbValue other_len = lb_slice_len(p, slices[i]);
  221. len = lb_emit_min(p, t_int, len, other_len);
  222. }
  223. GB_ASSERT(is_type_soa_struct(tv.type));
  224. lbAddr res = lb_add_local_generated(p, tv.type, true);
  225. for_array(i, slices) {
  226. lbValue src = lb_slice_elem(p, slices[i]);
  227. lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i);
  228. lb_emit_store(p, dst, src);
  229. }
  230. lbValue len_dst = lb_emit_struct_ep(p, res.addr, cast(i32)slices.count);
  231. lb_emit_store(p, len_dst, len);
  232. return lb_addr_load(p, res);
  233. }
  234. lbValue lb_soa_unzip(lbProcedure *p, AstCallExpr *ce, TypeAndValue const &tv) {
  235. GB_ASSERT(ce->args.count == 1);
  236. lbValue arg = lb_build_expr(p, ce->args[0]);
  237. Type *t = base_type(arg.type);
  238. GB_ASSERT(is_type_soa_struct(t) && t->Struct.soa_kind == StructSoa_Slice);
  239. lbValue len = lb_soa_struct_len(p, arg);
  240. lbAddr res = lb_add_local_generated(p, tv.type, true);
  241. if (is_type_tuple(tv.type)) {
  242. lbValue rp = lb_addr_get_ptr(p, res);
  243. for (i32 i = 0; i < cast(i32)(t->Struct.fields.count-1); i++) {
  244. lbValue ptr = lb_emit_struct_ev(p, arg, i);
  245. lbAddr dst = lb_addr(lb_emit_struct_ep(p, rp, i));
  246. lb_fill_slice(p, dst, ptr, len);
  247. }
  248. } else {
  249. GB_ASSERT(is_type_slice(tv.type));
  250. lbValue ptr = lb_emit_struct_ev(p, arg, 0);
  251. lb_fill_slice(p, res, ptr, len);
  252. }
  253. return lb_addr_load(p, res);
  254. }
  255. void lb_emit_try_lhs_rhs(lbProcedure *p, Ast *arg, TypeAndValue const &tv, lbValue *lhs_, lbValue *rhs_) {
  256. lbValue lhs = {};
  257. lbValue rhs = {};
  258. lbValue value = lb_build_expr(p, arg);
  259. if (is_type_tuple(value.type)) {
  260. i32 n = cast(i32)(value.type->Tuple.variables.count-1);
  261. if (value.type->Tuple.variables.count == 2) {
  262. lhs = lb_emit_struct_ev(p, value, 0);
  263. } else {
  264. lbAddr lhs_addr = lb_add_local_generated(p, tv.type, false);
  265. lbValue lhs_ptr = lb_addr_get_ptr(p, lhs_addr);
  266. for (i32 i = 0; i < n; i++) {
  267. lb_emit_store(p, lb_emit_struct_ep(p, lhs_ptr, i), lb_emit_struct_ev(p, value, i));
  268. }
  269. lhs = lb_addr_load(p, lhs_addr);
  270. }
  271. rhs = lb_emit_struct_ev(p, value, n);
  272. } else {
  273. rhs = value;
  274. }
  275. GB_ASSERT(rhs.value != nullptr);
  276. if (lhs_) *lhs_ = lhs;
  277. if (rhs_) *rhs_ = rhs;
  278. }
  279. lbValue lb_emit_try_has_value(lbProcedure *p, lbValue rhs) {
  280. lbValue has_value = {};
  281. if (is_type_boolean(rhs.type)) {
  282. has_value = rhs;
  283. } else {
  284. GB_ASSERT_MSG(type_has_nil(rhs.type), "%s", type_to_string(rhs.type));
  285. has_value = lb_emit_comp_against_nil(p, Token_CmpEq, rhs);
  286. }
  287. GB_ASSERT(has_value.value != nullptr);
  288. return has_value;
  289. }
  290. lbValue lb_emit_or_else(lbProcedure *p, Ast *arg, Ast *else_expr, TypeAndValue const &tv) {
  291. if (arg->state_flags & StateFlag_DirectiveWasFalse) {
  292. return lb_build_expr(p, else_expr);
  293. }
  294. lbValue lhs = {};
  295. lbValue rhs = {};
  296. lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  297. GB_ASSERT(else_expr != nullptr);
  298. Type *type = default_type(tv.type);
  299. if (is_diverging_expr(else_expr)) {
  300. lbBlock *then = lb_create_block(p, "or_else.then");
  301. lbBlock *else_ = lb_create_block(p, "or_else.else");
  302. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  303. // NOTE(bill): else block needs to be straight afterwards to make sure that the actual value is used
  304. // from the then block
  305. lb_start_block(p, else_);
  306. lb_build_expr(p, else_expr);
  307. lb_emit_unreachable(p); // add just in case
  308. lb_start_block(p, then);
  309. return lb_emit_conv(p, lhs, type);
  310. } else {
  311. LLVMValueRef incoming_values[2] = {};
  312. LLVMBasicBlockRef incoming_blocks[2] = {};
  313. lbBlock *then = lb_create_block(p, "or_else.then");
  314. lbBlock *done = lb_create_block(p, "or_else.done"); // NOTE(bill): Append later
  315. lbBlock *else_ = lb_create_block(p, "or_else.else");
  316. lb_emit_if(p, lb_emit_try_has_value(p, rhs), then, else_);
  317. lb_start_block(p, then);
  318. incoming_values[0] = lb_emit_conv(p, lhs, type).value;
  319. lb_emit_jump(p, done);
  320. lb_start_block(p, else_);
  321. incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, else_expr), type).value;
  322. lb_emit_jump(p, done);
  323. lb_start_block(p, done);
  324. lbValue res = {};
  325. res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), "");
  326. res.type = type;
  327. GB_ASSERT(p->curr_block->preds.count >= 2);
  328. incoming_blocks[0] = p->curr_block->preds[0]->block;
  329. incoming_blocks[1] = p->curr_block->preds[1]->block;
  330. LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2);
  331. return res;
  332. }
  333. }
  334. void lb_build_return_stmt(lbProcedure *p, Slice<Ast *> const &return_results);
  335. void lb_build_return_stmt_internal(lbProcedure *p, lbValue const &res);
  336. lbValue lb_emit_or_return(lbProcedure *p, Ast *arg, TypeAndValue const &tv) {
  337. lbValue lhs = {};
  338. lbValue rhs = {};
  339. lb_emit_try_lhs_rhs(p, arg, tv, &lhs, &rhs);
  340. lbBlock *return_block = lb_create_block(p, "or_return.return");
  341. lbBlock *continue_block = lb_create_block(p, "or_return.continue");
  342. lb_emit_if(p, lb_emit_try_has_value(p, rhs), continue_block, return_block);
  343. lb_start_block(p, return_block);
  344. {
  345. Type *proc_type = base_type(p->type);
  346. Type *results = proc_type->Proc.results;
  347. GB_ASSERT(results != nullptr && results->kind == Type_Tuple);
  348. TypeTuple *tuple = &results->Tuple;
  349. GB_ASSERT(tuple->variables.count != 0);
  350. Entity *end_entity = tuple->variables[tuple->variables.count-1];
  351. rhs = lb_emit_conv(p, rhs, end_entity->type);
  352. if (p->type->Proc.has_named_results) {
  353. GB_ASSERT(end_entity->token.string.len != 0);
  354. // NOTE(bill): store the named values before returning
  355. lbValue found = map_must_get(&p->module->values, end_entity);
  356. lb_emit_store(p, found, rhs);
  357. lb_build_return_stmt(p, {});
  358. } else {
  359. GB_ASSERT(tuple->variables.count == 1);
  360. lb_build_return_stmt_internal(p, rhs);
  361. }
  362. }
  363. lb_start_block(p, continue_block);
  364. if (tv.type != nullptr) {
  365. return lb_emit_conv(p, lhs, tv.type);
  366. }
  367. return {};
  368. }
  369. void lb_emit_increment(lbProcedure *p, lbValue addr) {
  370. GB_ASSERT(is_type_pointer(addr.type));
  371. Type *type = type_deref(addr.type);
  372. lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1));
  373. lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type));
  374. }
  375. lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type) {
  376. GB_ASSERT(type_size_of(value.type) == type_size_of(end_type));
  377. if (type_size_of(value.type) < 2) {
  378. return value;
  379. }
  380. Type *original_type = value.type;
  381. if (is_type_float(original_type)) {
  382. i64 sz = type_size_of(original_type);
  383. Type *integer_type = nullptr;
  384. switch (sz) {
  385. case 2: integer_type = t_u16; break;
  386. case 4: integer_type = t_u32; break;
  387. case 8: integer_type = t_u64; break;
  388. }
  389. GB_ASSERT(integer_type != nullptr);
  390. value = lb_emit_transmute(p, value, integer_type);
  391. }
  392. char const *name = "llvm.bswap";
  393. LLVMTypeRef types[1] = {lb_type(p->module, value.type)};
  394. LLVMValueRef args[1] = { value.value };
  395. lbValue res = {};
  396. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  397. res.type = value.type;
  398. if (is_type_float(original_type)) {
  399. res = lb_emit_transmute(p, res, original_type);
  400. }
  401. res.type = end_type;
  402. return res;
  403. }
  404. lbValue lb_emit_count_ones(lbProcedure *p, lbValue x, Type *type) {
  405. x = lb_emit_conv(p, x, type);
  406. char const *name = "llvm.ctpop";
  407. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  408. LLVMValueRef args[1] = { x.value };
  409. lbValue res = {};
  410. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  411. res.type = type;
  412. return res;
  413. }
  414. lbValue lb_emit_count_zeros(lbProcedure *p, lbValue x, Type *type) {
  415. Type *elem = base_array_type(type);
  416. i64 sz = 8*type_size_of(elem);
  417. lbValue size = lb_const_int(p->module, elem, cast(u64)sz);
  418. size = lb_emit_conv(p, size, type);
  419. lbValue count = lb_emit_count_ones(p, x, type);
  420. return lb_emit_arith(p, Token_Sub, size, count, type);
  421. }
  422. lbValue lb_emit_count_trailing_zeros(lbProcedure *p, lbValue x, Type *type) {
  423. x = lb_emit_conv(p, x, type);
  424. char const *name = "llvm.cttz";
  425. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  426. LLVMValueRef args[2] = {
  427. x.value,
  428. LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx)) };
  429. lbValue res = {};
  430. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  431. res.type = type;
  432. return res;
  433. }
  434. lbValue lb_emit_count_leading_zeros(lbProcedure *p, lbValue x, Type *type) {
  435. x = lb_emit_conv(p, x, type);
  436. char const *name = "llvm.ctlz";
  437. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  438. LLVMValueRef args[2] = {
  439. x.value,
  440. LLVMConstNull(LLVMInt1TypeInContext(p->module->ctx)) };
  441. lbValue res = {};
  442. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  443. res.type = type;
  444. return res;
  445. }
  446. lbValue lb_emit_reverse_bits(lbProcedure *p, lbValue x, Type *type) {
  447. x = lb_emit_conv(p, x, type);
  448. char const *name = "llvm.bitreverse";
  449. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  450. LLVMValueRef args[1] = { x.value };
  451. lbValue res = {};
  452. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  453. res.type = type;
  454. return res;
  455. }
  456. lbValue lb_emit_bit_set_card(lbProcedure *p, lbValue x) {
  457. GB_ASSERT(is_type_bit_set(x.type));
  458. Type *underlying = bit_set_to_int(x.type);
  459. lbValue card = lb_emit_count_ones(p, x, underlying);
  460. return lb_emit_conv(p, card, t_int);
  461. }
  462. lbValue lb_emit_union_cast_only_ok_check(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  463. GB_ASSERT(is_type_tuple(type));
  464. lbModule *m = p->module;
  465. Type *src_type = value.type;
  466. bool is_ptr = is_type_pointer(src_type);
  467. // IMPORTANT NOTE(bill): This assumes that the value is completely ignored
  468. // so when it does an assignment, it complete ignores the value.
  469. // Just make it two booleans and ignore the first one
  470. //
  471. // _, ok := x.(T);
  472. //
  473. Type *ok_type = type->Tuple.variables[1]->type;
  474. Type *gen_tuple_types[2] = {};
  475. gen_tuple_types[0] = ok_type;
  476. gen_tuple_types[1] = ok_type;
  477. Type *gen_tuple = alloc_type_tuple_from_field_types(gen_tuple_types, gb_count_of(gen_tuple_types), false, true);
  478. lbAddr v = lb_add_local_generated(p, gen_tuple, false);
  479. if (is_ptr) {
  480. value = lb_emit_load(p, value);
  481. }
  482. Type *src = base_type(type_deref(src_type));
  483. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  484. Type *dst = type->Tuple.variables[0]->type;
  485. lbValue cond = {};
  486. if (is_type_union_maybe_pointer(src)) {
  487. lbValue data = lb_emit_transmute(p, value, dst);
  488. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  489. } else {
  490. lbValue tag = lb_emit_union_tag_value(p, value);
  491. lbValue dst_tag = lb_const_union_tag(m, src, dst);
  492. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  493. }
  494. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  495. lb_emit_store(p, gep1, cond);
  496. return lb_addr_load(p, v);
  497. }
  498. lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  499. lbModule *m = p->module;
  500. Type *src_type = value.type;
  501. bool is_ptr = is_type_pointer(src_type);
  502. bool is_tuple = true;
  503. Type *tuple = type;
  504. if (type->kind != Type_Tuple) {
  505. is_tuple = false;
  506. tuple = make_optional_ok_type(type);
  507. }
  508. lbAddr v = lb_add_local_generated(p, tuple, true);
  509. if (is_ptr) {
  510. value = lb_emit_load(p, value);
  511. }
  512. Type *src = base_type(type_deref(src_type));
  513. GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type));
  514. Type *dst = tuple->Tuple.variables[0]->type;
  515. lbValue value_ = lb_address_from_load_or_generate_local(p, value);
  516. if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) {
  517. // just do a bit cast of the data at the front
  518. lbValue ptr = lb_emit_conv(p, value_, alloc_type_pointer(type));
  519. return lb_emit_load(p, ptr);
  520. }
  521. lbValue tag = {};
  522. lbValue dst_tag = {};
  523. lbValue cond = {};
  524. lbValue data = {};
  525. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  526. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  527. if (is_type_union_maybe_pointer(src)) {
  528. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  529. } else {
  530. tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_));
  531. dst_tag = lb_const_union_tag(m, src, dst);
  532. }
  533. lbBlock *ok_block = lb_create_block(p, "union_cast.ok");
  534. lbBlock *end_block = lb_create_block(p, "union_cast.end");
  535. if (data.value != nullptr) {
  536. GB_ASSERT(is_type_union_maybe_pointer(src));
  537. cond = lb_emit_comp_against_nil(p, Token_NotEq, data);
  538. } else {
  539. cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag);
  540. }
  541. lb_emit_if(p, cond, ok_block, end_block);
  542. lb_start_block(p, ok_block);
  543. if (data.value == nullptr) {
  544. data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type));
  545. }
  546. lb_emit_store(p, gep0, data);
  547. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  548. lb_emit_jump(p, end_block);
  549. lb_start_block(p, end_block);
  550. if (!is_tuple) {
  551. GB_ASSERT((p->state_flags & StateFlag_no_type_assert) == 0);
  552. // NOTE(bill): Panic on invalid conversion
  553. Type *dst_type = tuple->Tuple.variables[0]->type;
  554. isize arg_count = 7;
  555. if (build_context.disallow_rtti) {
  556. arg_count = 4;
  557. }
  558. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  559. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  560. args[0] = ok;
  561. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  562. args[2] = lb_const_int(m, t_i32, pos.line);
  563. args[3] = lb_const_int(m, t_i32, pos.column);
  564. if (!build_context.disallow_rtti) {
  565. args[4] = lb_typeid(m, src_type);
  566. args[5] = lb_typeid(m, dst_type);
  567. args[6] = lb_emit_conv(p, value_, t_rawptr);
  568. }
  569. lb_emit_runtime_call(p, "type_assertion_check2", args);
  570. return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0));
  571. }
  572. return lb_addr_load(p, v);
  573. }
  574. lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  575. lbModule *m = p->module;
  576. Type *src_type = value.type;
  577. if (is_type_pointer(src_type)) {
  578. value = lb_emit_load(p, value);
  579. }
  580. bool is_tuple = true;
  581. Type *tuple = type;
  582. if (type->kind != Type_Tuple) {
  583. is_tuple = false;
  584. tuple = make_optional_ok_type(type);
  585. }
  586. Type *dst_type = tuple->Tuple.variables[0]->type;
  587. if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) {
  588. // just do a bit cast of the data at the front
  589. lbValue ptr = lb_emit_struct_ev(p, value, 0);
  590. ptr = lb_emit_conv(p, ptr, alloc_type_pointer(type));
  591. return lb_addr(ptr);
  592. }
  593. lbAddr v = lb_add_local_generated(p, tuple, true);
  594. lbValue dst_typeid = lb_typeid(m, dst_type);
  595. lbValue any_typeid = lb_emit_struct_ev(p, value, 1);
  596. lbBlock *ok_block = lb_create_block(p, "any_cast.ok");
  597. lbBlock *end_block = lb_create_block(p, "any_cast.end");
  598. lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid);
  599. lb_emit_if(p, cond, ok_block, end_block);
  600. lb_start_block(p, ok_block);
  601. lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0);
  602. lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1);
  603. lbValue any_data = lb_emit_struct_ev(p, value, 0);
  604. lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type));
  605. lb_emit_store(p, gep0, lb_emit_load(p, ptr));
  606. lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true));
  607. lb_emit_jump(p, end_block);
  608. lb_start_block(p, end_block);
  609. if (!is_tuple) {
  610. // NOTE(bill): Panic on invalid conversion
  611. lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1));
  612. isize arg_count = 7;
  613. if (build_context.disallow_rtti) {
  614. arg_count = 4;
  615. }
  616. auto args = array_make<lbValue>(permanent_allocator(), arg_count);
  617. args[0] = ok;
  618. args[1] = lb_const_string(m, get_file_path_string(pos.file_id));
  619. args[2] = lb_const_int(m, t_i32, pos.line);
  620. args[3] = lb_const_int(m, t_i32, pos.column);
  621. if (!build_context.disallow_rtti) {
  622. args[4] = any_typeid;
  623. args[5] = dst_typeid;
  624. args[6] = lb_emit_struct_ev(p, value, 0);
  625. }
  626. lb_emit_runtime_call(p, "type_assertion_check2", args);
  627. return lb_addr(lb_emit_struct_ep(p, v.addr, 0));
  628. }
  629. return v;
  630. }
  631. lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) {
  632. return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos));
  633. }
  634. lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) {
  635. if (p->context_stack.count > 0) {
  636. return p->context_stack[p->context_stack.count-1].ctx;
  637. }
  638. Type *pt = base_type(p->type);
  639. GB_ASSERT(pt->kind == Type_Proc);
  640. GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin);
  641. lbAddr c = lb_add_local_generated(p, t_context, true);
  642. c.kind = lbAddr_Context;
  643. lb_emit_init_context(p, c);
  644. lb_push_context_onto_stack(p, c);
  645. lb_add_debug_context_variable(p, c);
  646. return c;
  647. }
  648. lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) {
  649. if (LLVMIsALoadInst(value.value)) {
  650. lbValue res = {};
  651. res.value = LLVMGetOperand(value.value, 0);
  652. res.type = alloc_type_pointer(value.type);
  653. return res;
  654. }
  655. GB_ASSERT(is_type_typed(value.type));
  656. lbAddr res = lb_add_local_generated(p, value.type, false);
  657. lb_addr_store(p, res, value);
  658. return res.addr;
  659. }
  660. lbValue lb_address_from_load(lbProcedure *p, lbValue value) {
  661. if (LLVMIsALoadInst(value.value)) {
  662. lbValue res = {};
  663. res.value = LLVMGetOperand(value.value, 0);
  664. res.type = alloc_type_pointer(value.type);
  665. return res;
  666. }
  667. GB_PANIC("lb_address_from_load");
  668. return {};
  669. }
  670. lbStructFieldRemapping lb_get_struct_remapping(lbModule *m, Type *t) {
  671. t = base_type(t);
  672. LLVMTypeRef struct_type = lb_type(m, t);
  673. auto *field_remapping = map_get(&m->struct_field_remapping, cast(void *)struct_type);
  674. if (field_remapping == nullptr) {
  675. field_remapping = map_get(&m->struct_field_remapping, cast(void *)t);
  676. }
  677. GB_ASSERT(field_remapping != nullptr);
  678. return *field_remapping;
  679. }
  680. i32 lb_convert_struct_index(lbModule *m, Type *t, i32 index) {
  681. if (t->kind == Type_Struct) {
  682. auto field_remapping = lb_get_struct_remapping(m, t);
  683. index = field_remapping[index];
  684. }
  685. return index;
  686. }
  687. LLVMTypeRef lb_type_padding_filler(lbModule *m, i64 padding, i64 padding_align) {
  688. // NOTE(bill): limit to `[N x u64]` to prevent ABI issues
  689. padding_align = gb_clamp(padding_align, 1, 8);
  690. if (padding % padding_align == 0) {
  691. LLVMTypeRef elem = nullptr;
  692. isize len = padding/padding_align;
  693. switch (padding_align) {
  694. case 1: elem = lb_type(m, t_u8); break;
  695. case 2: elem = lb_type(m, t_u16); break;
  696. case 4: elem = lb_type(m, t_u32); break;
  697. case 8: elem = lb_type(m, t_u64); break;
  698. }
  699. GB_ASSERT_MSG(elem != nullptr, "Invalid lb_type_padding_filler padding and padding_align: %lld", padding_align);
  700. if (len != 1) {
  701. return LLVMArrayType(elem, cast(unsigned)len);
  702. } else {
  703. return elem;
  704. }
  705. } else {
  706. return LLVMArrayType(lb_type(m, t_u8), cast(unsigned)padding);
  707. }
  708. }
  709. char const *llvm_type_kinds[] = {
  710. "LLVMVoidTypeKind",
  711. "LLVMHalfTypeKind",
  712. "LLVMFloatTypeKind",
  713. "LLVMDoubleTypeKind",
  714. "LLVMX86_FP80TypeKind",
  715. "LLVMFP128TypeKind",
  716. "LLVMPPC_FP128TypeKind",
  717. "LLVMLabelTypeKind",
  718. "LLVMIntegerTypeKind",
  719. "LLVMFunctionTypeKind",
  720. "LLVMStructTypeKind",
  721. "LLVMArrayTypeKind",
  722. "LLVMPointerTypeKind",
  723. "LLVMVectorTypeKind",
  724. "LLVMMetadataTypeKind",
  725. "LLVMX86_MMXTypeKind",
  726. "LLVMTokenTypeKind",
  727. "LLVMScalableVectorTypeKind",
  728. "LLVMBFloatTypeKind",
  729. };
  730. lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) {
  731. GB_ASSERT(is_type_pointer(s.type));
  732. Type *t = base_type(type_deref(s.type));
  733. Type *result_type = nullptr;
  734. if (is_type_relative_pointer(t)) {
  735. s = lb_addr_get_ptr(p, lb_addr(s));
  736. }
  737. if (is_type_struct(t)) {
  738. result_type = get_struct_field_type(t, index);
  739. } else if (is_type_union(t)) {
  740. GB_ASSERT(index == -1);
  741. return lb_emit_union_tag_ptr(p, s);
  742. } else if (is_type_tuple(t)) {
  743. GB_ASSERT(t->Tuple.variables.count > 0);
  744. result_type = t->Tuple.variables[index]->type;
  745. } else if (is_type_complex(t)) {
  746. Type *ft = base_complex_elem_type(t);
  747. switch (index) {
  748. case 0: result_type = ft; break;
  749. case 1: result_type = ft; break;
  750. }
  751. } else if (is_type_quaternion(t)) {
  752. Type *ft = base_complex_elem_type(t);
  753. switch (index) {
  754. case 0: result_type = ft; break;
  755. case 1: result_type = ft; break;
  756. case 2: result_type = ft; break;
  757. case 3: result_type = ft; break;
  758. }
  759. } else if (is_type_slice(t)) {
  760. switch (index) {
  761. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  762. case 1: result_type = t_int; break;
  763. }
  764. } else if (is_type_string(t)) {
  765. switch (index) {
  766. case 0: result_type = t_u8_ptr; break;
  767. case 1: result_type = t_int; break;
  768. }
  769. } else if (is_type_any(t)) {
  770. switch (index) {
  771. case 0: result_type = t_rawptr; break;
  772. case 1: result_type = t_typeid; break;
  773. }
  774. } else if (is_type_dynamic_array(t)) {
  775. switch (index) {
  776. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  777. case 1: result_type = t_int; break;
  778. case 2: result_type = t_int; break;
  779. case 3: result_type = t_allocator; break;
  780. }
  781. } else if (is_type_map(t)) {
  782. init_map_internal_types(t);
  783. Type *itp = alloc_type_pointer(t->Map.internal_type);
  784. s = lb_emit_transmute(p, s, itp);
  785. Type *gst = t->Map.internal_type;
  786. GB_ASSERT(gst->kind == Type_Struct);
  787. switch (index) {
  788. case 0: result_type = get_struct_field_type(gst, 0); break;
  789. case 1: result_type = get_struct_field_type(gst, 1); break;
  790. }
  791. } else if (is_type_array(t)) {
  792. return lb_emit_array_epi(p, s, index);
  793. } else if (is_type_relative_slice(t)) {
  794. switch (index) {
  795. case 0: result_type = t->RelativeSlice.base_integer; break;
  796. case 1: result_type = t->RelativeSlice.base_integer; break;
  797. }
  798. } else if (is_type_soa_pointer(t)) {
  799. switch (index) {
  800. case 0: result_type = alloc_type_pointer(t->SoaPointer.elem); break;
  801. case 1: result_type = t_int; break;
  802. }
  803. } else {
  804. GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index);
  805. }
  806. GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index);
  807. i32 original_index = index;
  808. index = lb_convert_struct_index(p->module, t, index);
  809. if (lb_is_const(s)) {
  810. // NOTE(bill): this cannot be replaced with lb_emit_epi
  811. lbModule *m = p->module;
  812. lbValue res = {};
  813. LLVMValueRef indices[2] = {llvm_zero(m), LLVMConstInt(lb_type(m, t_i32), index, false)};
  814. res.value = LLVMConstGEP2(lb_type(m, type_deref(s.type)), s.value, indices, gb_count_of(indices));
  815. res.type = alloc_type_pointer(result_type);
  816. return res;
  817. } else {
  818. lbValue res = {};
  819. LLVMTypeRef st = lb_type(p->module, type_deref(s.type));
  820. // gb_printf_err("%s\n", type_to_string(s.type));
  821. // gb_printf_err("%s\n", LLVMPrintTypeToString(LLVMTypeOf(s.value)));
  822. // gb_printf_err("%d\n", index);
  823. GB_ASSERT_MSG(LLVMGetTypeKind(st) == LLVMStructTypeKind, "%s", llvm_type_kinds[LLVMGetTypeKind(st)]);
  824. unsigned count = LLVMCountStructElementTypes(st);
  825. GB_ASSERT_MSG(count >= cast(unsigned)index, "%u %d %d", count, index, original_index);
  826. res.value = LLVMBuildStructGEP2(p->builder, st, s.value, cast(unsigned)index, "");
  827. res.type = alloc_type_pointer(result_type);
  828. return res;
  829. }
  830. }
  831. lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) {
  832. if (LLVMIsALoadInst(s.value)) {
  833. lbValue res = {};
  834. res.value = LLVMGetOperand(s.value, 0);
  835. res.type = alloc_type_pointer(s.type);
  836. lbValue ptr = lb_emit_struct_ep(p, res, index);
  837. return lb_emit_load(p, ptr);
  838. }
  839. Type *t = base_type(s.type);
  840. Type *result_type = nullptr;
  841. switch (t->kind) {
  842. case Type_Basic:
  843. switch (t->Basic.kind) {
  844. case Basic_string:
  845. switch (index) {
  846. case 0: result_type = t_u8_ptr; break;
  847. case 1: result_type = t_int; break;
  848. }
  849. break;
  850. case Basic_any:
  851. switch (index) {
  852. case 0: result_type = t_rawptr; break;
  853. case 1: result_type = t_typeid; break;
  854. }
  855. break;
  856. case Basic_complex32:
  857. case Basic_complex64:
  858. case Basic_complex128:
  859. {
  860. Type *ft = base_complex_elem_type(t);
  861. switch (index) {
  862. case 0: result_type = ft; break;
  863. case 1: result_type = ft; break;
  864. }
  865. break;
  866. }
  867. case Basic_quaternion64:
  868. case Basic_quaternion128:
  869. case Basic_quaternion256:
  870. {
  871. Type *ft = base_complex_elem_type(t);
  872. switch (index) {
  873. case 0: result_type = ft; break;
  874. case 1: result_type = ft; break;
  875. case 2: result_type = ft; break;
  876. case 3: result_type = ft; break;
  877. }
  878. break;
  879. }
  880. }
  881. break;
  882. case Type_Struct:
  883. result_type = get_struct_field_type(t, index);
  884. break;
  885. case Type_Union:
  886. GB_ASSERT(index == -1);
  887. // return lb_emit_union_tag_value(p, s);
  888. GB_PANIC("lb_emit_union_tag_value");
  889. case Type_Tuple:
  890. GB_ASSERT(t->Tuple.variables.count > 0);
  891. result_type = t->Tuple.variables[index]->type;
  892. if (t->Tuple.variables.count == 1) {
  893. return s;
  894. }
  895. break;
  896. case Type_Slice:
  897. switch (index) {
  898. case 0: result_type = alloc_type_pointer(t->Slice.elem); break;
  899. case 1: result_type = t_int; break;
  900. }
  901. break;
  902. case Type_DynamicArray:
  903. switch (index) {
  904. case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break;
  905. case 1: result_type = t_int; break;
  906. case 2: result_type = t_int; break;
  907. case 3: result_type = t_allocator; break;
  908. }
  909. break;
  910. case Type_Map:
  911. {
  912. init_map_internal_types(t);
  913. Type *gst = t->Map.generated_struct_type;
  914. switch (index) {
  915. case 0: result_type = get_struct_field_type(gst, 0); break;
  916. case 1: result_type = get_struct_field_type(gst, 1); break;
  917. }
  918. }
  919. break;
  920. case Type_Array:
  921. result_type = t->Array.elem;
  922. break;
  923. case Type_SoaPointer:
  924. switch (index) {
  925. case 0: result_type = alloc_type_pointer(t->SoaPointer.elem); break;
  926. case 1: result_type = t_int; break;
  927. }
  928. break;
  929. default:
  930. GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index);
  931. break;
  932. }
  933. GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index);
  934. index = lb_convert_struct_index(p->module, t, index);
  935. lbValue res = {};
  936. res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, "");
  937. res.type = result_type;
  938. return res;
  939. }
  940. lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) {
  941. GB_ASSERT(sel.index.count > 0);
  942. Type *type = type_deref(e.type);
  943. for_array(i, sel.index) {
  944. i32 index = cast(i32)sel.index[i];
  945. if (is_type_pointer(type)) {
  946. type = type_deref(type);
  947. e = lb_emit_load(p, e);
  948. }
  949. type = core_type(type);
  950. if (type->kind == Type_SoaPointer) {
  951. lbValue addr = lb_emit_struct_ep(p, e, 0);
  952. lbValue index = lb_emit_struct_ep(p, e, 1);
  953. addr = lb_emit_load(p, addr);
  954. index = lb_emit_load(p, index);
  955. i32 first_index = sel.index[0];
  956. Selection sub_sel = sel;
  957. sub_sel.index.data += 1;
  958. sub_sel.index.count -= 1;
  959. lbValue arr = lb_emit_struct_ep(p, addr, first_index);
  960. Type *t = base_type(type_deref(addr.type));
  961. GB_ASSERT(is_type_soa_struct(t));
  962. if (t->Struct.soa_kind == StructSoa_Fixed) {
  963. e = lb_emit_array_ep(p, arr, index);
  964. } else {
  965. e = lb_emit_ptr_offset(p, lb_emit_load(p, arr), index);
  966. }
  967. } else if (is_type_quaternion(type)) {
  968. e = lb_emit_struct_ep(p, e, index);
  969. } else if (is_type_raw_union(type)) {
  970. type = get_struct_field_type(type, index);
  971. GB_ASSERT(is_type_pointer(e.type));
  972. e = lb_emit_transmute(p, e, alloc_type_pointer(type));
  973. } else if (is_type_struct(type)) {
  974. type = get_struct_field_type(type, index);
  975. e = lb_emit_struct_ep(p, e, index);
  976. } else if (type->kind == Type_Union) {
  977. GB_ASSERT(index == -1);
  978. type = t_type_info_ptr;
  979. e = lb_emit_struct_ep(p, e, index);
  980. } else if (type->kind == Type_Tuple) {
  981. type = type->Tuple.variables[index]->type;
  982. e = lb_emit_struct_ep(p, e, index);
  983. } else if (type->kind == Type_Basic) {
  984. switch (type->Basic.kind) {
  985. case Basic_any: {
  986. if (index == 0) {
  987. type = t_rawptr;
  988. } else if (index == 1) {
  989. type = t_type_info_ptr;
  990. }
  991. e = lb_emit_struct_ep(p, e, index);
  992. break;
  993. }
  994. case Basic_string:
  995. e = lb_emit_struct_ep(p, e, index);
  996. break;
  997. default:
  998. GB_PANIC("un-gep-able type %s", type_to_string(type));
  999. break;
  1000. }
  1001. } else if (type->kind == Type_Slice) {
  1002. e = lb_emit_struct_ep(p, e, index);
  1003. } else if (type->kind == Type_DynamicArray) {
  1004. e = lb_emit_struct_ep(p, e, index);
  1005. } else if (type->kind == Type_Array) {
  1006. e = lb_emit_array_epi(p, e, index);
  1007. } else if (type->kind == Type_Map) {
  1008. e = lb_emit_struct_ep(p, e, index);
  1009. } else if (type->kind == Type_RelativePointer) {
  1010. e = lb_emit_struct_ep(p, e, index);
  1011. } else {
  1012. GB_PANIC("un-gep-able type %s", type_to_string(type));
  1013. }
  1014. }
  1015. return e;
  1016. }
  1017. lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) {
  1018. lbValue ptr = lb_address_from_load_or_generate_local(p, e);
  1019. lbValue res = lb_emit_deep_field_gep(p, ptr, sel);
  1020. return lb_emit_load(p, res);
  1021. }
  1022. lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) {
  1023. Type *t = s.type;
  1024. GB_ASSERT_MSG(is_type_pointer(t), "%s", type_to_string(t));
  1025. Type *st = base_type(type_deref(t));
  1026. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  1027. GB_ASSERT_MSG(is_type_integer(core_type(index.type)), "%s", type_to_string(index.type));
  1028. LLVMValueRef indices[2] = {};
  1029. indices[0] = llvm_zero(p->module);
  1030. indices[1] = lb_emit_conv(p, index, t_int).value;
  1031. Type *ptr = base_array_type(st);
  1032. lbValue res = {};
  1033. if (LLVMIsConstant(s.value) && LLVMIsConstant(index.value)) {
  1034. res.value = LLVMConstGEP2(lb_type(p->module, st), s.value, indices, gb_count_of(indices));
  1035. } else {
  1036. res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, st), s.value, indices, gb_count_of(indices), "");
  1037. }
  1038. res.type = alloc_type_pointer(ptr);
  1039. return res;
  1040. }
  1041. lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) {
  1042. Type *t = s.type;
  1043. GB_ASSERT(is_type_pointer(t));
  1044. Type *st = base_type(type_deref(t));
  1045. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  1046. GB_ASSERT(0 <= index);
  1047. return lb_emit_epi(p, s, index);
  1048. }
  1049. lbValue lb_emit_array_epi(lbModule *m, lbValue s, isize index) {
  1050. Type *t = s.type;
  1051. GB_ASSERT(is_type_pointer(t));
  1052. Type *st = base_type(type_deref(t));
  1053. GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st) || is_type_matrix(st), "%s", type_to_string(st));
  1054. GB_ASSERT(0 <= index);
  1055. return lb_emit_epi(m, s, index);
  1056. }
  1057. lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) {
  1058. index = lb_emit_conv(p, index, t_int);
  1059. LLVMValueRef indices[1] = {index.value};
  1060. lbValue res = {};
  1061. res.type = ptr.type;
  1062. LLVMTypeRef type = lb_type(p->module, type_deref(res.type, true));
  1063. if (lb_is_const(ptr) && lb_is_const(index)) {
  1064. res.value = LLVMConstGEP2(type, ptr.value, indices, 1);
  1065. } else {
  1066. res.value = LLVMBuildGEP2(p->builder, type, ptr.value, indices, 1, "");
  1067. }
  1068. return res;
  1069. }
  1070. lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) {
  1071. Type *t = s.type;
  1072. GB_ASSERT(is_type_pointer(t));
  1073. Type *mt = base_type(type_deref(t));
  1074. if (column == 0) {
  1075. GB_ASSERT_MSG(is_type_matrix(mt) || is_type_array_like(mt), "%s", type_to_string(mt));
  1076. return lb_emit_epi(p, s, row);
  1077. } else if (row == 0 && is_type_array_like(mt)) {
  1078. return lb_emit_epi(p, s, column);
  1079. }
  1080. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1081. isize offset = matrix_indices_to_offset(mt, row, column);
  1082. return lb_emit_epi(p, s, offset);
  1083. }
  1084. lbValue lb_emit_matrix_ep(lbProcedure *p, lbValue s, lbValue row, lbValue column) {
  1085. Type *t = s.type;
  1086. GB_ASSERT(is_type_pointer(t));
  1087. Type *mt = base_type(type_deref(t));
  1088. GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt));
  1089. Type *ptr = base_array_type(mt);
  1090. LLVMValueRef stride_elems = lb_const_int(p->module, t_int, matrix_type_stride_in_elems(mt)).value;
  1091. row = lb_emit_conv(p, row, t_int);
  1092. column = lb_emit_conv(p, column, t_int);
  1093. LLVMValueRef index = LLVMBuildAdd(p->builder, row.value, LLVMBuildMul(p->builder, column.value, stride_elems, ""), "");
  1094. LLVMValueRef indices[2] = {
  1095. LLVMConstInt(lb_type(p->module, t_int), 0, false),
  1096. index,
  1097. };
  1098. LLVMTypeRef type = lb_type(p->module, mt);
  1099. lbValue res = {};
  1100. if (lb_is_const(s)) {
  1101. res.value = LLVMConstGEP2(type, s.value, indices, gb_count_of(indices));
  1102. } else {
  1103. res.value = LLVMBuildGEP2(p->builder, type, s.value, indices, gb_count_of(indices), "");
  1104. }
  1105. res.type = alloc_type_pointer(ptr);
  1106. return res;
  1107. }
  1108. lbValue lb_emit_matrix_ev(lbProcedure *p, lbValue s, isize row, isize column) {
  1109. Type *st = base_type(s.type);
  1110. GB_ASSERT_MSG(is_type_matrix(st), "%s", type_to_string(st));
  1111. lbValue value = lb_address_from_load_or_generate_local(p, s);
  1112. lbValue ptr = lb_emit_matrix_epi(p, value, row, column);
  1113. return lb_emit_load(p, ptr);
  1114. }
  1115. void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) {
  1116. Type *t = lb_addr_type(slice);
  1117. GB_ASSERT(is_type_slice(t));
  1118. lbValue ptr = lb_addr_get_ptr(p, slice);
  1119. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  1120. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1121. }
  1122. void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) {
  1123. Type *t = lb_addr_type(string);
  1124. GB_ASSERT(is_type_string(t));
  1125. lbValue ptr = lb_addr_get_ptr(p, string);
  1126. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem);
  1127. lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len);
  1128. }
  1129. lbValue lb_string_elem(lbProcedure *p, lbValue string) {
  1130. Type *t = base_type(string.type);
  1131. GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string);
  1132. return lb_emit_struct_ev(p, string, 0);
  1133. }
  1134. lbValue lb_string_len(lbProcedure *p, lbValue string) {
  1135. Type *t = base_type(string.type);
  1136. GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t));
  1137. return lb_emit_struct_ev(p, string, 1);
  1138. }
  1139. lbValue lb_cstring_len(lbProcedure *p, lbValue value) {
  1140. GB_ASSERT(is_type_cstring(value.type));
  1141. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1142. args[0] = lb_emit_conv(p, value, t_cstring);
  1143. return lb_emit_runtime_call(p, "cstring_len", args);
  1144. }
  1145. lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) {
  1146. Type *t = type_deref(array_ptr.type);
  1147. GB_ASSERT(is_type_array(t));
  1148. return lb_emit_struct_ep(p, array_ptr, 0);
  1149. }
  1150. lbValue lb_slice_elem(lbProcedure *p, lbValue slice) {
  1151. GB_ASSERT(is_type_slice(slice.type));
  1152. return lb_emit_struct_ev(p, slice, 0);
  1153. }
  1154. lbValue lb_slice_len(lbProcedure *p, lbValue slice) {
  1155. GB_ASSERT(is_type_slice(slice.type) || is_type_relative_slice(slice.type));
  1156. return lb_emit_struct_ev(p, slice, 1);
  1157. }
  1158. lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) {
  1159. GB_ASSERT(is_type_dynamic_array(da.type));
  1160. return lb_emit_struct_ev(p, da, 0);
  1161. }
  1162. lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) {
  1163. GB_ASSERT(is_type_dynamic_array(da.type));
  1164. return lb_emit_struct_ev(p, da, 1);
  1165. }
  1166. lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) {
  1167. GB_ASSERT(is_type_dynamic_array(da.type));
  1168. return lb_emit_struct_ev(p, da, 2);
  1169. }
  1170. lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) {
  1171. GB_ASSERT(is_type_dynamic_array(da.type));
  1172. return lb_emit_struct_ev(p, da, 3);
  1173. }
  1174. lbValue lb_map_entries(lbProcedure *p, lbValue value) {
  1175. Type *t = base_type(value.type);
  1176. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  1177. init_map_internal_types(t);
  1178. i32 index = 1;
  1179. lbValue entries = lb_emit_struct_ev(p, value, index);
  1180. return entries;
  1181. }
  1182. lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) {
  1183. Type *t = base_type(type_deref(value.type));
  1184. GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t));
  1185. init_map_internal_types(t);
  1186. i32 index = 1;
  1187. lbValue entries = lb_emit_struct_ep(p, value, index);
  1188. return entries;
  1189. }
  1190. lbValue lb_map_len(lbProcedure *p, lbValue value) {
  1191. lbValue entries = lb_map_entries(p, value);
  1192. return lb_dynamic_array_len(p, entries);
  1193. }
  1194. lbValue lb_map_cap(lbProcedure *p, lbValue value) {
  1195. lbValue entries = lb_map_entries(p, value);
  1196. return lb_dynamic_array_cap(p, entries);
  1197. }
  1198. lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) {
  1199. Type *t = base_type(value.type);
  1200. bool is_ptr = false;
  1201. if (is_type_pointer(t)) {
  1202. is_ptr = true;
  1203. t = base_type(type_deref(t));
  1204. }
  1205. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1206. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1207. }
  1208. GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice ||
  1209. t->Struct.soa_kind == StructSoa_Dynamic);
  1210. isize n = 0;
  1211. Type *elem = base_type(t->Struct.soa_elem);
  1212. if (elem->kind == Type_Struct) {
  1213. n = cast(isize)elem->Struct.fields.count;
  1214. } else if (elem->kind == Type_Array) {
  1215. n = cast(isize)elem->Array.count;
  1216. } else {
  1217. GB_PANIC("Unreachable");
  1218. }
  1219. if (is_ptr) {
  1220. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1221. return lb_emit_load(p, v);
  1222. }
  1223. return lb_emit_struct_ev(p, value, cast(i32)n);
  1224. }
  1225. lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) {
  1226. Type *t = base_type(value.type);
  1227. bool is_ptr = false;
  1228. if (is_type_pointer(t)) {
  1229. is_ptr = true;
  1230. t = base_type(type_deref(t));
  1231. }
  1232. if (t->Struct.soa_kind == StructSoa_Fixed) {
  1233. return lb_const_int(p->module, t_int, t->Struct.soa_count);
  1234. }
  1235. GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic);
  1236. isize n = 0;
  1237. Type *elem = base_type(t->Struct.soa_elem);
  1238. if (elem->kind == Type_Struct) {
  1239. n = cast(isize)elem->Struct.fields.count+1;
  1240. } else if (elem->kind == Type_Array) {
  1241. n = cast(isize)elem->Array.count+1;
  1242. } else {
  1243. GB_PANIC("Unreachable");
  1244. }
  1245. if (is_ptr) {
  1246. lbValue v = lb_emit_struct_ep(p, value, cast(i32)n);
  1247. return lb_emit_load(p, v);
  1248. }
  1249. return lb_emit_struct_ev(p, value, cast(i32)n);
  1250. }
  1251. lbValue lb_emit_mul_add(lbProcedure *p, lbValue a, lbValue b, lbValue c, Type *t) {
  1252. lbModule *m = p->module;
  1253. a = lb_emit_conv(p, a, t);
  1254. b = lb_emit_conv(p, b, t);
  1255. c = lb_emit_conv(p, c, t);
  1256. bool is_possible = !is_type_different_to_arch_endianness(t) && is_type_float(t);
  1257. if (is_possible) {
  1258. switch (build_context.metrics.arch) {
  1259. case TargetArch_amd64:
  1260. if (type_size_of(t) == 2) {
  1261. is_possible = false;
  1262. }
  1263. break;
  1264. case TargetArch_arm64:
  1265. // possible
  1266. break;
  1267. case TargetArch_i386:
  1268. case TargetArch_wasm32:
  1269. case TargetArch_wasm64:
  1270. is_possible = false;
  1271. break;
  1272. }
  1273. }
  1274. if (is_possible) {
  1275. char const *name = "llvm.fma";
  1276. LLVMTypeRef types[1] = { lb_type(m, t) };
  1277. LLVMValueRef values[3] = {
  1278. a.value,
  1279. b.value,
  1280. c.value };
  1281. LLVMValueRef call = lb_call_intrinsic(p, name, values, gb_count_of(values), types, gb_count_of(types));
  1282. return {call, t};
  1283. } else {
  1284. lbValue x = lb_emit_arith(p, Token_Mul, a, b, t);
  1285. lbValue y = lb_emit_arith(p, Token_Add, x, c, t);
  1286. return y;
  1287. }
  1288. }
  1289. LLVMValueRef llvm_mask_iota(lbModule *m, unsigned start, unsigned count) {
  1290. auto iota = slice_make<LLVMValueRef>(temporary_allocator(), count);
  1291. for (unsigned i = 0; i < count; i++) {
  1292. iota[i] = lb_const_int(m, t_u32, start+i).value;
  1293. }
  1294. return LLVMConstVector(iota.data, count);
  1295. }
  1296. LLVMValueRef llvm_mask_zero(lbModule *m, unsigned count) {
  1297. return LLVMConstNull(LLVMVectorType(lb_type(m, t_u32), count));
  1298. }
  1299. #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMGetUndef((type))
  1300. // #define LLVM_VECTOR_DUMMY_VALUE(type) LLVMConstNull((type))
  1301. LLVMValueRef llvm_basic_shuffle(lbProcedure *p, LLVMValueRef vector, LLVMValueRef mask) {
  1302. return LLVMBuildShuffleVector(p->builder, vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask, "");
  1303. }
  1304. LLVMValueRef llvm_basic_const_shuffle(LLVMValueRef vector, LLVMValueRef mask) {
  1305. return LLVMConstShuffleVector(vector, LLVM_VECTOR_DUMMY_VALUE(LLVMTypeOf(vector)), mask);
  1306. }
  1307. LLVMValueRef llvm_vector_broadcast(lbProcedure *p, LLVMValueRef value, unsigned count) {
  1308. GB_ASSERT(count > 0);
  1309. if (LLVMIsConstant(value)) {
  1310. LLVMValueRef single = LLVMConstVector(&value, 1);
  1311. if (count == 1) {
  1312. return single;
  1313. }
  1314. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1315. return llvm_basic_const_shuffle(single, mask);
  1316. }
  1317. LLVMTypeRef single_type = LLVMVectorType(LLVMTypeOf(value), 1);
  1318. LLVMValueRef single = LLVMBuildBitCast(p->builder, value, single_type, "");
  1319. if (count == 1) {
  1320. return single;
  1321. }
  1322. LLVMValueRef mask = llvm_mask_zero(p->module, count);
  1323. return llvm_basic_shuffle(p, single, mask);
  1324. }
  1325. LLVMValueRef llvm_vector_shuffle_reduction(lbProcedure *p, LLVMValueRef value, LLVMOpcode op_code) {
  1326. LLVMTypeRef original_vector_type = LLVMTypeOf(value);
  1327. GB_ASSERT(LLVMGetTypeKind(original_vector_type) == LLVMVectorTypeKind);
  1328. unsigned len = LLVMGetVectorSize(original_vector_type);
  1329. LLVMValueRef v_zero32 = lb_const_int(p->module, t_u32, 0).value;
  1330. if (len == 1) {
  1331. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1332. }
  1333. GB_ASSERT((len & (len-1)) == 0);
  1334. for (unsigned i = len; i != 1; i >>= 1) {
  1335. unsigned mask_len = i/2;
  1336. LLVMValueRef lhs_mask = llvm_mask_iota(p->module, 0, mask_len);
  1337. LLVMValueRef rhs_mask = llvm_mask_iota(p->module, mask_len, mask_len);
  1338. GB_ASSERT(LLVMTypeOf(lhs_mask) == LLVMTypeOf(rhs_mask));
  1339. LLVMValueRef lhs = llvm_basic_shuffle(p, value, lhs_mask);
  1340. LLVMValueRef rhs = llvm_basic_shuffle(p, value, rhs_mask);
  1341. GB_ASSERT(LLVMTypeOf(lhs) == LLVMTypeOf(rhs));
  1342. value = LLVMBuildBinOp(p->builder, op_code, lhs, rhs, "");
  1343. }
  1344. return LLVMBuildExtractElement(p->builder, value, v_zero32, "");
  1345. }
  1346. LLVMValueRef llvm_vector_expand_to_power_of_two(lbProcedure *p, LLVMValueRef value) {
  1347. LLVMTypeRef vector_type = LLVMTypeOf(value);
  1348. unsigned len = LLVMGetVectorSize(vector_type);
  1349. if (len == 1) {
  1350. return value;
  1351. }
  1352. if ((len & (len-1)) == 0) {
  1353. return value;
  1354. }
  1355. unsigned expanded_len = cast(unsigned)next_pow2(cast(i64)len);
  1356. LLVMValueRef mask = llvm_mask_iota(p->module, 0, expanded_len);
  1357. return LLVMBuildShuffleVector(p->builder, value, LLVMConstNull(vector_type), mask, "");
  1358. }
  1359. LLVMValueRef llvm_vector_reduce_add(lbProcedure *p, LLVMValueRef value) {
  1360. LLVMTypeRef type = LLVMTypeOf(value);
  1361. GB_ASSERT(LLVMGetTypeKind(type) == LLVMVectorTypeKind);
  1362. LLVMTypeRef elem = OdinLLVMGetVectorElementType(type);
  1363. unsigned len = LLVMGetVectorSize(type);
  1364. if (len == 0) {
  1365. return LLVMConstNull(type);
  1366. }
  1367. char const *name = nullptr;
  1368. i32 value_offset = 0;
  1369. i32 value_count = 0;
  1370. switch (LLVMGetTypeKind(elem)) {
  1371. case LLVMHalfTypeKind:
  1372. case LLVMFloatTypeKind:
  1373. case LLVMDoubleTypeKind:
  1374. name = "llvm.vector.reduce.fadd";
  1375. value_offset = 0;
  1376. value_count = 2;
  1377. break;
  1378. case LLVMIntegerTypeKind:
  1379. name = "llvm.vector.reduce.add";
  1380. value_offset = 1;
  1381. value_count = 1;
  1382. break;
  1383. default:
  1384. GB_PANIC("invalid vector type %s", LLVMPrintTypeToString(type));
  1385. break;
  1386. }
  1387. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1388. if (id != 0 && false) {
  1389. LLVMTypeRef types[1] = { type };
  1390. LLVMValueRef values[2] = { LLVMConstNull(elem), value };
  1391. return lb_call_intrinsic(p, name, values + value_offset, value_count, types, gb_count_of(types));
  1392. }
  1393. // Manual reduce
  1394. #if 0
  1395. LLVMValueRef sum = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, 0).value, "");
  1396. for (unsigned i = 0; i < len; i++) {
  1397. LLVMValueRef val = LLVMBuildExtractElement(p->builder, value, lb_const_int(p->module, t_u32, i).value, "");
  1398. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1399. sum = LLVMBuildAdd(p->builder, sum, val, "");
  1400. } else {
  1401. sum = LLVMBuildFAdd(p->builder, sum, val, "");
  1402. }
  1403. }
  1404. return sum;
  1405. #else
  1406. LLVMOpcode op_code = LLVMFAdd;
  1407. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1408. op_code = LLVMAdd;
  1409. }
  1410. unsigned len_pow_2 = prev_pow2(len);
  1411. if (len_pow_2 == len) {
  1412. return llvm_vector_shuffle_reduction(p, value, op_code);
  1413. } else {
  1414. GB_ASSERT(len_pow_2 < len);
  1415. LLVMValueRef lower_mask = llvm_mask_iota(p->module, 0, len_pow_2);
  1416. LLVMValueRef upper_mask = llvm_mask_iota(p->module, len_pow_2, len-len_pow_2);
  1417. LLVMValueRef lower = llvm_basic_shuffle(p, value, lower_mask);
  1418. LLVMValueRef upper = llvm_basic_shuffle(p, value, upper_mask);
  1419. upper = llvm_vector_expand_to_power_of_two(p, upper);
  1420. LLVMValueRef lower_reduced = llvm_vector_shuffle_reduction(p, lower, op_code);
  1421. LLVMValueRef upper_reduced = llvm_vector_shuffle_reduction(p, upper, op_code);
  1422. GB_ASSERT(LLVMTypeOf(lower_reduced) == LLVMTypeOf(upper_reduced));
  1423. return LLVMBuildBinOp(p->builder, op_code, lower_reduced, upper_reduced, "");
  1424. }
  1425. #endif
  1426. }
  1427. LLVMValueRef llvm_vector_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1428. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1429. LLVMTypeRef elem = OdinLLVMGetVectorElementType(LLVMTypeOf(a));
  1430. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1431. return LLVMBuildAdd(p->builder, a, b, "");
  1432. }
  1433. return LLVMBuildFAdd(p->builder, a, b, "");
  1434. }
  1435. LLVMValueRef llvm_vector_mul(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1436. GB_ASSERT(LLVMTypeOf(a) == LLVMTypeOf(b));
  1437. LLVMTypeRef elem = OdinLLVMGetVectorElementType(LLVMTypeOf(a));
  1438. if (LLVMGetTypeKind(elem) == LLVMIntegerTypeKind) {
  1439. return LLVMBuildMul(p->builder, a, b, "");
  1440. }
  1441. return LLVMBuildFMul(p->builder, a, b, "");
  1442. }
  1443. LLVMValueRef llvm_vector_dot(lbProcedure *p, LLVMValueRef a, LLVMValueRef b) {
  1444. return llvm_vector_reduce_add(p, llvm_vector_mul(p, a, b));
  1445. }
  1446. LLVMValueRef llvm_vector_mul_add(lbProcedure *p, LLVMValueRef a, LLVMValueRef b, LLVMValueRef c) {
  1447. LLVMTypeRef t = LLVMTypeOf(a);
  1448. GB_ASSERT(t == LLVMTypeOf(b));
  1449. GB_ASSERT(t == LLVMTypeOf(c));
  1450. GB_ASSERT(LLVMGetTypeKind(t) == LLVMVectorTypeKind);
  1451. LLVMTypeRef elem = OdinLLVMGetVectorElementType(t);
  1452. bool is_possible = false;
  1453. switch (LLVMGetTypeKind(elem)) {
  1454. case LLVMHalfTypeKind:
  1455. is_possible = true;
  1456. break;
  1457. case LLVMFloatTypeKind:
  1458. case LLVMDoubleTypeKind:
  1459. is_possible = true;
  1460. break;
  1461. }
  1462. if (is_possible) {
  1463. char const *name = "llvm.fmuladd";
  1464. LLVMTypeRef types[1] = { t };
  1465. LLVMValueRef values[3] = { a, b, c};
  1466. LLVMValueRef call = lb_call_intrinsic(p, name, values, gb_count_of(values), types, gb_count_of(types));
  1467. return call;
  1468. } else {
  1469. LLVMValueRef x = llvm_vector_mul(p, a, b);
  1470. LLVMValueRef y = llvm_vector_add(p, x, c);
  1471. return y;
  1472. }
  1473. }
  1474. LLVMValueRef llvm_get_inline_asm(LLVMTypeRef func_type, String const &str, String const &clobbers, bool has_side_effects=true, bool is_align_stack=false, LLVMInlineAsmDialect dialect=LLVMInlineAsmDialectATT) {
  1475. return LLVMGetInlineAsm(func_type,
  1476. cast(char *)str.text, cast(size_t)str.len,
  1477. cast(char *)clobbers.text, cast(size_t)clobbers.len,
  1478. has_side_effects, is_align_stack,
  1479. dialect
  1480. #if LLVM_VERSION_MAJOR >= 13
  1481. , /*CanThrow*/false
  1482. #endif
  1483. );
  1484. }
  1485. void lb_set_wasm_import_attributes(LLVMValueRef value, Entity *entity, String import_name) {
  1486. if (!is_arch_wasm()) {
  1487. return;
  1488. }
  1489. String module_name = str_lit("env");
  1490. if (entity->Procedure.foreign_library != nullptr) {
  1491. Entity *foreign_library = entity->Procedure.foreign_library;
  1492. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  1493. GB_ASSERT(foreign_library->LibraryName.paths.count == 1);
  1494. module_name = foreign_library->LibraryName.paths[0];
  1495. if (string_starts_with(import_name, module_name)) {
  1496. import_name = substring(import_name, module_name.len+WASM_MODULE_NAME_SEPARATOR.len, import_name.len);
  1497. }
  1498. }
  1499. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-module", alloc_cstring(permanent_allocator(), module_name));
  1500. LLVMAddTargetDependentFunctionAttr(value, "wasm-import-name", alloc_cstring(permanent_allocator(), import_name));
  1501. }
  1502. void lb_set_wasm_export_attributes(LLVMValueRef value, String export_name) {
  1503. if (!is_arch_wasm()) {
  1504. return;
  1505. }
  1506. LLVMSetLinkage(value, LLVMDLLExportLinkage);
  1507. LLVMSetDLLStorageClass(value, LLVMDLLExportStorageClass);
  1508. LLVMSetVisibility(value, LLVMDefaultVisibility);
  1509. LLVMAddTargetDependentFunctionAttr(value, "wasm-export-name", alloc_cstring(permanent_allocator(), export_name));
  1510. }
  1511. lbAddr lb_handle_objc_find_or_register_selector(lbProcedure *p, String const &name) {
  1512. lbAddr *found = string_map_get(&p->module->objc_selectors, name);
  1513. if (found) {
  1514. return *found;
  1515. } else {
  1516. lbModule *default_module = &p->module->gen->default_module;
  1517. Entity *e = nullptr;
  1518. lbAddr default_addr = lb_add_global_generated(default_module, t_objc_SEL, {}, &e);
  1519. lbValue ptr = lb_find_value_from_entity(p->module, e);
  1520. lbAddr local_addr = lb_addr(ptr);
  1521. string_map_set(&default_module->objc_selectors, name, default_addr);
  1522. if (default_module != p->module) {
  1523. string_map_set(&p->module->objc_selectors, name, local_addr);
  1524. }
  1525. return local_addr;
  1526. }
  1527. }
  1528. lbValue lb_handle_objc_find_selector(lbProcedure *p, Ast *expr) {
  1529. ast_node(ce, CallExpr, expr);
  1530. auto tav = ce->args[0]->tav;
  1531. GB_ASSERT(tav.value.kind == ExactValue_String);
  1532. String name = tav.value.value_string;
  1533. return lb_addr_load(p, lb_handle_objc_find_or_register_selector(p, name));
  1534. }
  1535. lbValue lb_handle_objc_register_selector(lbProcedure *p, Ast *expr) {
  1536. ast_node(ce, CallExpr, expr);
  1537. lbModule *m = p->module;
  1538. auto tav = ce->args[0]->tav;
  1539. GB_ASSERT(tav.value.kind == ExactValue_String);
  1540. String name = tav.value.value_string;
  1541. lbAddr dst = lb_handle_objc_find_or_register_selector(p, name);
  1542. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1543. args[0] = lb_const_value(m, t_cstring, exact_value_string(name));
  1544. lbValue ptr = lb_emit_runtime_call(p, "sel_registerName", args);
  1545. lb_addr_store(p, dst, ptr);
  1546. return lb_addr_load(p, dst);
  1547. }
  1548. lbAddr lb_handle_objc_find_or_register_class(lbProcedure *p, String const &name) {
  1549. lbAddr *found = string_map_get(&p->module->objc_classes, name);
  1550. if (found) {
  1551. return *found;
  1552. } else {
  1553. lbModule *default_module = &p->module->gen->default_module;
  1554. Entity *e = nullptr;
  1555. lbAddr default_addr = lb_add_global_generated(default_module, t_objc_SEL, {}, &e);
  1556. lbValue ptr = lb_find_value_from_entity(p->module, e);
  1557. lbAddr local_addr = lb_addr(ptr);
  1558. string_map_set(&default_module->objc_classes, name, default_addr);
  1559. if (default_module != p->module) {
  1560. string_map_set(&p->module->objc_classes, name, local_addr);
  1561. }
  1562. return local_addr;
  1563. }
  1564. }
  1565. lbValue lb_handle_objc_find_class(lbProcedure *p, Ast *expr) {
  1566. ast_node(ce, CallExpr, expr);
  1567. auto tav = ce->args[0]->tav;
  1568. GB_ASSERT(tav.value.kind == ExactValue_String);
  1569. String name = tav.value.value_string;
  1570. return lb_addr_load(p, lb_handle_objc_find_or_register_class(p, name));
  1571. }
  1572. lbValue lb_handle_objc_register_class(lbProcedure *p, Ast *expr) {
  1573. ast_node(ce, CallExpr, expr);
  1574. lbModule *m = p->module;
  1575. auto tav = ce->args[0]->tav;
  1576. GB_ASSERT(tav.value.kind == ExactValue_String);
  1577. String name = tav.value.value_string;
  1578. lbAddr dst = lb_handle_objc_find_or_register_class(p, name);
  1579. auto args = array_make<lbValue>(permanent_allocator(), 3);
  1580. args[0] = lb_const_nil(m, t_objc_Class);
  1581. args[1] = lb_const_nil(m, t_objc_Class);
  1582. args[2] = lb_const_int(m, t_uint, 0);
  1583. lbValue ptr = lb_emit_runtime_call(p, "objc_allocateClassPair", args);
  1584. lb_addr_store(p, dst, ptr);
  1585. return lb_addr_load(p, dst);
  1586. }
  1587. lbValue lb_handle_objc_id(lbProcedure *p, Ast *expr) {
  1588. TypeAndValue const &tav = type_and_value_of_expr(expr);
  1589. if (tav.mode == Addressing_Type) {
  1590. Type *type = tav.type;
  1591. GB_ASSERT_MSG(type->kind == Type_Named, "%s", type_to_string(type));
  1592. Entity *e = type->Named.type_name;
  1593. GB_ASSERT(e->kind == Entity_TypeName);
  1594. String name = e->TypeName.objc_class_name;
  1595. lbAddr *found = string_map_get(&p->module->objc_classes, name);
  1596. if (found) {
  1597. return lb_addr_load(p, *found);
  1598. } else {
  1599. lbModule *default_module = &p->module->gen->default_module;
  1600. Entity *e = nullptr;
  1601. lbAddr default_addr = lb_add_global_generated(default_module, t_objc_Class, {}, &e);
  1602. lbValue ptr = lb_find_value_from_entity(p->module, e);
  1603. lbAddr local_addr = lb_addr(ptr);
  1604. string_map_set(&default_module->objc_classes, name, default_addr);
  1605. if (default_module != p->module) {
  1606. string_map_set(&p->module->objc_classes, name, local_addr);
  1607. }
  1608. return lb_addr_load(p, local_addr);
  1609. }
  1610. }
  1611. return lb_build_expr(p, expr);
  1612. }
  1613. lbValue lb_handle_objc_send(lbProcedure *p, Ast *expr) {
  1614. ast_node(ce, CallExpr, expr);
  1615. lbModule *m = p->module;
  1616. CheckerInfo *info = m->info;
  1617. ObjcMsgData data = map_must_get(&info->objc_msgSend_types, expr);
  1618. GB_ASSERT(data.proc_type != nullptr);
  1619. GB_ASSERT(ce->args.count >= 3);
  1620. auto args = array_make<lbValue>(permanent_allocator(), 0, ce->args.count-1);
  1621. lbValue id = lb_handle_objc_id(p, ce->args[1]);
  1622. Ast *sel_expr = ce->args[2];
  1623. GB_ASSERT(sel_expr->tav.value.kind == ExactValue_String);
  1624. lbValue sel = lb_addr_load(p, lb_handle_objc_find_or_register_selector(p, sel_expr->tav.value.value_string));
  1625. array_add(&args, id);
  1626. array_add(&args, sel);
  1627. for (isize i = 3; i < ce->args.count; i++) {
  1628. lbValue arg = lb_build_expr(p, ce->args[i]);
  1629. array_add(&args, arg);
  1630. }
  1631. lbValue the_proc = {};
  1632. switch (data.kind) {
  1633. default:
  1634. GB_PANIC("unhandled ObjcMsgKind %u", data.kind);
  1635. break;
  1636. case ObjcMsg_normal: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend")); break;
  1637. case ObjcMsg_fpret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fpret")); break;
  1638. case ObjcMsg_fp2ret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_fp2ret")); break;
  1639. case ObjcMsg_stret: the_proc = lb_lookup_runtime_procedure(m, str_lit("objc_msgSend_stret")); break;
  1640. }
  1641. the_proc = lb_emit_conv(p, the_proc, data.proc_type);
  1642. return lb_emit_call(p, the_proc, args);
  1643. }
  1644. LLVMAtomicOrdering llvm_atomic_ordering_from_odin(ExactValue const &value) {
  1645. GB_ASSERT(value.kind == ExactValue_Integer);
  1646. i64 v = exact_value_to_i64(value);
  1647. switch (v) {
  1648. case OdinAtomicMemoryOrder_relaxed: return LLVMAtomicOrderingUnordered;
  1649. case OdinAtomicMemoryOrder_consume: return LLVMAtomicOrderingMonotonic;
  1650. case OdinAtomicMemoryOrder_acquire: return LLVMAtomicOrderingAcquire;
  1651. case OdinAtomicMemoryOrder_release: return LLVMAtomicOrderingRelease;
  1652. case OdinAtomicMemoryOrder_acq_rel: return LLVMAtomicOrderingAcquireRelease;
  1653. case OdinAtomicMemoryOrder_seq_cst: return LLVMAtomicOrderingSequentiallyConsistent;
  1654. }
  1655. GB_PANIC("Unknown atomic ordering");
  1656. return LLVMAtomicOrderingSequentiallyConsistent;
  1657. }
  1658. LLVMAtomicOrdering llvm_atomic_ordering_from_odin(Ast *expr) {
  1659. ExactValue value = type_and_value_of_expr(expr).value;
  1660. return llvm_atomic_ordering_from_odin(value);
  1661. }