llvm_backend_stmt.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684
  1. gb_internal void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) {
  2. if (vd == nullptr || vd->is_mutable) {
  3. return;
  4. }
  5. auto *min_dep_set = &p->module->info->minimum_dependency_set;
  6. static i32 global_guid = 0;
  7. for (Ast *ident : vd->names) {
  8. GB_ASSERT(ident->kind == Ast_Ident);
  9. Entity *e = entity_of_node(ident);
  10. GB_ASSERT(e != nullptr);
  11. if (e->kind != Entity_TypeName) {
  12. continue;
  13. }
  14. bool polymorphic_struct = false;
  15. if (e->type != nullptr && e->kind == Entity_TypeName) {
  16. Type *bt = base_type(e->type);
  17. if (bt->kind == Type_Struct) {
  18. polymorphic_struct = bt->Struct.is_polymorphic;
  19. }
  20. }
  21. if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) {
  22. continue;
  23. }
  24. if (e->TypeName.ir_mangled_name.len != 0) {
  25. // NOTE(bill): Already set
  26. continue;
  27. }
  28. lb_set_nested_type_name_ir_mangled_name(e, p, p->module);
  29. }
  30. for_array(i, vd->names) {
  31. Ast *ident = vd->names[i];
  32. GB_ASSERT(ident->kind == Ast_Ident);
  33. Entity *e = entity_of_node(ident);
  34. GB_ASSERT(e != nullptr);
  35. if (e->kind != Entity_Procedure) {
  36. continue;
  37. }
  38. GB_ASSERT (vd->values[i] != nullptr);
  39. Ast *value = unparen_expr(vd->values[i]);
  40. if (value->kind != Ast_ProcLit) {
  41. continue; // It's an alias
  42. }
  43. DeclInfo *decl = decl_info_of_entity(e);
  44. ast_node(pl, ProcLit, decl->proc_lit);
  45. if (pl->body != nullptr) {
  46. GenProcsData *gpd = e->Procedure.gen_procs;
  47. if (gpd) {
  48. rw_mutex_shared_lock(&gpd->mutex);
  49. for (Entity *e : gpd->procs) {
  50. if (!ptr_set_exists(min_dep_set, e)) {
  51. continue;
  52. }
  53. DeclInfo *d = decl_info_of_entity(e);
  54. lb_build_nested_proc(p, &d->proc_lit->ProcLit, e);
  55. }
  56. rw_mutex_shared_unlock(&gpd->mutex);
  57. } else {
  58. lb_build_nested_proc(p, pl, e);
  59. }
  60. } else {
  61. // FFI - Foreign function interace
  62. String original_name = e->token.string;
  63. String name = original_name;
  64. if (e->Procedure.is_foreign) {
  65. lb_add_foreign_library_path(p->module, e->Procedure.foreign_library);
  66. }
  67. if (e->Procedure.link_name.len > 0) {
  68. name = e->Procedure.link_name;
  69. }
  70. lbValue *prev_value = string_map_get(&p->module->members, name);
  71. if (prev_value != nullptr) {
  72. // NOTE(bill): Don't do mutliple declarations in the IR
  73. return;
  74. }
  75. e->Procedure.link_name = name;
  76. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  77. lbValue value = {};
  78. value.value = nested_proc->value;
  79. value.type = nested_proc->type;
  80. array_add(&p->module->procedures_to_generate, nested_proc);
  81. array_add(&p->children, nested_proc);
  82. string_map_set(&p->module->members, name, value);
  83. }
  84. }
  85. }
  86. gb_internal void lb_build_stmt_list(lbProcedure *p, Slice<Ast *> const &stmts) {
  87. for (Ast *stmt : stmts) {
  88. switch (stmt->kind) {
  89. case_ast_node(vd, ValueDecl, stmt);
  90. lb_build_constant_value_decl(p, vd);
  91. case_end;
  92. case_ast_node(fb, ForeignBlockDecl, stmt);
  93. ast_node(block, BlockStmt, fb->body);
  94. lb_build_stmt_list(p, block->stmts);
  95. case_end;
  96. }
  97. }
  98. for (Ast *stmt : stmts) {
  99. lb_build_stmt(p, stmt);
  100. }
  101. }
  102. gb_internal lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) {
  103. GB_ASSERT(ident->kind == Ast_Ident);
  104. Entity *e = entity_of_node(ident);
  105. GB_ASSERT(e->kind == Entity_Label);
  106. for (lbBranchBlocks const &b : p->branch_blocks) {
  107. if (b.label == e->Label.node) {
  108. return b;
  109. }
  110. }
  111. GB_PANIC("Unreachable");
  112. lbBranchBlocks empty = {};
  113. return empty;
  114. }
  115. gb_internal lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) {
  116. lbTargetList *tl = gb_alloc_item(permanent_allocator(), lbTargetList);
  117. tl->prev = p->target_list;
  118. tl->break_ = break_;
  119. tl->continue_ = continue_;
  120. tl->fallthrough_ = fallthrough_;
  121. p->target_list = tl;
  122. if (label != nullptr) { // Set label blocks
  123. GB_ASSERT(label->kind == Ast_Label);
  124. for (lbBranchBlocks &b : p->branch_blocks) {
  125. GB_ASSERT(b.label != nullptr && label != nullptr);
  126. GB_ASSERT(b.label->kind == Ast_Label);
  127. if (b.label == label) {
  128. b.break_ = break_;
  129. b.continue_ = continue_;
  130. return tl;
  131. }
  132. }
  133. GB_PANIC("Unreachable");
  134. }
  135. return tl;
  136. }
  137. gb_internal void lb_pop_target_list(lbProcedure *p) {
  138. p->target_list = p->target_list->prev;
  139. }
  140. gb_internal void lb_open_scope(lbProcedure *p, Scope *s) {
  141. lbModule *m = p->module;
  142. if (m->debug_builder) {
  143. LLVMMetadataRef curr_metadata = lb_get_llvm_metadata(m, s);
  144. if (s != nullptr && s->node != nullptr && curr_metadata == nullptr) {
  145. Token token = ast_token(s->node);
  146. unsigned line = cast(unsigned)token.pos.line;
  147. unsigned column = cast(unsigned)token.pos.column;
  148. LLVMMetadataRef file = nullptr;
  149. AstFile *ast_file = s->node->file();
  150. if (ast_file != nullptr) {
  151. file = lb_get_llvm_metadata(m, ast_file);
  152. }
  153. LLVMMetadataRef scope = nullptr;
  154. if (p->scope_stack.count > 0) {
  155. scope = lb_get_llvm_metadata(m, p->scope_stack[p->scope_stack.count-1]);
  156. }
  157. if (scope == nullptr) {
  158. scope = lb_get_llvm_metadata(m, p);
  159. }
  160. GB_ASSERT_MSG(scope != nullptr, "%.*s", LIT(p->name));
  161. if (m->debug_builder) {
  162. LLVMMetadataRef res = LLVMDIBuilderCreateLexicalBlock(m->debug_builder, scope,
  163. file, line, column
  164. );
  165. lb_set_llvm_metadata(m, s, res);
  166. }
  167. }
  168. }
  169. p->scope_index += 1;
  170. array_add(&p->scope_stack, s);
  171. }
  172. gb_internal void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) {
  173. lb_emit_defer_stmts(p, kind, block);
  174. GB_ASSERT(p->scope_index > 0);
  175. // NOTE(bill): Remove `context`s made in that scope
  176. while (p->context_stack.count > 0) {
  177. lbContextData *ctx = &p->context_stack[p->context_stack.count-1];
  178. if (ctx->scope_index >= p->scope_index) {
  179. array_pop(&p->context_stack);
  180. } else {
  181. break;
  182. }
  183. }
  184. p->scope_index -= 1;
  185. array_pop(&p->scope_stack);
  186. }
  187. gb_internal void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) {
  188. TypeAndValue tv = type_and_value_of_expr(ws->cond);
  189. GB_ASSERT(is_type_boolean(tv.type));
  190. GB_ASSERT(tv.value.kind == ExactValue_Bool);
  191. if (tv.value.value_bool) {
  192. lb_build_stmt_list(p, ws->body->BlockStmt.stmts);
  193. } else if (ws->else_stmt) {
  194. switch (ws->else_stmt->kind) {
  195. case Ast_BlockStmt:
  196. lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts);
  197. break;
  198. case Ast_WhenStmt:
  199. lb_build_when_stmt(p, &ws->else_stmt->WhenStmt);
  200. break;
  201. default:
  202. GB_PANIC("Invalid 'else' statement in 'when' statement");
  203. break;
  204. }
  205. }
  206. }
  207. gb_internal void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr,
  208. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_,
  209. bool is_reverse) {
  210. lbModule *m = p->module;
  211. lbValue count = {};
  212. Type *expr_type = base_type(type_deref(expr.type));
  213. switch (expr_type->kind) {
  214. case Type_Array:
  215. count = lb_const_int(m, t_int, expr_type->Array.count);
  216. break;
  217. }
  218. lbValue val = {};
  219. lbValue idx = {};
  220. lbBlock *loop = nullptr;
  221. lbBlock *done = nullptr;
  222. lbBlock *body = nullptr;
  223. loop = lb_create_block(p, "for.index.loop");
  224. body = lb_create_block(p, "for.index.body");
  225. done = lb_create_block(p, "for.index.done");
  226. lbAddr index = lb_add_local_generated(p, t_int, false);
  227. if (!is_reverse) {
  228. /*
  229. for x, i in array {
  230. ...
  231. }
  232. i := -1
  233. for {
  234. i += 1
  235. if !(i < len(array)) {
  236. break
  237. }
  238. #no_bounds_check x := array[i]
  239. ...
  240. }
  241. */
  242. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  243. lb_emit_jump(p, loop);
  244. lb_start_block(p, loop);
  245. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  246. lb_addr_store(p, index, incr);
  247. if (count.value == nullptr) {
  248. GB_ASSERT(count_ptr.value != nullptr);
  249. count = lb_emit_load(p, count_ptr);
  250. }
  251. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  252. lb_emit_if(p, cond, body, done);
  253. } else {
  254. // NOTE(bill): REVERSED LOGIC
  255. /*
  256. #reverse for x, i in array {
  257. ...
  258. }
  259. i := len(array)
  260. for {
  261. i -= 1
  262. if i < 0 {
  263. break
  264. }
  265. #no_bounds_check x := array[i]
  266. ...
  267. }
  268. */
  269. if (count.value == nullptr) {
  270. GB_ASSERT(count_ptr.value != nullptr);
  271. count = lb_emit_load(p, count_ptr);
  272. }
  273. count = lb_emit_conv(p, count, t_int);
  274. lb_addr_store(p, index, count);
  275. lb_emit_jump(p, loop);
  276. lb_start_block(p, loop);
  277. lbValue incr = lb_emit_arith(p, Token_Sub, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  278. lb_addr_store(p, index, incr);
  279. lbValue anti_cond = lb_emit_comp(p, Token_Lt, incr, lb_const_int(m, t_int, 0));
  280. lb_emit_if(p, anti_cond, done, body);
  281. }
  282. lb_start_block(p, body);
  283. idx = lb_addr_load(p, index);
  284. switch (expr_type->kind) {
  285. case Type_Array: {
  286. if (val_type != nullptr) {
  287. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  288. }
  289. break;
  290. }
  291. case Type_EnumeratedArray: {
  292. if (val_type != nullptr) {
  293. val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx));
  294. // NOTE(bill): Override the idx value for the enumeration
  295. Type *index_type = expr_type->EnumeratedArray.index;
  296. if (compare_exact_values(Token_NotEq, *expr_type->EnumeratedArray.min_value, exact_value_u64(0))) {
  297. idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, *expr_type->EnumeratedArray.min_value), index_type);
  298. }
  299. }
  300. break;
  301. }
  302. case Type_Slice: {
  303. if (val_type != nullptr) {
  304. lbValue elem = lb_slice_elem(p, expr);
  305. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  306. }
  307. break;
  308. }
  309. case Type_DynamicArray: {
  310. if (val_type != nullptr) {
  311. lbValue elem = lb_emit_struct_ep(p, expr, 0);
  312. elem = lb_emit_load(p, elem);
  313. val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx));
  314. }
  315. break;
  316. }
  317. case Type_Struct: {
  318. GB_ASSERT(is_type_soa_struct(expr_type));
  319. break;
  320. }
  321. default:
  322. GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type));
  323. break;
  324. }
  325. if (val_) *val_ = val;
  326. if (idx_) *idx_ = idx;
  327. if (loop_) *loop_ = loop;
  328. if (done_) *done_ = done;
  329. }
  330. gb_internal lbValue lb_map_cell_index_static(lbProcedure *p, Type *type, lbValue cells_ptr, lbValue index) {
  331. i64 size, len;
  332. i64 elem_sz = type_size_of(type);
  333. map_cell_size_and_len(type, &size, &len);
  334. index = lb_emit_conv(p, index, t_uintptr);
  335. if (size == len*elem_sz) {
  336. lbValue elems_ptr = lb_emit_conv(p, cells_ptr, alloc_type_pointer(type));
  337. return lb_emit_ptr_offset(p, elems_ptr, index);
  338. }
  339. lbValue cell_index = {};
  340. lbValue data_index = {};
  341. lbValue size_const = lb_const_int(p->module, t_uintptr, size);
  342. lbValue len_const = lb_const_int(p->module, t_uintptr, len);
  343. if (is_power_of_two(len)) {
  344. u64 log2_len = floor_log2(cast(u64)len);
  345. cell_index = log2_len == 0 ? index : lb_emit_arith(p, Token_Shr, index, lb_const_int(p->module, t_uintptr, log2_len), t_uintptr);
  346. data_index = lb_emit_arith(p, Token_And, index, lb_const_int(p->module, t_uintptr, len-1), t_uintptr);
  347. } else {
  348. cell_index = lb_emit_arith(p, Token_Quo, index, len_const, t_uintptr);
  349. data_index = lb_emit_arith(p, Token_Mod, index, len_const, t_uintptr);
  350. }
  351. lbValue elems_ptr = lb_emit_conv(p, cells_ptr, t_uintptr);
  352. lbValue cell_offset = lb_emit_arith(p, Token_Mul, size_const, cell_index, t_uintptr);
  353. elems_ptr = lb_emit_arith(p, Token_Add, elems_ptr, cell_offset, t_uintptr);
  354. elems_ptr = lb_emit_conv(p, elems_ptr, alloc_type_pointer(type));
  355. return lb_emit_ptr_offset(p, elems_ptr, data_index);
  356. }
  357. gb_internal lbValue lb_map_hash_is_valid(lbProcedure *p, lbValue hash) {
  358. // N :: size_of(uintptr)*8 - 1
  359. // (hash != 0) & (hash>>N == 0)
  360. u64 top_bit_index = cast(u64)(type_size_of(t_uintptr)*8 - 1);
  361. lbValue shift_amount = lb_const_int(p->module, t_uintptr, top_bit_index);
  362. lbValue zero = lb_const_int(p->module, t_uintptr, 0);
  363. lbValue not_empty = lb_emit_comp(p, Token_NotEq, hash, zero);
  364. lbValue not_deleted = lb_emit_arith(p, Token_Shr, hash, shift_amount, t_uintptr);
  365. not_deleted = lb_emit_comp(p, Token_CmpEq, not_deleted, zero);
  366. return lb_emit_arith(p, Token_And, not_deleted, not_empty, t_uintptr);
  367. }
  368. gb_internal void lb_build_range_map(lbProcedure *p, lbValue expr, Type *val_type,
  369. lbValue *val_, lbValue *key_, lbBlock **loop_, lbBlock **done_) {
  370. lbModule *m = p->module;
  371. Type *type = base_type(type_deref(expr.type));
  372. GB_ASSERT(type->kind == Type_Map);
  373. lbValue idx = {};
  374. lbBlock *loop = nullptr;
  375. lbBlock *done = nullptr;
  376. lbBlock *body = nullptr;
  377. lbBlock *hash_check = nullptr;
  378. lbAddr index = lb_add_local_generated(p, t_int, false);
  379. lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1));
  380. loop = lb_create_block(p, "for.index.loop");
  381. lb_emit_jump(p, loop);
  382. lb_start_block(p, loop);
  383. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int);
  384. lb_addr_store(p, index, incr);
  385. hash_check = lb_create_block(p, "for.index.hash_check");
  386. body = lb_create_block(p, "for.index.body");
  387. done = lb_create_block(p, "for.index.done");
  388. lbValue map_value = lb_emit_load(p, expr);
  389. lbValue capacity = lb_map_cap(p, map_value);
  390. lbValue cond = lb_emit_comp(p, Token_Lt, incr, capacity);
  391. lb_emit_if(p, cond, hash_check, done);
  392. lb_start_block(p, hash_check);
  393. idx = lb_addr_load(p, index);
  394. lbValue ks = lb_map_data_uintptr(p, map_value);
  395. lbValue vs = lb_emit_conv(p, lb_map_cell_index_static(p, type->Map.key, ks, capacity), alloc_type_pointer(type->Map.value));
  396. lbValue hs = lb_emit_conv(p, lb_map_cell_index_static(p, type->Map.value, vs, capacity), alloc_type_pointer(t_uintptr));
  397. // NOTE(bill): no need to use lb_map_cell_index_static for that hashes
  398. // since it will always be packed without padding into the cells
  399. lbValue hash = lb_emit_load(p, lb_emit_ptr_offset(p, hs, idx));
  400. lbValue hash_cond = lb_map_hash_is_valid(p, hash);
  401. lb_emit_if(p, hash_cond, body, loop);
  402. lb_start_block(p, body);
  403. lbValue key_ptr = lb_map_cell_index_static(p, type->Map.key, ks, idx);
  404. lbValue val_ptr = lb_map_cell_index_static(p, type->Map.value, vs, idx);
  405. lbValue key = lb_emit_load(p, key_ptr);
  406. lbValue val = lb_emit_load(p, val_ptr);
  407. if (val_) *val_ = val;
  408. if (key_) *key_ = key;
  409. if (loop_) *loop_ = loop;
  410. if (done_) *done_ = done;
  411. }
  412. gb_internal void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type,
  413. lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_,
  414. bool is_reverse) {
  415. lbModule *m = p->module;
  416. lbValue count = lb_const_int(m, t_int, 0);
  417. Type *expr_type = base_type(expr.type);
  418. switch (expr_type->kind) {
  419. case Type_Basic:
  420. count = lb_string_len(p, expr);
  421. break;
  422. default:
  423. GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type));
  424. break;
  425. }
  426. lbValue val = {};
  427. lbValue idx = {};
  428. lbBlock *loop = nullptr;
  429. lbBlock *done = nullptr;
  430. lbBlock *body = nullptr;
  431. loop = lb_create_block(p, "for.string.loop");
  432. body = lb_create_block(p, "for.string.body");
  433. done = lb_create_block(p, "for.string.done");
  434. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  435. lbValue offset = {};
  436. lbValue cond = {};
  437. if (!is_reverse) {
  438. /*
  439. for c, offset in str {
  440. ...
  441. }
  442. offset := 0
  443. for offset < len(str) {
  444. c, _w := string_decode_rune(str[offset:])
  445. ...
  446. offset += _w
  447. }
  448. */
  449. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  450. lb_emit_jump(p, loop);
  451. lb_start_block(p, loop);
  452. offset = lb_addr_load(p, offset_);
  453. cond = lb_emit_comp(p, Token_Lt, offset, count);
  454. } else {
  455. // NOTE(bill): REVERSED LOGIC
  456. /*
  457. #reverse for c, offset in str {
  458. ...
  459. }
  460. offset := len(str)
  461. for offset > 0 {
  462. c, _w := string_decode_last_rune(str[:offset])
  463. offset -= _w
  464. ...
  465. }
  466. */
  467. lb_addr_store(p, offset_, count);
  468. lb_emit_jump(p, loop);
  469. lb_start_block(p, loop);
  470. offset = lb_addr_load(p, offset_);
  471. cond = lb_emit_comp(p, Token_Gt, offset, lb_const_int(m, t_int, 0));
  472. }
  473. lb_emit_if(p, cond, body, done);
  474. lb_start_block(p, body);
  475. lbValue rune_and_len = {};
  476. if (!is_reverse) {
  477. lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset);
  478. lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int);
  479. auto args = array_make<lbValue>(permanent_allocator(), 1);
  480. args[0] = lb_emit_string(p, str_elem, str_len);
  481. rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args);
  482. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  483. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int));
  484. idx = offset;
  485. } else {
  486. // NOTE(bill): REVERSED LOGIC
  487. lbValue str_elem = lb_string_elem(p, expr);
  488. lbValue str_len = offset;
  489. auto args = array_make<lbValue>(permanent_allocator(), 1);
  490. args[0] = lb_emit_string(p, str_elem, str_len);
  491. rune_and_len = lb_emit_runtime_call(p, "string_decode_last_rune", args);
  492. lbValue len = lb_emit_struct_ev(p, rune_and_len, 1);
  493. lb_addr_store(p, offset_, lb_emit_arith(p, Token_Sub, offset, len, t_int));
  494. idx = lb_addr_load(p, offset_);
  495. }
  496. if (val_type != nullptr) {
  497. val = lb_emit_struct_ev(p, rune_and_len, 0);
  498. }
  499. if (val_) *val_ = val;
  500. if (idx_) *idx_ = idx;
  501. if (loop_) *loop_ = loop;
  502. if (done_) *done_ = done;
  503. }
  504. gb_internal Ast *lb_strip_and_prefix(Ast *ident) {
  505. if (ident != nullptr) {
  506. if (ident->kind == Ast_UnaryExpr && ident->UnaryExpr.op.kind == Token_And) {
  507. ident = ident->UnaryExpr.expr;
  508. }
  509. GB_ASSERT(ident->kind == Ast_Ident);
  510. }
  511. return ident;
  512. }
  513. gb_internal void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node,
  514. AstRangeStmt *rs, Scope *scope) {
  515. bool ADD_EXTRA_WRAPPING_CHECK = true;
  516. lbModule *m = p->module;
  517. lb_open_scope(p, scope);
  518. Ast *val0 = rs->vals.count > 0 ? lb_strip_and_prefix(rs->vals[0]) : nullptr;
  519. Ast *val1 = rs->vals.count > 1 ? lb_strip_and_prefix(rs->vals[1]) : nullptr;
  520. Type *val0_type = nullptr;
  521. Type *val1_type = nullptr;
  522. if (val0 != nullptr && !is_blank_ident(val0)) {
  523. val0_type = type_of_expr(val0);
  524. }
  525. if (val1 != nullptr && !is_blank_ident(val1)) {
  526. val1_type = type_of_expr(val1);
  527. }
  528. TokenKind op = Token_Lt;
  529. switch (node->op.kind) {
  530. case Token_Ellipsis: op = Token_LtEq; break;
  531. case Token_RangeFull: op = Token_LtEq; break;
  532. case Token_RangeHalf: op = Token_Lt; break;
  533. default: GB_PANIC("Invalid interval operator"); break;
  534. }
  535. lbValue lower = lb_build_expr(p, node->left);
  536. lbValue upper = {}; // initialized each time in the loop
  537. lbAddr value;
  538. if (val0_type != nullptr) {
  539. Entity *e = entity_of_node(val0);
  540. value = lb_add_local(p, val0_type, e, false);
  541. } else {
  542. value = lb_add_local_generated(p, lower.type, false);
  543. }
  544. lb_addr_store(p, value, lower);
  545. lbAddr index;
  546. if (val1_type != nullptr) {
  547. Entity *e = entity_of_node(val1);
  548. index = lb_add_local(p, val1_type, e, false);
  549. } else {
  550. index = lb_add_local_generated(p, t_int, false);
  551. }
  552. lb_addr_store(p, index, lb_const_int(m, t_int, 0));
  553. lbBlock *loop = lb_create_block(p, "for.interval.loop");
  554. lbBlock *body = lb_create_block(p, "for.interval.body");
  555. lbBlock *done = lb_create_block(p, "for.interval.done");
  556. lb_emit_jump(p, loop);
  557. lb_start_block(p, loop);
  558. upper = lb_build_expr(p, node->right);
  559. lbValue curr_value = lb_addr_load(p, value);
  560. lbValue cond = lb_emit_comp(p, op, curr_value, upper);
  561. lb_emit_if(p, cond, body, done);
  562. lb_start_block(p, body);
  563. lbValue val = lb_addr_load(p, value);
  564. lbValue idx = lb_addr_load(p, index);
  565. if (val0_type) lb_store_range_stmt_val(p, val0, val);
  566. if (val1_type) lb_store_range_stmt_val(p, val1, idx);
  567. {
  568. // NOTE: this check block will most likely be optimized out, and is here
  569. // to make this code easier to read
  570. lbBlock *check = nullptr;
  571. lbBlock *post = lb_create_block(p, "for.interval.post");
  572. lbBlock *continue_block = post;
  573. if (ADD_EXTRA_WRAPPING_CHECK &&
  574. op == Token_LtEq) {
  575. check = lb_create_block(p, "for.interval.check");
  576. continue_block = check;
  577. }
  578. lb_push_target_list(p, rs->label, done, continue_block, nullptr);
  579. lb_build_stmt(p, rs->body);
  580. lb_close_scope(p, lbDeferExit_Default, nullptr);
  581. lb_pop_target_list(p);
  582. if (check != nullptr) {
  583. lb_emit_jump(p, check);
  584. lb_start_block(p, check);
  585. lbValue check_cond = lb_emit_comp(p, Token_NotEq, curr_value, upper);
  586. lb_emit_if(p, check_cond, post, done);
  587. } else {
  588. lb_emit_jump(p, post);
  589. }
  590. lb_start_block(p, post);
  591. lb_emit_increment(p, value.addr);
  592. lb_emit_increment(p, index.addr);
  593. lb_emit_jump(p, loop);
  594. }
  595. lb_start_block(p, done);
  596. }
  597. gb_internal void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) {
  598. lbModule *m = p->module;
  599. Type *t = enum_type;
  600. GB_ASSERT(is_type_enum(t));
  601. t = base_type(t);
  602. Type *core_elem = core_type(t);
  603. GB_ASSERT(t->kind == Type_Enum);
  604. i64 enum_count = t->Enum.fields.count;
  605. lbValue max_count = lb_const_int(m, t_int, enum_count);
  606. lbValue ti = lb_type_info(m, t);
  607. lbValue variant = lb_emit_struct_ep(p, ti, 4);
  608. lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr);
  609. lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2));
  610. lbValue values_data = lb_slice_elem(p, values);
  611. lbAddr offset_ = lb_add_local_generated(p, t_int, false);
  612. lb_addr_store(p, offset_, lb_const_int(m, t_int, 0));
  613. lbBlock *loop = lb_create_block(p, "for.enum.loop");
  614. lb_emit_jump(p, loop);
  615. lb_start_block(p, loop);
  616. lbBlock *body = lb_create_block(p, "for.enum.body");
  617. lbBlock *done = lb_create_block(p, "for.enum.done");
  618. lbValue offset = lb_addr_load(p, offset_);
  619. lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count);
  620. lb_emit_if(p, cond, body, done);
  621. lb_start_block(p, body);
  622. lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset);
  623. lb_emit_increment(p, offset_.addr);
  624. lbValue val = {};
  625. if (val_type != nullptr) {
  626. GB_ASSERT(are_types_identical(enum_type, val_type));
  627. if (is_type_integer(core_elem)) {
  628. lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr));
  629. val = lb_emit_conv(p, i, t);
  630. } else {
  631. GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem));
  632. }
  633. }
  634. if (val_) *val_ = val;
  635. if (idx_) *idx_ = offset;
  636. if (loop_) *loop_ = loop;
  637. if (done_) *done_ = done;
  638. }
  639. gb_internal void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type,
  640. lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) {
  641. lbBlock *loop = lb_create_block(p, "for.tuple.loop");
  642. lb_emit_jump(p, loop);
  643. lb_start_block(p, loop);
  644. lbBlock *body = lb_create_block(p, "for.tuple.body");
  645. lbBlock *done = lb_create_block(p, "for.tuple.done");
  646. lbValue tuple_value = lb_build_expr(p, expr);
  647. Type *tuple = tuple_value.type;
  648. GB_ASSERT(tuple->kind == Type_Tuple);
  649. i32 tuple_count = cast(i32)tuple->Tuple.variables.count;
  650. i32 cond_index = tuple_count-1;
  651. lbValue cond = lb_emit_tuple_ev(p, tuple_value, cond_index);
  652. lb_emit_if(p, cond, body, done);
  653. lb_start_block(p, body);
  654. if (val0_) *val0_ = lb_emit_tuple_ev(p, tuple_value, 0);
  655. if (val1_) *val1_ = lb_emit_tuple_ev(p, tuple_value, 1);
  656. if (loop_) *loop_ = loop;
  657. if (done_) *done_ = done;
  658. }
  659. gb_internal void lb_build_range_stmt_struct_soa(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  660. Ast *expr = unparen_expr(rs->expr);
  661. TypeAndValue tav = type_and_value_of_expr(expr);
  662. lbBlock *loop = nullptr;
  663. lbBlock *body = nullptr;
  664. lbBlock *done = nullptr;
  665. bool is_reverse = rs->reverse;
  666. lb_open_scope(p, scope);
  667. Ast *val0 = rs->vals.count > 0 ? lb_strip_and_prefix(rs->vals[0]) : nullptr;
  668. Ast *val1 = rs->vals.count > 1 ? lb_strip_and_prefix(rs->vals[1]) : nullptr;
  669. Type *val_types[2] = {};
  670. if (val0 != nullptr && !is_blank_ident(val0)) {
  671. val_types[0] = type_of_expr(val0);
  672. }
  673. if (val1 != nullptr && !is_blank_ident(val1)) {
  674. val_types[1] = type_of_expr(val1);
  675. }
  676. lbAddr array = lb_build_addr(p, expr);
  677. if (is_type_pointer(lb_addr_type(array))) {
  678. array = lb_addr(lb_addr_load(p, array));
  679. }
  680. lbValue count = lb_soa_struct_len(p, lb_addr_load(p, array));
  681. lbAddr index = lb_add_local_generated(p, t_int, false);
  682. if (!is_reverse) {
  683. /*
  684. for x, i in array {
  685. ...
  686. }
  687. i := -1
  688. for {
  689. i += 1
  690. if !(i < len(array)) {
  691. break
  692. }
  693. x := array[i] // but #soa-ified
  694. ...
  695. }
  696. */
  697. lb_addr_store(p, index, lb_const_int(p->module, t_int, cast(u64)-1));
  698. loop = lb_create_block(p, "for.soa.loop");
  699. lb_emit_jump(p, loop);
  700. lb_start_block(p, loop);
  701. lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  702. lb_addr_store(p, index, incr);
  703. body = lb_create_block(p, "for.soa.body");
  704. done = lb_create_block(p, "for.soa.done");
  705. lbValue cond = lb_emit_comp(p, Token_Lt, incr, count);
  706. lb_emit_if(p, cond, body, done);
  707. } else {
  708. // NOTE(bill): REVERSED LOGIC
  709. /*
  710. #reverse for x, i in array {
  711. ...
  712. }
  713. i := len(array)
  714. for {
  715. i -= 1
  716. if i < 0 {
  717. break
  718. }
  719. #no_bounds_check x := array[i] // but #soa-ified
  720. ...
  721. }
  722. */
  723. lb_addr_store(p, index, count);
  724. loop = lb_create_block(p, "for.soa.loop");
  725. lb_emit_jump(p, loop);
  726. lb_start_block(p, loop);
  727. lbValue incr = lb_emit_arith(p, Token_Sub, lb_addr_load(p, index), lb_const_int(p->module, t_int, 1), t_int);
  728. lb_addr_store(p, index, incr);
  729. body = lb_create_block(p, "for.soa.body");
  730. done = lb_create_block(p, "for.soa.done");
  731. lbValue cond = lb_emit_comp(p, Token_Lt, incr, lb_const_int(p->module, t_int, 0));
  732. lb_emit_if(p, cond, done, body);
  733. }
  734. lb_start_block(p, body);
  735. if (val_types[0]) {
  736. Entity *e = entity_of_node(val0);
  737. if (e != nullptr) {
  738. lbAddr soa_val = lb_addr_soa_variable(array.addr, lb_addr_load(p, index), nullptr);
  739. map_set(&p->module->soa_values, e, soa_val);
  740. }
  741. }
  742. if (val_types[1]) {
  743. lb_store_range_stmt_val(p, val1, lb_addr_load(p, index));
  744. }
  745. lb_push_target_list(p, rs->label, done, loop, nullptr);
  746. lb_build_stmt(p, rs->body);
  747. lb_close_scope(p, lbDeferExit_Default, nullptr);
  748. lb_pop_target_list(p);
  749. lb_emit_jump(p, loop);
  750. lb_start_block(p, done);
  751. }
  752. gb_internal void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs, Scope *scope) {
  753. Ast *expr = unparen_expr(rs->expr);
  754. if (is_ast_range(expr)) {
  755. lb_build_range_interval(p, &expr->BinaryExpr, rs, scope);
  756. return;
  757. }
  758. Type *expr_type = type_of_expr(expr);
  759. if (expr_type != nullptr) {
  760. Type *et = base_type(type_deref(expr_type));
  761. if (is_type_soa_struct(et)) {
  762. lb_build_range_stmt_struct_soa(p, rs, scope);
  763. return;
  764. }
  765. }
  766. lb_open_scope(p, scope);
  767. Ast *val0 = rs->vals.count > 0 ? lb_strip_and_prefix(rs->vals[0]) : nullptr;
  768. Ast *val1 = rs->vals.count > 1 ? lb_strip_and_prefix(rs->vals[1]) : nullptr;
  769. Type *val0_type = nullptr;
  770. Type *val1_type = nullptr;
  771. if (val0 != nullptr && !is_blank_ident(val0)) {
  772. val0_type = type_of_expr(val0);
  773. }
  774. if (val1 != nullptr && !is_blank_ident(val1)) {
  775. val1_type = type_of_expr(val1);
  776. }
  777. lbValue val = {};
  778. lbValue key = {};
  779. lbBlock *loop = nullptr;
  780. lbBlock *done = nullptr;
  781. bool is_map = false;
  782. TypeAndValue tav = type_and_value_of_expr(expr);
  783. if (tav.mode == Addressing_Type) {
  784. lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done);
  785. } else {
  786. Type *expr_type = type_of_expr(expr);
  787. Type *et = base_type(type_deref(expr_type));
  788. switch (et->kind) {
  789. case Type_Map: {
  790. is_map = true;
  791. lbValue map = lb_build_addr_ptr(p, expr);
  792. if (is_type_pointer(type_deref(map.type))) {
  793. map = lb_emit_load(p, map);
  794. }
  795. lb_build_range_map(p, map, val1_type, &val, &key, &loop, &done);
  796. break;
  797. }
  798. case Type_Array: {
  799. lbValue array = lb_build_addr_ptr(p, expr);
  800. if (is_type_pointer(type_deref(array.type))) {
  801. array = lb_emit_load(p, array);
  802. }
  803. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  804. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count));
  805. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done, rs->reverse);
  806. break;
  807. }
  808. case Type_EnumeratedArray: {
  809. lbValue array = lb_build_addr_ptr(p, expr);
  810. if (is_type_pointer(type_deref(array.type))) {
  811. array = lb_emit_load(p, array);
  812. }
  813. lbAddr count_ptr = lb_add_local_generated(p, t_int, false);
  814. lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count));
  815. lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done, rs->reverse);
  816. break;
  817. }
  818. case Type_DynamicArray: {
  819. lbValue count_ptr = {};
  820. lbValue array = lb_build_addr_ptr(p, expr);
  821. if (is_type_pointer(type_deref(array.type))) {
  822. array = lb_emit_load(p, array);
  823. }
  824. count_ptr = lb_emit_struct_ep(p, array, 1);
  825. lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done, rs->reverse);
  826. break;
  827. }
  828. case Type_Slice: {
  829. lbValue count_ptr = {};
  830. lbValue slice = lb_build_expr(p, expr);
  831. if (is_type_pointer(slice.type)) {
  832. count_ptr = lb_emit_struct_ep(p, slice, 1);
  833. slice = lb_emit_load(p, slice);
  834. } else {
  835. count_ptr = lb_add_local_generated(p, t_int, false).addr;
  836. lb_emit_store(p, count_ptr, lb_slice_len(p, slice));
  837. }
  838. lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done, rs->reverse);
  839. break;
  840. }
  841. case Type_Basic: {
  842. lbValue string = lb_build_expr(p, expr);
  843. if (is_type_pointer(string.type)) {
  844. string = lb_emit_load(p, string);
  845. }
  846. if (is_type_untyped(expr_type)) {
  847. lbAddr s = lb_add_local_generated(p, default_type(string.type), false);
  848. lb_addr_store(p, s, string);
  849. string = lb_addr_load(p, s);
  850. }
  851. Type *t = base_type(string.type);
  852. GB_ASSERT(!is_type_cstring(t));
  853. lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done, rs->reverse);
  854. break;
  855. }
  856. case Type_Tuple:
  857. lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done);
  858. break;
  859. default:
  860. GB_PANIC("Cannot range over %s", type_to_string(expr_type));
  861. break;
  862. }
  863. }
  864. if (is_map) {
  865. if (val0_type) lb_store_range_stmt_val(p, val0, key);
  866. if (val1_type) lb_store_range_stmt_val(p, val1, val);
  867. } else {
  868. if (val0_type) lb_store_range_stmt_val(p, val0, val);
  869. if (val1_type) lb_store_range_stmt_val(p, val1, key);
  870. }
  871. lb_push_target_list(p, rs->label, done, loop, nullptr);
  872. lb_build_stmt(p, rs->body);
  873. lb_close_scope(p, lbDeferExit_Default, nullptr);
  874. lb_pop_target_list(p);
  875. lb_emit_jump(p, loop);
  876. lb_start_block(p, done);
  877. }
  878. gb_internal void lb_build_unroll_range_stmt(lbProcedure *p, AstUnrollRangeStmt *rs, Scope *scope) {
  879. lbModule *m = p->module;
  880. lb_open_scope(p, scope); // Open scope here
  881. Ast *val0 = lb_strip_and_prefix(rs->val0);
  882. Ast *val1 = lb_strip_and_prefix(rs->val1);
  883. Type *val0_type = nullptr;
  884. Type *val1_type = nullptr;
  885. if (val0 != nullptr && !is_blank_ident(val0)) {
  886. val0_type = type_of_expr(val0);
  887. }
  888. if (val1 != nullptr && !is_blank_ident(val1)) {
  889. val1_type = type_of_expr(val1);
  890. }
  891. if (val0_type != nullptr) {
  892. Entity *e = entity_of_node(val0);
  893. lb_add_local(p, e->type, e, true);
  894. }
  895. if (val1_type != nullptr) {
  896. Entity *e = entity_of_node(val1);
  897. lb_add_local(p, e->type, e, true);
  898. }
  899. lbValue val = {};
  900. lbValue key = {};
  901. Ast *expr = unparen_expr(rs->expr);
  902. TypeAndValue tav = type_and_value_of_expr(expr);
  903. if (is_ast_range(expr)) {
  904. lbAddr val0_addr = {};
  905. lbAddr val1_addr = {};
  906. if (val0_type) val0_addr = lb_build_addr(p, val0);
  907. if (val1_type) val1_addr = lb_build_addr(p, val1);
  908. TokenKind op = expr->BinaryExpr.op.kind;
  909. Ast *start_expr = expr->BinaryExpr.left;
  910. Ast *end_expr = expr->BinaryExpr.right;
  911. GB_ASSERT(start_expr->tav.mode == Addressing_Constant);
  912. GB_ASSERT(end_expr->tav.mode == Addressing_Constant);
  913. ExactValue start = start_expr->tav.value;
  914. ExactValue end = end_expr->tav.value;
  915. if (op != Token_RangeHalf) { // .. [start, end] (or ..=)
  916. ExactValue index = exact_value_i64(0);
  917. for (ExactValue val = start;
  918. compare_exact_values(Token_LtEq, val, end);
  919. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  920. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  921. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  922. lb_build_stmt(p, rs->body);
  923. }
  924. } else { // ..< [start, end)
  925. ExactValue index = exact_value_i64(0);
  926. for (ExactValue val = start;
  927. compare_exact_values(Token_Lt, val, end);
  928. val = exact_value_increment_one(val), index = exact_value_increment_one(index)) {
  929. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val));
  930. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index));
  931. lb_build_stmt(p, rs->body);
  932. }
  933. }
  934. } else if (tav.mode == Addressing_Type) {
  935. GB_ASSERT(is_type_enum(type_deref(tav.type)));
  936. Type *et = type_deref(tav.type);
  937. Type *bet = base_type(et);
  938. lbAddr val0_addr = {};
  939. lbAddr val1_addr = {};
  940. if (val0_type) val0_addr = lb_build_addr(p, val0);
  941. if (val1_type) val1_addr = lb_build_addr(p, val1);
  942. for_array(i, bet->Enum.fields) {
  943. Entity *field = bet->Enum.fields[i];
  944. GB_ASSERT(field->kind == Entity_Constant);
  945. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value));
  946. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  947. lb_build_stmt(p, rs->body);
  948. }
  949. } else {
  950. lbAddr val0_addr = {};
  951. lbAddr val1_addr = {};
  952. if (val0_type) val0_addr = lb_build_addr(p, val0);
  953. if (val1_type) val1_addr = lb_build_addr(p, val1);
  954. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  955. Type *t = base_type(expr->tav.type);
  956. switch (t->kind) {
  957. case Type_Basic:
  958. GB_ASSERT(is_type_string(t));
  959. {
  960. ExactValue value = expr->tav.value;
  961. GB_ASSERT(value.kind == ExactValue_String);
  962. String str = value.value_string;
  963. Rune codepoint = 0;
  964. isize offset = 0;
  965. do {
  966. isize width = utf8_decode(str.text+offset, str.len-offset, &codepoint);
  967. if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint)));
  968. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset)));
  969. lb_build_stmt(p, rs->body);
  970. offset += width;
  971. } while (offset < str.len);
  972. }
  973. break;
  974. case Type_Array:
  975. if (t->Array.count > 0) {
  976. lbValue val = lb_build_expr(p, expr);
  977. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  978. for (i64 i = 0; i < t->Array.count; i++) {
  979. if (val0_type) {
  980. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  981. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  982. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  983. }
  984. if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i)));
  985. lb_build_stmt(p, rs->body);
  986. }
  987. }
  988. break;
  989. case Type_EnumeratedArray:
  990. if (t->EnumeratedArray.count > 0) {
  991. lbValue val = lb_build_expr(p, expr);
  992. lbValue val_addr = lb_address_from_load_or_generate_local(p, val);
  993. for (i64 i = 0; i < t->EnumeratedArray.count; i++) {
  994. if (val0_type) {
  995. // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32
  996. lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i);
  997. lb_addr_store(p, val0_addr, lb_emit_load(p, elem));
  998. }
  999. if (val1_type) {
  1000. ExactValue idx = exact_value_add(exact_value_i64(i), *t->EnumeratedArray.min_value);
  1001. lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx));
  1002. }
  1003. lb_build_stmt(p, rs->body);
  1004. }
  1005. }
  1006. break;
  1007. default:
  1008. GB_PANIC("Invalid '#unroll for' type");
  1009. break;
  1010. }
  1011. }
  1012. lb_close_scope(p, lbDeferExit_Default, nullptr);
  1013. }
  1014. gb_internal bool lb_switch_stmt_can_be_trivial_jump_table(AstSwitchStmt *ss, bool *default_found_) {
  1015. if (ss->tag == nullptr) {
  1016. return false;
  1017. }
  1018. bool is_typeid = false;
  1019. TypeAndValue tv = type_and_value_of_expr(ss->tag);
  1020. if (is_type_integer(core_type(tv.type))) {
  1021. // okay
  1022. } else if (is_type_typeid(tv.type)) {
  1023. // okay
  1024. is_typeid = true;
  1025. } else {
  1026. return false;
  1027. }
  1028. ast_node(body, BlockStmt, ss->body);
  1029. for (Ast *clause : body->stmts) {
  1030. ast_node(cc, CaseClause, clause);
  1031. if (cc->list.count == 0) {
  1032. if (default_found_) *default_found_ = true;
  1033. continue;
  1034. }
  1035. for (Ast *expr : cc->list) {
  1036. expr = unparen_expr(expr);
  1037. if (is_ast_range(expr)) {
  1038. return false;
  1039. }
  1040. if (expr->tav.mode == Addressing_Type) {
  1041. GB_ASSERT(is_typeid);
  1042. continue;
  1043. }
  1044. tv = type_and_value_of_expr(expr);
  1045. if (tv.mode != Addressing_Constant) {
  1046. return false;
  1047. }
  1048. if (!is_type_integer(core_type(tv.type))) {
  1049. return false;
  1050. }
  1051. }
  1052. }
  1053. return true;
  1054. }
  1055. gb_internal void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss, Scope *scope) {
  1056. lb_open_scope(p, scope);
  1057. if (ss->init != nullptr) {
  1058. lb_build_stmt(p, ss->init);
  1059. }
  1060. lbValue tag = lb_const_bool(p->module, t_llvm_bool, true);
  1061. if (ss->tag != nullptr) {
  1062. tag = lb_build_expr(p, ss->tag);
  1063. }
  1064. lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later
  1065. ast_node(body, BlockStmt, ss->body);
  1066. isize case_count = body->stmts.count;
  1067. Slice<Ast *> default_stmts = {};
  1068. lbBlock *default_fall = nullptr;
  1069. lbBlock *default_block = nullptr;
  1070. lbBlock *fall = nullptr;
  1071. bool default_found = false;
  1072. bool is_trivial = lb_switch_stmt_can_be_trivial_jump_table(ss, &default_found);
  1073. auto body_blocks = slice_make<lbBlock *>(permanent_allocator(), body->stmts.count);
  1074. for_array(i, body->stmts) {
  1075. Ast *clause = body->stmts[i];
  1076. ast_node(cc, CaseClause, clause);
  1077. body_blocks[i] = lb_create_block(p, cc->list.count == 0 ? "switch.default.body" : "switch.case.body");
  1078. if (cc->list.count == 0) {
  1079. default_block = body_blocks[i];
  1080. }
  1081. }
  1082. LLVMValueRef switch_instr = nullptr;
  1083. if (is_trivial) {
  1084. isize num_cases = 0;
  1085. for (Ast *clause : body->stmts) {
  1086. ast_node(cc, CaseClause, clause);
  1087. num_cases += cc->list.count;
  1088. }
  1089. LLVMBasicBlockRef end_block = done->block;
  1090. if (default_block) {
  1091. end_block = default_block->block;
  1092. }
  1093. switch_instr = LLVMBuildSwitch(p->builder, tag.value, end_block, cast(unsigned)num_cases);
  1094. }
  1095. for_array(i, body->stmts) {
  1096. Ast *clause = body->stmts[i];
  1097. ast_node(cc, CaseClause, clause);
  1098. lbBlock *body = body_blocks[i];
  1099. fall = done;
  1100. if (i+1 < case_count) {
  1101. fall = body_blocks[i+1];
  1102. }
  1103. if (cc->list.count == 0) {
  1104. // default case
  1105. default_stmts = cc->stmts;
  1106. default_fall = fall;
  1107. if (switch_instr == nullptr) {
  1108. default_block = body;
  1109. } else {
  1110. GB_ASSERT(default_block != nullptr);
  1111. }
  1112. continue;
  1113. }
  1114. lbBlock *next_cond = nullptr;
  1115. for (Ast *expr : cc->list) {
  1116. expr = unparen_expr(expr);
  1117. if (switch_instr != nullptr) {
  1118. lbValue on_val = {};
  1119. if (expr->tav.mode == Addressing_Type) {
  1120. GB_ASSERT(is_type_typeid(tag.type));
  1121. lbValue e = lb_typeid(p->module, expr->tav.type);
  1122. on_val = lb_emit_conv(p, e, tag.type);
  1123. } else {
  1124. GB_ASSERT(expr->tav.mode == Addressing_Constant);
  1125. GB_ASSERT(!is_ast_range(expr));
  1126. on_val = lb_build_expr(p, expr);
  1127. on_val = lb_emit_conv(p, on_val, tag.type);
  1128. }
  1129. GB_ASSERT(LLVMIsConstant(on_val.value));
  1130. LLVMAddCase(switch_instr, on_val.value, body->block);
  1131. continue;
  1132. }
  1133. next_cond = lb_create_block(p, "switch.case.next");
  1134. lbValue cond = {};
  1135. if (is_ast_range(expr)) {
  1136. ast_node(ie, BinaryExpr, expr);
  1137. TokenKind op = Token_Invalid;
  1138. switch (ie->op.kind) {
  1139. case Token_Ellipsis: op = Token_LtEq; break;
  1140. case Token_RangeFull: op = Token_LtEq; break;
  1141. case Token_RangeHalf: op = Token_Lt; break;
  1142. default: GB_PANIC("Invalid interval operator"); break;
  1143. }
  1144. lbValue lhs = lb_build_expr(p, ie->left);
  1145. lbValue rhs = lb_build_expr(p, ie->right);
  1146. lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag);
  1147. lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs);
  1148. cond = lb_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool);
  1149. } else {
  1150. if (expr->tav.mode == Addressing_Type) {
  1151. GB_ASSERT(is_type_typeid(tag.type));
  1152. lbValue e = lb_typeid(p->module, expr->tav.type);
  1153. e = lb_emit_conv(p, e, tag.type);
  1154. cond = lb_emit_comp(p, Token_CmpEq, tag, e);
  1155. } else {
  1156. cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr));
  1157. }
  1158. }
  1159. lb_emit_if(p, cond, body, next_cond);
  1160. lb_start_block(p, next_cond);
  1161. }
  1162. lb_start_block(p, body);
  1163. lb_push_target_list(p, ss->label, done, nullptr, fall);
  1164. lb_open_scope(p, body->scope);
  1165. lb_build_stmt_list(p, cc->stmts);
  1166. lb_close_scope(p, lbDeferExit_Default, body);
  1167. lb_pop_target_list(p);
  1168. lb_emit_jump(p, done);
  1169. if (switch_instr == nullptr) {
  1170. lb_start_block(p, next_cond);
  1171. }
  1172. }
  1173. if (default_block != nullptr) {
  1174. if (switch_instr == nullptr) {
  1175. lb_emit_jump(p, default_block);
  1176. }
  1177. lb_start_block(p, default_block);
  1178. lb_push_target_list(p, ss->label, done, nullptr, default_fall);
  1179. lb_open_scope(p, default_block->scope);
  1180. lb_build_stmt_list(p, default_stmts);
  1181. lb_close_scope(p, lbDeferExit_Default, default_block);
  1182. lb_pop_target_list(p);
  1183. }
  1184. lb_emit_jump(p, done);
  1185. lb_start_block(p, done);
  1186. lb_close_scope(p, lbDeferExit_Default, done);
  1187. }
  1188. gb_internal void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) {
  1189. Entity *e = implicit_entity_of_node(clause);
  1190. GB_ASSERT(e != nullptr);
  1191. if (e->flags & EntityFlag_Value) {
  1192. // by value
  1193. GB_ASSERT(are_types_identical(e->type, value.type));
  1194. lbAddr x = lb_add_local(p, e->type, e, false);
  1195. lb_addr_store(p, x, value);
  1196. } else {
  1197. // by reference
  1198. GB_ASSERT(are_types_identical(e->type, type_deref(value.type)));
  1199. lb_add_entity(p->module, e, value);
  1200. }
  1201. }
  1202. gb_internal lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) {
  1203. Entity *e = entity_of_node(stmt_val);
  1204. if (e == nullptr) {
  1205. return {};
  1206. }
  1207. if ((e->flags & EntityFlag_Value) == 0) {
  1208. if (LLVMIsALoadInst(value.value)) {
  1209. lbValue ptr = lb_address_from_load_or_generate_local(p, value);
  1210. lb_add_entity(p->module, e, ptr);
  1211. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  1212. return lb_addr(ptr);
  1213. }
  1214. }
  1215. // by value
  1216. lbAddr addr = lb_add_local(p, e->type, e, false);
  1217. lb_addr_store(p, addr, value);
  1218. return addr;
  1219. }
  1220. gb_internal void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) {
  1221. ast_node(cc, CaseClause, clause);
  1222. lb_push_target_list(p, label, done, nullptr, nullptr);
  1223. lb_build_stmt_list(p, cc->stmts);
  1224. lb_close_scope(p, lbDeferExit_Default, body);
  1225. lb_pop_target_list(p);
  1226. lb_emit_jump(p, done);
  1227. }
  1228. gb_internal void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) {
  1229. lbModule *m = p->module;
  1230. lb_open_scope(p, ss->scope);
  1231. ast_node(as, AssignStmt, ss->tag);
  1232. GB_ASSERT(as->lhs.count == 1);
  1233. GB_ASSERT(as->rhs.count == 1);
  1234. lbValue parent = lb_build_expr(p, as->rhs[0]);
  1235. bool is_parent_ptr = is_type_pointer(parent.type);
  1236. Type *parent_base_type = type_deref(parent.type);
  1237. TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type);
  1238. GB_ASSERT(switch_kind != TypeSwitch_Invalid);
  1239. lbValue parent_value = parent;
  1240. lbValue parent_ptr = parent;
  1241. if (!is_parent_ptr) {
  1242. parent_ptr = lb_address_from_load_or_generate_local(p, parent);
  1243. }
  1244. lbValue tag = {};
  1245. lbValue union_data = {};
  1246. if (switch_kind == TypeSwitch_Union) {
  1247. union_data = lb_emit_conv(p, parent_ptr, t_rawptr);
  1248. Type *union_type = type_deref(parent_ptr.type);
  1249. if (is_type_union_maybe_pointer(union_type)) {
  1250. tag = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, union_data), t_int);
  1251. } else if (union_tag_size(union_type) == 0) {
  1252. tag = {}; // there is no tag for a zero sized union
  1253. } else {
  1254. lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr);
  1255. tag = lb_emit_load(p, tag_ptr);
  1256. }
  1257. } else if (switch_kind == TypeSwitch_Any) {
  1258. tag = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1));
  1259. } else {
  1260. GB_PANIC("Unknown switch kind");
  1261. }
  1262. ast_node(body, BlockStmt, ss->body);
  1263. lbBlock *done = lb_create_block(p, "typeswitch.done");
  1264. lbBlock *else_block = done;
  1265. lbBlock *default_block = nullptr;
  1266. isize num_cases = 0;
  1267. for (Ast *clause : body->stmts) {
  1268. ast_node(cc, CaseClause, clause);
  1269. num_cases += cc->list.count;
  1270. if (cc->list.count == 0) {
  1271. GB_ASSERT(default_block == nullptr);
  1272. default_block = lb_create_block(p, "typeswitch.default.body");
  1273. else_block = default_block;
  1274. }
  1275. }
  1276. LLVMValueRef switch_instr = nullptr;
  1277. if (type_size_of(parent_base_type) == 0) {
  1278. GB_ASSERT(tag.value == nullptr);
  1279. switch_instr = LLVMBuildSwitch(p->builder, lb_const_bool(p->module, t_llvm_bool, false).value, else_block->block, cast(unsigned)num_cases);
  1280. } else {
  1281. GB_ASSERT(tag.value != nullptr);
  1282. switch_instr = LLVMBuildSwitch(p->builder, tag.value, else_block->block, cast(unsigned)num_cases);
  1283. }
  1284. bool all_by_reference = false;
  1285. for (Ast *clause : body->stmts) {
  1286. ast_node(cc, CaseClause, clause);
  1287. if (cc->list.count != 1) {
  1288. continue;
  1289. }
  1290. Entity *case_entity = implicit_entity_of_node(clause);
  1291. all_by_reference |= (case_entity->flags & EntityFlag_Value) == 0;
  1292. break;
  1293. }
  1294. // NOTE(bill, 2023-02-17): In the case of a pass by value, the value does need to be copied
  1295. // to prevent errors such as these:
  1296. //
  1297. // switch v in some_union {
  1298. // case i32:
  1299. // fmt.println(v) // 'i32'
  1300. // some_union = f32(123)
  1301. // fmt.println(v) // if `v` is an implicit reference, then the data is now completely corrupted
  1302. // case f32:
  1303. // fmt.println(v)
  1304. // }
  1305. //
  1306. lbAddr backing_data = {};
  1307. if (!all_by_reference) {
  1308. bool variants_found = false;
  1309. i64 max_size = 0;
  1310. i64 max_align = 1;
  1311. for (Ast *clause : body->stmts) {
  1312. ast_node(cc, CaseClause, clause);
  1313. if (cc->list.count != 1) {
  1314. continue;
  1315. }
  1316. Entity *case_entity = implicit_entity_of_node(clause);
  1317. if (!is_type_untyped_nil(case_entity->type)) {
  1318. max_size = gb_max(max_size, type_size_of(case_entity->type));
  1319. max_align = gb_max(max_align, type_align_of(case_entity->type));
  1320. variants_found = true;
  1321. }
  1322. }
  1323. if (variants_found) {
  1324. Type *t = alloc_type_array(t_u8, max_size);
  1325. backing_data = lb_add_local(p, t, nullptr, false, true);
  1326. GB_ASSERT(lb_try_update_alignment(backing_data.addr, cast(unsigned)max_align));
  1327. }
  1328. }
  1329. lbValue backing_ptr = backing_data.addr;
  1330. for (Ast *clause : body->stmts) {
  1331. ast_node(cc, CaseClause, clause);
  1332. lb_open_scope(p, cc->scope);
  1333. if (cc->list.count == 0) {
  1334. lb_start_block(p, default_block);
  1335. lb_store_type_case_implicit(p, clause, parent_value);
  1336. lb_type_case_body(p, ss->label, clause, p->curr_block, done);
  1337. continue;
  1338. }
  1339. lbBlock *body = lb_create_block(p, "typeswitch.body");
  1340. if (p->debug_info != nullptr) {
  1341. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, clause));
  1342. }
  1343. bool saw_nil = false;
  1344. for (Ast *type_expr : cc->list) {
  1345. Type *case_type = type_of_expr(type_expr);
  1346. lbValue on_val = {};
  1347. if (switch_kind == TypeSwitch_Union) {
  1348. Type *ut = base_type(type_deref(parent.type));
  1349. on_val = lb_const_union_tag(m, ut, case_type);
  1350. } else if (switch_kind == TypeSwitch_Any) {
  1351. if (is_type_untyped_nil(case_type)) {
  1352. saw_nil = true;
  1353. on_val = lb_const_nil(m, t_typeid);
  1354. } else {
  1355. on_val = lb_typeid(m, case_type);
  1356. }
  1357. }
  1358. GB_ASSERT(on_val.value != nullptr);
  1359. LLVMAddCase(switch_instr, on_val.value, body->block);
  1360. }
  1361. Entity *case_entity = implicit_entity_of_node(clause);
  1362. lb_start_block(p, body);
  1363. bool by_reference = (case_entity->flags & EntityFlag_Value) == 0;
  1364. if (cc->list.count == 1 && !saw_nil) {
  1365. lbValue data = {};
  1366. if (switch_kind == TypeSwitch_Union) {
  1367. data = union_data;
  1368. } else if (switch_kind == TypeSwitch_Any) {
  1369. data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0));
  1370. }
  1371. Type *ct = case_entity->type;
  1372. Type *ct_ptr = alloc_type_pointer(ct);
  1373. lbValue ptr = {};
  1374. if (backing_data.addr.value) { // by value
  1375. GB_ASSERT(!by_reference);
  1376. // make a copy of the case value
  1377. lb_mem_copy_non_overlapping(p,
  1378. backing_ptr, // dst
  1379. data, // src
  1380. lb_const_int(p->module, t_int, type_size_of(case_entity->type)));
  1381. ptr = lb_emit_conv(p, backing_ptr, ct_ptr);
  1382. } else { // by reference
  1383. GB_ASSERT(by_reference);
  1384. ptr = lb_emit_conv(p, data, ct_ptr);
  1385. }
  1386. GB_ASSERT(are_types_identical(case_entity->type, type_deref(ptr.type)));
  1387. lb_add_entity(p->module, case_entity, ptr);
  1388. lb_add_debug_local_variable(p, ptr.value, case_entity->type, case_entity->token);
  1389. } else {
  1390. // TODO(bill): is the correct expected behaviour?
  1391. lb_store_type_case_implicit(p, clause, parent_value);
  1392. }
  1393. lb_type_case_body(p, ss->label, clause, body, done);
  1394. }
  1395. lb_emit_jump(p, done);
  1396. lb_start_block(p, done);
  1397. lb_close_scope(p, lbDeferExit_Default, done);
  1398. }
  1399. gb_internal void lb_build_static_variables(lbProcedure *p, AstValueDecl *vd) {
  1400. for_array(i, vd->names) {
  1401. lbValue value = {};
  1402. if (vd->values.count > 0) {
  1403. GB_ASSERT(vd->names.count == vd->values.count);
  1404. Ast *ast_value = vd->values[i];
  1405. GB_ASSERT(ast_value->tav.mode == Addressing_Constant ||
  1406. ast_value->tav.mode == Addressing_Invalid);
  1407. bool allow_local = false;
  1408. value = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value, allow_local);
  1409. }
  1410. Ast *ident = vd->names[i];
  1411. GB_ASSERT(!is_blank_ident(ident));
  1412. Entity *e = entity_of_node(ident);
  1413. GB_ASSERT(e->flags & EntityFlag_Static);
  1414. String name = e->token.string;
  1415. String mangled_name = {};
  1416. {
  1417. gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len);
  1418. str = gb_string_appendc(str, "-");
  1419. str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id);
  1420. mangled_name.text = cast(u8 *)str;
  1421. mangled_name.len = gb_string_length(str);
  1422. }
  1423. char *c_name = alloc_cstring(permanent_allocator(), mangled_name);
  1424. LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name);
  1425. LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type)));
  1426. if (value.value != nullptr) {
  1427. LLVMSetInitializer(global, value.value);
  1428. } else {
  1429. }
  1430. if (e->Variable.thread_local_model != "") {
  1431. LLVMSetThreadLocal(global, true);
  1432. String m = e->Variable.thread_local_model;
  1433. LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel;
  1434. if (m == "default") {
  1435. mode = LLVMGeneralDynamicTLSModel;
  1436. } else if (m == "localdynamic") {
  1437. mode = LLVMLocalDynamicTLSModel;
  1438. } else if (m == "initialexec") {
  1439. mode = LLVMInitialExecTLSModel;
  1440. } else if (m == "localexec") {
  1441. mode = LLVMLocalExecTLSModel;
  1442. } else {
  1443. GB_PANIC("Unhandled thread local mode %.*s", LIT(m));
  1444. }
  1445. LLVMSetThreadLocalMode(global, mode);
  1446. } else {
  1447. LLVMSetLinkage(global, LLVMInternalLinkage);
  1448. }
  1449. lbValue global_val = {global, alloc_type_pointer(e->type)};
  1450. lb_add_entity(p->module, e, global_val);
  1451. lb_add_member(p->module, mangled_name, global_val);
  1452. }
  1453. }
  1454. gb_internal isize lb_append_tuple_values(lbProcedure *p, Array<lbValue> *dst_values, lbValue src_value) {
  1455. isize init_count = dst_values->count;
  1456. Type *t = src_value.type;
  1457. if (t->kind == Type_Tuple) {
  1458. lbTupleFix *tf = map_get(&p->tuple_fix_map, src_value.value);
  1459. if (tf) {
  1460. for (lbValue const &value : tf->values) {
  1461. array_add(dst_values, value);
  1462. }
  1463. } else {
  1464. for_array(i, t->Tuple.variables) {
  1465. lbValue v = lb_emit_tuple_ev(p, src_value, cast(i32)i);
  1466. array_add(dst_values, v);
  1467. }
  1468. }
  1469. } else {
  1470. array_add(dst_values, src_value);
  1471. }
  1472. return dst_values->count - init_count;
  1473. }
  1474. gb_internal void lb_build_assignment(lbProcedure *p, Array<lbAddr> &lvals, Slice<Ast *> const &values) {
  1475. if (values.count == 0) {
  1476. return;
  1477. }
  1478. auto inits = array_make<lbValue>(permanent_allocator(), 0, lvals.count);
  1479. for (Ast *rhs : values) {
  1480. lbValue init = lb_build_expr(p, rhs);
  1481. lb_append_tuple_values(p, &inits, init);
  1482. }
  1483. bool prev_in_assignment = p->in_multi_assignment;
  1484. isize lval_count = 0;
  1485. for (lbAddr const &lval : lvals) {
  1486. if (lval.addr.value != nullptr) {
  1487. // check if it is not a blank identifier
  1488. lval_count += 1;
  1489. }
  1490. }
  1491. p->in_multi_assignment = lval_count > 1;
  1492. GB_ASSERT(lvals.count == inits.count);
  1493. for_array(i, inits) {
  1494. lbAddr lval = lvals[i];
  1495. lbValue init = inits[i];
  1496. lb_addr_store(p, lval, init);
  1497. }
  1498. p->in_multi_assignment = prev_in_assignment;
  1499. }
  1500. gb_internal void lb_build_return_stmt_internal(lbProcedure *p, lbValue res) {
  1501. lbFunctionType *ft = lb_get_function_type(p->module, p->type);
  1502. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  1503. bool split_returns = ft->multiple_return_original_type != nullptr;
  1504. if (split_returns) {
  1505. GB_ASSERT(res.value == nullptr || !is_type_tuple(res.type));
  1506. }
  1507. if (return_by_pointer) {
  1508. if (res.value != nullptr) {
  1509. LLVMValueRef res_val = res.value;
  1510. i64 sz = type_size_of(res.type);
  1511. if (LLVMIsALoadInst(res_val) && sz > build_context.int_size) {
  1512. lbValue ptr = lb_address_from_load_or_generate_local(p, res);
  1513. lb_mem_copy_non_overlapping(p, p->return_ptr.addr, ptr, lb_const_int(p->module, t_int, sz));
  1514. } else {
  1515. LLVMBuildStore(p->builder, res_val, p->return_ptr.addr.value);
  1516. }
  1517. } else {
  1518. LLVMBuildStore(p->builder, LLVMConstNull(p->abi_function_type->ret.type), p->return_ptr.addr.value);
  1519. }
  1520. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1521. LLVMBuildRetVoid(p->builder);
  1522. } else {
  1523. LLVMValueRef ret_val = res.value;
  1524. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.type);
  1525. if (p->abi_function_type->ret.cast_type != nullptr) {
  1526. ret_val = OdinLLVMBuildTransmute(p, ret_val, p->abi_function_type->ret.cast_type);
  1527. }
  1528. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1529. LLVMBuildRet(p->builder, ret_val);
  1530. }
  1531. }
  1532. gb_internal void lb_build_return_stmt(lbProcedure *p, Slice<Ast *> const &return_results) {
  1533. lb_ensure_abi_function_type(p->module, p);
  1534. lbValue res = {};
  1535. TypeTuple *tuple = &p->type->Proc.results->Tuple;
  1536. isize return_count = p->type->Proc.result_count;
  1537. isize res_count = return_results.count;
  1538. lbFunctionType *ft = lb_get_function_type(p->module, p->type);
  1539. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  1540. if (return_count == 0) {
  1541. // No return values
  1542. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1543. LLVMBuildRetVoid(p->builder);
  1544. return;
  1545. } else if (return_count == 1) {
  1546. Entity *e = tuple->variables[0];
  1547. if (res_count == 0) {
  1548. rw_mutex_shared_lock(&p->module->values_mutex);
  1549. lbValue found = map_must_get(&p->module->values, e);
  1550. rw_mutex_shared_unlock(&p->module->values_mutex);
  1551. res = lb_emit_load(p, found);
  1552. } else {
  1553. res = lb_build_expr(p, return_results[0]);
  1554. res = lb_emit_conv(p, res, e->type);
  1555. }
  1556. if (p->type->Proc.has_named_results) {
  1557. // NOTE(bill): store the named values before returning
  1558. if (e->token.string != "") {
  1559. rw_mutex_shared_lock(&p->module->values_mutex);
  1560. lbValue found = map_must_get(&p->module->values, e);
  1561. rw_mutex_shared_unlock(&p->module->values_mutex);
  1562. lb_emit_store(p, found, lb_emit_conv(p, res, e->type));
  1563. }
  1564. }
  1565. } else {
  1566. auto results = array_make<lbValue>(permanent_allocator(), 0, return_count);
  1567. if (res_count != 0) {
  1568. for (isize res_index = 0; res_index < res_count; res_index++) {
  1569. lbValue res = lb_build_expr(p, return_results[res_index]);
  1570. lb_append_tuple_values(p, &results, res);
  1571. }
  1572. } else {
  1573. for (isize res_index = 0; res_index < return_count; res_index++) {
  1574. Entity *e = tuple->variables[res_index];
  1575. rw_mutex_shared_lock(&p->module->values_mutex);
  1576. lbValue found = map_must_get(&p->module->values, e);
  1577. rw_mutex_shared_unlock(&p->module->values_mutex);
  1578. lbValue res = lb_emit_load(p, found);
  1579. array_add(&results, res);
  1580. }
  1581. }
  1582. GB_ASSERT(results.count == return_count);
  1583. if (p->type->Proc.has_named_results) {
  1584. auto named_results = slice_make<lbValue>(temporary_allocator(), results.count);
  1585. auto values = slice_make<lbValue>(temporary_allocator(), results.count);
  1586. // NOTE(bill): store the named values before returning
  1587. for_array(i, p->type->Proc.results->Tuple.variables) {
  1588. Entity *e = p->type->Proc.results->Tuple.variables[i];
  1589. if (e->kind != Entity_Variable) {
  1590. continue;
  1591. }
  1592. if (e->token.string == "") {
  1593. continue;
  1594. }
  1595. rw_mutex_shared_lock(&p->module->values_mutex);
  1596. named_results[i] = map_must_get(&p->module->values, e);
  1597. rw_mutex_shared_unlock(&p->module->values_mutex);
  1598. values[i] = lb_emit_conv(p, results[i], e->type);
  1599. }
  1600. for_array(i, named_results) {
  1601. lb_emit_store(p, named_results[i], values[i]);
  1602. }
  1603. }
  1604. bool split_returns = ft->multiple_return_original_type != nullptr;
  1605. if (split_returns) {
  1606. auto result_values = slice_make<lbValue>(temporary_allocator(), results.count);
  1607. auto result_eps = slice_make<lbValue>(temporary_allocator(), results.count-1);
  1608. for_array(i, results) {
  1609. result_values[i] = lb_emit_conv(p, results[i], tuple->variables[i]->type);
  1610. }
  1611. isize param_offset = return_by_pointer ? 1 : 0;
  1612. param_offset += ft->original_arg_count;
  1613. for_array(i, result_eps) {
  1614. lbValue result_ep = {};
  1615. result_ep.value = LLVMGetParam(p->value, cast(unsigned)(param_offset+i));
  1616. result_ep.type = alloc_type_pointer(tuple->variables[i]->type);
  1617. result_eps[i] = result_ep;
  1618. }
  1619. for_array(i, result_eps) {
  1620. lb_emit_store(p, result_eps[i], result_values[i]);
  1621. }
  1622. if (return_by_pointer) {
  1623. GB_ASSERT(result_values.count-1 == result_eps.count);
  1624. lb_addr_store(p, p->return_ptr, result_values[result_values.count-1]);
  1625. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1626. LLVMBuildRetVoid(p->builder);
  1627. return;
  1628. } else {
  1629. return lb_build_return_stmt_internal(p, result_values[result_values.count-1]);
  1630. }
  1631. } else {
  1632. Type *ret_type = p->type->Proc.results;
  1633. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1634. if (return_by_pointer) {
  1635. res = p->return_ptr.addr;
  1636. } else {
  1637. res = lb_add_local_generated(p, ret_type, false).addr;
  1638. }
  1639. auto result_values = slice_make<lbValue>(temporary_allocator(), results.count);
  1640. auto result_eps = slice_make<lbValue>(temporary_allocator(), results.count);
  1641. for_array(i, results) {
  1642. result_values[i] = lb_emit_conv(p, results[i], tuple->variables[i]->type);
  1643. }
  1644. for_array(i, results) {
  1645. result_eps[i] = lb_emit_struct_ep(p, res, cast(i32)i);
  1646. }
  1647. for_array(i, result_eps) {
  1648. lb_emit_store(p, result_eps[i], result_values[i]);
  1649. }
  1650. if (return_by_pointer) {
  1651. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  1652. LLVMBuildRetVoid(p->builder);
  1653. return;
  1654. }
  1655. res = lb_emit_load(p, res);
  1656. }
  1657. }
  1658. lb_build_return_stmt_internal(p, res);
  1659. }
  1660. gb_internal void lb_build_if_stmt(lbProcedure *p, Ast *node) {
  1661. ast_node(is, IfStmt, node);
  1662. lb_open_scope(p, is->scope); // Scope #1
  1663. defer (lb_close_scope(p, lbDeferExit_Default, nullptr));
  1664. if (is->init != nullptr) {
  1665. // TODO(bill): Should this have a separate block to begin with?
  1666. #if 1
  1667. lbBlock *init = lb_create_block(p, "if.init");
  1668. lb_emit_jump(p, init);
  1669. lb_start_block(p, init);
  1670. #endif
  1671. lb_build_stmt(p, is->init);
  1672. }
  1673. lbBlock *then = lb_create_block(p, "if.then");
  1674. lbBlock *done = lb_create_block(p, "if.done");
  1675. lbBlock *else_ = done;
  1676. if (is->else_stmt != nullptr) {
  1677. else_ = lb_create_block(p, "if.else");
  1678. }
  1679. lbValue cond = lb_build_cond(p, is->cond, then, else_);
  1680. // Note `cond.value` only set for non-and/or conditions and const negs so that the `LLVMIsConstant()`
  1681. // and `LLVMConstIntGetZExtValue()` calls below will be valid and `LLVMInstructionEraseFromParent()`
  1682. // will target the correct (& only) branch statement
  1683. if (is->label != nullptr) {
  1684. lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr);
  1685. tl->is_block = true;
  1686. }
  1687. if (cond.value && LLVMIsConstant(cond.value)) {
  1688. // NOTE(bill): Do a compile time short circuit for when the condition is constantly known.
  1689. // This done manually rather than relying on the SSA passes because sometimes the SSA passes
  1690. // miss some even if they are constantly known, especially with few optimization passes.
  1691. bool const_cond = LLVMConstIntGetZExtValue(cond.value) != 0;
  1692. LLVMValueRef if_instr = LLVMGetLastInstruction(p->curr_block->block);
  1693. GB_ASSERT(LLVMGetInstructionOpcode(if_instr) == LLVMBr);
  1694. GB_ASSERT(LLVMIsConditional(if_instr));
  1695. LLVMInstructionEraseFromParent(if_instr);
  1696. if (const_cond) {
  1697. lb_emit_jump(p, then);
  1698. lb_start_block(p, then);
  1699. lb_build_stmt(p, is->body);
  1700. lb_emit_jump(p, done);
  1701. } else {
  1702. if (is->else_stmt != nullptr) {
  1703. lb_emit_jump(p, else_);
  1704. lb_start_block(p, else_);
  1705. lb_open_scope(p, scope_of_node(is->else_stmt));
  1706. lb_build_stmt(p, is->else_stmt);
  1707. lb_close_scope(p, lbDeferExit_Default, nullptr);
  1708. }
  1709. lb_emit_jump(p, done);
  1710. }
  1711. } else {
  1712. lb_start_block(p, then);
  1713. lb_build_stmt(p, is->body);
  1714. lb_emit_jump(p, done);
  1715. if (is->else_stmt != nullptr) {
  1716. lb_start_block(p, else_);
  1717. lb_open_scope(p, scope_of_node(is->else_stmt));
  1718. lb_build_stmt(p, is->else_stmt);
  1719. lb_close_scope(p, lbDeferExit_Default, nullptr);
  1720. lb_emit_jump(p, done);
  1721. }
  1722. }
  1723. if (is->label != nullptr) {
  1724. lb_pop_target_list(p);
  1725. }
  1726. lb_start_block(p, done);
  1727. }
  1728. gb_internal void lb_build_for_stmt(lbProcedure *p, Ast *node) {
  1729. ast_node(fs, ForStmt, node);
  1730. lb_open_scope(p, fs->scope); // Open Scope here
  1731. if (p->debug_info != nullptr) {
  1732. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  1733. }
  1734. if (fs->init != nullptr) {
  1735. #if 1
  1736. lbBlock *init = lb_create_block(p, "for.init");
  1737. lb_emit_jump(p, init);
  1738. lb_start_block(p, init);
  1739. #endif
  1740. lb_build_stmt(p, fs->init);
  1741. }
  1742. lbBlock *body = lb_create_block(p, "for.body");
  1743. lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later
  1744. lbBlock *loop = body;
  1745. if (fs->cond != nullptr) {
  1746. loop = lb_create_block(p, "for.loop");
  1747. }
  1748. lbBlock *post = loop;
  1749. if (fs->post != nullptr) {
  1750. post = lb_create_block(p, "for.post");
  1751. }
  1752. lb_emit_jump(p, loop);
  1753. lb_start_block(p, loop);
  1754. if (loop != body) {
  1755. // right now the condition (all expressions) will not set it's debug location, so we will do it here
  1756. if (p->debug_info != nullptr) {
  1757. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, fs->cond));
  1758. }
  1759. lb_build_cond(p, fs->cond, body, done);
  1760. lb_start_block(p, body);
  1761. }
  1762. lb_push_target_list(p, fs->label, done, post, nullptr);
  1763. lb_build_stmt(p, fs->body);
  1764. lb_pop_target_list(p);
  1765. if (p->debug_info != nullptr) {
  1766. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_end_location_from_ast(p, fs->body));
  1767. }
  1768. lb_emit_jump(p, post);
  1769. if (fs->post != nullptr) {
  1770. lb_start_block(p, post);
  1771. lb_build_stmt(p, fs->post);
  1772. lb_emit_jump(p, loop);
  1773. }
  1774. lb_start_block(p, done);
  1775. lb_close_scope(p, lbDeferExit_Default, nullptr);
  1776. }
  1777. gb_internal void lb_build_assign_stmt_array(lbProcedure *p, TokenKind op, lbAddr const &lhs, lbValue const &value) {
  1778. GB_ASSERT(op != Token_Eq);
  1779. Type *lhs_type = lb_addr_type(lhs);
  1780. Type *array_type = base_type(lhs_type);
  1781. GB_ASSERT(is_type_array_like(array_type));
  1782. i64 count = get_array_type_count(array_type);
  1783. Type *elem_type = base_array_type(array_type);
  1784. lbValue rhs = lb_emit_conv(p, value, lhs_type);
  1785. bool inline_array_arith = lb_can_try_to_inline_array_arith(array_type);
  1786. if (lhs.kind == lbAddr_Swizzle) {
  1787. GB_ASSERT(is_type_array(lhs_type));
  1788. struct ValueAndIndex {
  1789. lbValue value;
  1790. u8 index;
  1791. };
  1792. bool indices_handled[4] = {};
  1793. i32 indices[4] = {};
  1794. i32 index_count = 0;
  1795. for (u8 i = 0; i < lhs.swizzle.count; i++) {
  1796. u8 index = lhs.swizzle.indices[i];
  1797. if (indices_handled[index]) {
  1798. continue;
  1799. }
  1800. indices[index_count++] = index;
  1801. }
  1802. lbValue lhs_ptrs[4] = {};
  1803. lbValue x_loads[4] = {};
  1804. lbValue y_loads[4] = {};
  1805. lbValue ops[4] = {};
  1806. for (i32 i = 0; i < index_count; i++) {
  1807. lhs_ptrs[i] = lb_emit_array_epi(p, lhs.addr, indices[i]);
  1808. }
  1809. for (i32 i = 0; i < index_count; i++) {
  1810. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  1811. }
  1812. for (i32 i = 0; i < index_count; i++) {
  1813. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  1814. y_loads[i].type = elem_type;
  1815. }
  1816. for (i32 i = 0; i < index_count; i++) {
  1817. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  1818. }
  1819. for (i32 i = 0; i < index_count; i++) {
  1820. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  1821. }
  1822. return;
  1823. } else if (lhs.kind == lbAddr_SwizzleLarge) {
  1824. GB_ASSERT(is_type_array(lhs_type));
  1825. struct ValueAndIndex {
  1826. lbValue value;
  1827. u32 index;
  1828. };
  1829. Type *bt = base_type(lhs_type);
  1830. GB_ASSERT(bt->kind == Type_Array);
  1831. auto indices_handled = slice_make<bool>(temporary_allocator(), bt->Array.count);
  1832. auto indices = slice_make<i32>(temporary_allocator(), bt->Array.count);
  1833. i32 index_count = 0;
  1834. for (i32 index : lhs.swizzle_large.indices) {
  1835. if (indices_handled[index]) {
  1836. continue;
  1837. }
  1838. indices[index_count++] = index;
  1839. }
  1840. lbValue lhs_ptrs[4] = {};
  1841. lbValue x_loads[4] = {};
  1842. lbValue y_loads[4] = {};
  1843. lbValue ops[4] = {};
  1844. for (i32 i = 0; i < index_count; i++) {
  1845. lhs_ptrs[i] = lb_emit_array_epi(p, lhs.addr, indices[i]);
  1846. }
  1847. for (i32 i = 0; i < index_count; i++) {
  1848. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  1849. }
  1850. for (i32 i = 0; i < index_count; i++) {
  1851. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  1852. y_loads[i].type = elem_type;
  1853. }
  1854. for (i32 i = 0; i < index_count; i++) {
  1855. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  1856. }
  1857. for (i32 i = 0; i < index_count; i++) {
  1858. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  1859. }
  1860. return;
  1861. }
  1862. lbValue x = lb_addr_get_ptr(p, lhs);
  1863. if (inline_array_arith) {
  1864. unsigned n = cast(unsigned)count;
  1865. auto lhs_ptrs = slice_make<lbValue>(temporary_allocator(), n);
  1866. auto x_loads = slice_make<lbValue>(temporary_allocator(), n);
  1867. auto y_loads = slice_make<lbValue>(temporary_allocator(), n);
  1868. auto ops = slice_make<lbValue>(temporary_allocator(), n);
  1869. for (unsigned i = 0; i < n; i++) {
  1870. lhs_ptrs[i] = lb_emit_array_epi(p, x, i);
  1871. }
  1872. for (unsigned i = 0; i < n; i++) {
  1873. x_loads[i] = lb_emit_load(p, lhs_ptrs[i]);
  1874. }
  1875. for (unsigned i = 0; i < n; i++) {
  1876. y_loads[i].value = LLVMBuildExtractValue(p->builder, rhs.value, i, "");
  1877. y_loads[i].type = elem_type;
  1878. }
  1879. for (unsigned i = 0; i < n; i++) {
  1880. ops[i] = lb_emit_arith(p, op, x_loads[i], y_loads[i], elem_type);
  1881. }
  1882. for (unsigned i = 0; i < n; i++) {
  1883. lb_emit_store(p, lhs_ptrs[i], ops[i]);
  1884. }
  1885. } else {
  1886. lbValue y = lb_address_from_load_or_generate_local(p, rhs);
  1887. auto loop_data = lb_loop_start(p, cast(isize)count, t_i32);
  1888. lbValue a_ptr = lb_emit_array_ep(p, x, loop_data.idx);
  1889. lbValue b_ptr = lb_emit_array_ep(p, y, loop_data.idx);
  1890. lbValue a = lb_emit_load(p, a_ptr);
  1891. lbValue b = lb_emit_load(p, b_ptr);
  1892. lbValue c = lb_emit_arith(p, op, a, b, elem_type);
  1893. lb_emit_store(p, a_ptr, c);
  1894. lb_loop_end(p, loop_data);
  1895. }
  1896. }
  1897. gb_internal void lb_build_assign_stmt(lbProcedure *p, AstAssignStmt *as) {
  1898. if (as->op.kind == Token_Eq) {
  1899. auto lvals = array_make<lbAddr>(permanent_allocator(), 0, as->lhs.count);
  1900. for (Ast *lhs : as->lhs) {
  1901. lbAddr lval = {};
  1902. if (!is_blank_ident(lhs)) {
  1903. lval = lb_build_addr(p, lhs);
  1904. }
  1905. array_add(&lvals, lval);
  1906. }
  1907. lb_build_assignment(p, lvals, as->rhs);
  1908. return;
  1909. }
  1910. GB_ASSERT(as->lhs.count == 1);
  1911. GB_ASSERT(as->rhs.count == 1);
  1912. // NOTE(bill): Only 1 += 1 is allowed, no tuples
  1913. // +=, -=, etc
  1914. i32 op_ = cast(i32)as->op.kind;
  1915. op_ += Token_Add - Token_AddEq; // Convert += to +
  1916. TokenKind op = cast(TokenKind)op_;
  1917. if (op == Token_CmpAnd || op == Token_CmpOr) {
  1918. Type *type = as->lhs[0]->tav.type;
  1919. lbValue new_value = lb_emit_logical_binary_expr(p, op, as->lhs[0], as->rhs[0], type);
  1920. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  1921. lb_addr_store(p, lhs, new_value);
  1922. } else {
  1923. lbAddr lhs = lb_build_addr(p, as->lhs[0]);
  1924. lbValue value = lb_build_expr(p, as->rhs[0]);
  1925. Type *lhs_type = lb_addr_type(lhs);
  1926. // NOTE(bill): Allow for the weird edge case of:
  1927. // array *= matrix
  1928. if (op == Token_Mul && is_type_matrix(value.type) && is_type_array(lhs_type)) {
  1929. lbValue old_value = lb_addr_load(p, lhs);
  1930. Type *type = old_value.type;
  1931. lbValue new_value = lb_emit_vector_mul_matrix(p, old_value, value, type);
  1932. lb_addr_store(p, lhs, new_value);
  1933. return;
  1934. }
  1935. if (is_type_array(lhs_type)) {
  1936. lb_build_assign_stmt_array(p, op, lhs, value);
  1937. return;
  1938. } else {
  1939. lbValue old_value = lb_addr_load(p, lhs);
  1940. Type *type = old_value.type;
  1941. lbValue change = lb_emit_conv(p, value, type);
  1942. lbValue new_value = lb_emit_arith(p, op, old_value, change, type);
  1943. lb_addr_store(p, lhs, new_value);
  1944. }
  1945. }
  1946. }
  1947. gb_internal void lb_build_stmt(lbProcedure *p, Ast *node) {
  1948. Ast *prev_stmt = p->curr_stmt;
  1949. defer (p->curr_stmt = prev_stmt);
  1950. p->curr_stmt = node;
  1951. if (p->curr_block != nullptr) {
  1952. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  1953. if (lb_is_instr_terminating(last_instr)) {
  1954. return;
  1955. }
  1956. }
  1957. if (p->debug_info != nullptr) {
  1958. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_ast(p, node));
  1959. }
  1960. u16 prev_state_flags = p->state_flags;
  1961. defer (p->state_flags = prev_state_flags);
  1962. if (node->state_flags != 0) {
  1963. u16 in = node->state_flags;
  1964. u16 out = p->state_flags;
  1965. if (in & StateFlag_bounds_check) {
  1966. out |= StateFlag_bounds_check;
  1967. out &= ~StateFlag_no_bounds_check;
  1968. } else if (in & StateFlag_no_bounds_check) {
  1969. out |= StateFlag_no_bounds_check;
  1970. out &= ~StateFlag_bounds_check;
  1971. }
  1972. if (in & StateFlag_no_type_assert) {
  1973. out |= StateFlag_no_type_assert;
  1974. out &= ~StateFlag_type_assert;
  1975. } else if (in & StateFlag_type_assert) {
  1976. out |= StateFlag_type_assert;
  1977. out &= ~StateFlag_no_type_assert;
  1978. }
  1979. p->state_flags = out;
  1980. }
  1981. switch (node->kind) {
  1982. case_ast_node(bs, EmptyStmt, node);
  1983. case_end;
  1984. case_ast_node(us, UsingStmt, node);
  1985. case_end;
  1986. case_ast_node(ws, WhenStmt, node);
  1987. lb_build_when_stmt(p, ws);
  1988. case_end;
  1989. case_ast_node(bs, BlockStmt, node);
  1990. lbBlock *done = nullptr;
  1991. if (bs->label != nullptr) {
  1992. done = lb_create_block(p, "block.done");
  1993. lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr);
  1994. tl->is_block = true;
  1995. }
  1996. lb_open_scope(p, bs->scope);
  1997. lb_build_stmt_list(p, bs->stmts);
  1998. lb_close_scope(p, lbDeferExit_Default, nullptr);
  1999. if (done != nullptr) {
  2000. lb_emit_jump(p, done);
  2001. lb_start_block(p, done);
  2002. }
  2003. if (bs->label != nullptr) {
  2004. lb_pop_target_list(p);
  2005. }
  2006. case_end;
  2007. case_ast_node(vd, ValueDecl, node);
  2008. if (!vd->is_mutable) {
  2009. return;
  2010. }
  2011. bool is_static = false;
  2012. if (vd->names.count > 0) {
  2013. for (Ast *name : vd->names) {
  2014. if (!is_blank_ident(name)) {
  2015. GB_ASSERT(name->kind == Ast_Ident);
  2016. Entity *e = entity_of_node(name);
  2017. TokenPos pos = ast_token(name).pos;
  2018. GB_ASSERT_MSG(e != nullptr, "\n%s missing entity for %.*s", token_pos_to_string(pos), LIT(name->Ident.token.string));
  2019. if (e->flags & EntityFlag_Static) {
  2020. // NOTE(bill): If one of the entities is static, they all are
  2021. is_static = true;
  2022. break;
  2023. }
  2024. }
  2025. }
  2026. }
  2027. if (is_static) {
  2028. lb_build_static_variables(p, vd);
  2029. return;
  2030. }
  2031. TEMPORARY_ALLOCATOR_GUARD();
  2032. auto const &values = vd->values;
  2033. if (values.count == 0) {
  2034. auto lvals = slice_make<lbAddr>(temporary_allocator(), vd->names.count);
  2035. for_array(i, vd->names) {
  2036. Ast *name = vd->names[i];
  2037. if (!is_blank_ident(name)) {
  2038. Entity *e = entity_of_node(name);
  2039. // bool zero_init = true; // Always do it
  2040. bool zero_init = values.count == 0;
  2041. lvals[i] = lb_add_local(p, e->type, e, zero_init);
  2042. }
  2043. }
  2044. } else {
  2045. auto lvals_preused = slice_make<bool>(temporary_allocator(), vd->names.count);
  2046. auto lvals = slice_make<lbAddr>(temporary_allocator(), vd->names.count);
  2047. auto inits = array_make<lbValue>(temporary_allocator(), 0, lvals.count);
  2048. isize lval_index = 0;
  2049. for (Ast *rhs : values) {
  2050. rhs = unparen_expr(rhs);
  2051. lbValue init = lb_build_expr(p, rhs);
  2052. if (rhs->kind == Ast_CompoundLit) {
  2053. // NOTE(bill, 2023-02-17): lb_const_value might produce a stack local variable for the
  2054. // compound literal, so reusing that variable should minimize the stack wastage
  2055. lbAddr *comp_lit_addr = map_get(&p->module->exact_value_compound_literal_addr_map, rhs);
  2056. if (comp_lit_addr) {
  2057. if (Entity *e = entity_of_node(vd->names[lval_index])) {
  2058. lbValue val = comp_lit_addr->addr;
  2059. lb_add_entity(p->module, e, val);
  2060. lb_add_debug_local_variable(p, val.value, e->type, e->token);
  2061. lvals_preused[lval_index] = true;
  2062. lvals[lval_index] = *comp_lit_addr;
  2063. }
  2064. }
  2065. }
  2066. lval_index += lb_append_tuple_values(p, &inits, init);
  2067. }
  2068. GB_ASSERT(lval_index == lvals.count);
  2069. for_array(i, vd->names) {
  2070. Ast *name = vd->names[i];
  2071. if (!is_blank_ident(name) && !lvals_preused[i]) {
  2072. Entity *e = entity_of_node(name);
  2073. bool zero_init = values.count == 0;
  2074. lvals[i] = lb_add_local(p, e->type, e, zero_init);
  2075. }
  2076. }
  2077. GB_ASSERT(lvals.count == inits.count);
  2078. for_array(i, inits) {
  2079. lbAddr lval = lvals[i];
  2080. lbValue init = inits[i];
  2081. lb_addr_store(p, lval, init);
  2082. }
  2083. }
  2084. case_end;
  2085. case_ast_node(as, AssignStmt, node);
  2086. lb_build_assign_stmt(p, as);
  2087. case_end;
  2088. case_ast_node(es, ExprStmt, node);
  2089. lb_build_expr(p, es->expr);
  2090. case_end;
  2091. case_ast_node(ds, DeferStmt, node);
  2092. lb_add_defer_node(p, p->scope_index, ds->stmt);
  2093. case_end;
  2094. case_ast_node(rs, ReturnStmt, node);
  2095. lb_build_return_stmt(p, rs->results);
  2096. case_end;
  2097. case_ast_node(is, IfStmt, node);
  2098. lb_build_if_stmt(p, node);
  2099. case_end;
  2100. case_ast_node(fs, ForStmt, node);
  2101. lb_build_for_stmt(p, node);
  2102. case_end;
  2103. case_ast_node(rs, RangeStmt, node);
  2104. lb_build_range_stmt(p, rs, rs->scope);
  2105. case_end;
  2106. case_ast_node(rs, UnrollRangeStmt, node);
  2107. lb_build_unroll_range_stmt(p, rs, rs->scope);
  2108. case_end;
  2109. case_ast_node(ss, SwitchStmt, node);
  2110. lb_build_switch_stmt(p, ss, ss->scope);
  2111. case_end;
  2112. case_ast_node(ss, TypeSwitchStmt, node);
  2113. lb_build_type_switch_stmt(p, ss);
  2114. case_end;
  2115. case_ast_node(bs, BranchStmt, node);
  2116. lbBlock *block = nullptr;
  2117. if (bs->label != nullptr) {
  2118. lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label);
  2119. switch (bs->token.kind) {
  2120. case Token_break: block = bb.break_; break;
  2121. case Token_continue: block = bb.continue_; break;
  2122. case Token_fallthrough:
  2123. GB_PANIC("fallthrough cannot have a label");
  2124. break;
  2125. }
  2126. } else {
  2127. for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) {
  2128. if (t->is_block) {
  2129. continue;
  2130. }
  2131. switch (bs->token.kind) {
  2132. case Token_break: block = t->break_; break;
  2133. case Token_continue: block = t->continue_; break;
  2134. case Token_fallthrough: block = t->fallthrough_; break;
  2135. }
  2136. }
  2137. }
  2138. if (block != nullptr) {
  2139. lb_emit_defer_stmts(p, lbDeferExit_Branch, block);
  2140. }
  2141. lb_emit_jump(p, block);
  2142. lb_start_block(p, lb_create_block(p, "unreachable"));
  2143. case_end;
  2144. }
  2145. }
  2146. gb_internal void lb_build_defer_stmt(lbProcedure *p, lbDefer const &d) {
  2147. if (p->curr_block == nullptr) {
  2148. return;
  2149. }
  2150. // NOTE(bill): The prev block may defer injection before it's terminator
  2151. LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block);
  2152. if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) {
  2153. // NOTE(bill): ReturnStmt defer stuff will be handled previously
  2154. return;
  2155. }
  2156. isize prev_context_stack_count = p->context_stack.count;
  2157. GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity);
  2158. defer (p->context_stack.count = prev_context_stack_count);
  2159. p->context_stack.count = d.context_stack_count;
  2160. lbBlock *b = lb_create_block(p, "defer");
  2161. if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) {
  2162. lb_emit_jump(p, b);
  2163. }
  2164. lb_start_block(p, b);
  2165. if (d.kind == lbDefer_Node) {
  2166. lb_build_stmt(p, d.stmt);
  2167. } else if (d.kind == lbDefer_Proc) {
  2168. lb_emit_call(p, d.proc.deferred, d.proc.result_as_args);
  2169. }
  2170. }
  2171. gb_internal void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) {
  2172. isize count = p->defer_stmts.count;
  2173. isize i = count;
  2174. while (i --> 0) {
  2175. lbDefer const &d = p->defer_stmts[i];
  2176. if (kind == lbDeferExit_Default) {
  2177. if (p->scope_index == d.scope_index &&
  2178. d.scope_index > 0) {
  2179. lb_build_defer_stmt(p, d);
  2180. array_pop(&p->defer_stmts);
  2181. continue;
  2182. } else {
  2183. break;
  2184. }
  2185. } else if (kind == lbDeferExit_Return) {
  2186. lb_build_defer_stmt(p, d);
  2187. } else if (kind == lbDeferExit_Branch) {
  2188. GB_ASSERT(block != nullptr);
  2189. isize lower_limit = block->scope_index;
  2190. if (lower_limit < d.scope_index) {
  2191. lb_build_defer_stmt(p, d);
  2192. }
  2193. }
  2194. }
  2195. }
  2196. gb_internal void lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) {
  2197. Type *pt = base_type(p->type);
  2198. GB_ASSERT(pt->kind == Type_Proc);
  2199. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2200. GB_ASSERT(p->context_stack.count != 0);
  2201. }
  2202. lbDefer *d = array_add_and_get(&p->defer_stmts);
  2203. d->kind = lbDefer_Node;
  2204. d->scope_index = scope_index;
  2205. d->context_stack_count = p->context_stack.count;
  2206. d->block = p->curr_block;
  2207. d->stmt = stmt;
  2208. }
  2209. gb_internal void lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array<lbValue> const &result_as_args) {
  2210. Type *pt = base_type(p->type);
  2211. GB_ASSERT(pt->kind == Type_Proc);
  2212. if (pt->Proc.calling_convention == ProcCC_Odin) {
  2213. GB_ASSERT(p->context_stack.count != 0);
  2214. }
  2215. lbDefer *d = array_add_and_get(&p->defer_stmts);
  2216. d->kind = lbDefer_Proc;
  2217. d->scope_index = p->scope_index;
  2218. d->block = p->curr_block;
  2219. d->context_stack_count = p->context_stack.count;
  2220. d->proc.deferred = deferred;
  2221. d->proc.result_as_args = result_as_args;
  2222. }