llvm_backend_proc.cpp 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360
  1. lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  2. GB_ASSERT(entity != nullptr);
  3. GB_ASSERT(entity->kind == Entity_Procedure);
  4. if (!entity->Procedure.is_foreign) {
  5. GB_ASSERT(entity->flags & EntityFlag_ProcBodyChecked);
  6. }
  7. String link_name = {};
  8. if (ignore_body) {
  9. lbModule *other_module = lb_pkg_module(m->gen, entity->pkg);
  10. link_name = lb_get_entity_name(other_module, entity);
  11. } else {
  12. link_name = lb_get_entity_name(m, entity);
  13. }
  14. {
  15. StringHashKey key = string_hash_string(link_name);
  16. lbValue *found = string_map_get(&m->members, key);
  17. if (found) {
  18. lb_add_entity(m, entity, *found);
  19. return string_map_must_get(&m->procedures, key);
  20. }
  21. }
  22. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  23. p->module = m;
  24. entity->code_gen_module = m;
  25. entity->code_gen_procedure = p;
  26. p->entity = entity;
  27. p->name = link_name;
  28. DeclInfo *decl = entity->decl_info;
  29. ast_node(pl, ProcLit, decl->proc_lit);
  30. Type *pt = base_type(entity->type);
  31. GB_ASSERT(pt->kind == Type_Proc);
  32. p->type = entity->type;
  33. p->type_expr = decl->type_expr;
  34. p->body = pl->body;
  35. p->inlining = pl->inlining;
  36. p->is_foreign = entity->Procedure.is_foreign;
  37. p->is_export = entity->Procedure.is_export;
  38. p->is_entry_point = false;
  39. gbAllocator a = heap_allocator();
  40. p->children.allocator = a;
  41. p->params.allocator = a;
  42. p->defer_stmts.allocator = a;
  43. p->blocks.allocator = a;
  44. p->branch_blocks.allocator = a;
  45. p->context_stack.allocator = a;
  46. p->scope_stack.allocator = a;
  47. if (p->is_foreign) {
  48. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  49. }
  50. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  51. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  52. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  53. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  54. lb_ensure_abi_function_type(m, p);
  55. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  56. if (false) {
  57. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  58. // TODO(bill): Clean up this logic
  59. if (!is_arch_wasm()) {
  60. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  61. }
  62. LLVMSetFunctionCallConv(p->value, cc_kind);
  63. }
  64. if (pt->Proc.diverging) {
  65. lb_add_attribute_to_proc(m, p->value, "noreturn");
  66. }
  67. if (pt->Proc.calling_convention == ProcCC_Naked) {
  68. lb_add_attribute_to_proc(m, p->value, "naked");
  69. }
  70. switch (p->inlining) {
  71. case ProcInlining_inline:
  72. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  73. break;
  74. case ProcInlining_no_inline:
  75. lb_add_attribute_to_proc(m, p->value, "noinline");
  76. break;
  77. }
  78. if (entity->flags & EntityFlag_Cold) {
  79. lb_add_attribute_to_proc(m, p->value, "cold");
  80. }
  81. switch (entity->Procedure.optimization_mode) {
  82. case ProcedureOptimizationMode_None:
  83. lb_add_attribute_to_proc(m, p->value, "optnone");
  84. break;
  85. case ProcedureOptimizationMode_Minimal:
  86. lb_add_attribute_to_proc(m, p->value, "optnone");
  87. break;
  88. case ProcedureOptimizationMode_Size:
  89. lb_add_attribute_to_proc(m, p->value, "optsize");
  90. break;
  91. case ProcedureOptimizationMode_Speed:
  92. // TODO(bill): handle this correctly
  93. lb_add_attribute_to_proc(m, p->value, "optsize");
  94. break;
  95. }
  96. // lbCallingConventionKind cc_kind = lbCallingConvention_C;
  97. // // TODO(bill): Clean up this logic
  98. // if (build_context.metrics.os != TargetOs_js) {
  99. // cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  100. // }
  101. // LLVMSetFunctionCallConv(p->value, cc_kind);
  102. lbValue proc_value = {p->value, p->type};
  103. lb_add_entity(m, entity, proc_value);
  104. lb_add_member(m, p->name, proc_value);
  105. lb_add_procedure_value(m, p);
  106. if (p->is_export) {
  107. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  108. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  109. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  110. if (is_arch_wasm()) {
  111. char const *export_name = alloc_cstring(permanent_allocator(), p->name);
  112. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-export-name", export_name);
  113. }
  114. } else if (!p->is_foreign) {
  115. if (!USE_SEPARATE_MODULES) {
  116. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  117. // NOTE(bill): if a procedure is defined in package runtime and uses a custom link name,
  118. // then it is very likely it is required by LLVM and thus cannot have internal linkage
  119. if (entity->pkg != nullptr && entity->pkg->kind == Package_Runtime && p->body != nullptr) {
  120. GB_ASSERT(entity->kind == Entity_Procedure);
  121. if (entity->Procedure.link_name != "") {
  122. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  123. }
  124. }
  125. }
  126. }
  127. if (p->is_foreign) {
  128. if (is_arch_wasm()) {
  129. char const *import_name = alloc_cstring(permanent_allocator(), p->name);
  130. char const *module_name = "env";
  131. if (entity->Procedure.foreign_library != nullptr) {
  132. Entity *foreign_library = entity->Procedure.foreign_library;
  133. GB_ASSERT(foreign_library->kind == Entity_LibraryName);
  134. if (foreign_library->LibraryName.paths.count > 0) {
  135. module_name = alloc_cstring(permanent_allocator(), foreign_library->LibraryName.paths[0]);
  136. }
  137. }
  138. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-name", import_name);
  139. LLVMAddTargetDependentFunctionAttr(p->value, "wasm-import-module", module_name);
  140. }
  141. }
  142. // NOTE(bill): offset==0 is the return value
  143. isize offset = 1;
  144. if (pt->Proc.return_by_pointer) {
  145. offset = 2;
  146. }
  147. isize parameter_index = 0;
  148. if (pt->Proc.param_count) {
  149. TypeTuple *params = &pt->Proc.params->Tuple;
  150. for (isize i = 0; i < pt->Proc.param_count; i++) {
  151. Entity *e = params->variables[i];
  152. if (e->kind != Entity_Variable) {
  153. continue;
  154. }
  155. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  156. continue;
  157. }
  158. if (e->flags&EntityFlag_NoAlias) {
  159. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  160. }
  161. parameter_index += 1;
  162. }
  163. }
  164. if (ignore_body) {
  165. p->body = nullptr;
  166. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  167. }
  168. if (m->debug_builder) { // Debug Information
  169. Type *bt = base_type(p->type);
  170. unsigned line = cast(unsigned)entity->token.pos.line;
  171. LLVMMetadataRef scope = nullptr;
  172. LLVMMetadataRef file = nullptr;
  173. LLVMMetadataRef type = nullptr;
  174. scope = p->module->debug_compile_unit;
  175. type = lb_debug_type_internal_proc(m, bt);
  176. Ast *ident = entity->identifier.load();
  177. if (entity->file != nullptr) {
  178. file = lb_get_llvm_metadata(m, entity->file);
  179. scope = file;
  180. } else if (ident != nullptr && ident->file != nullptr) {
  181. file = lb_get_llvm_metadata(m, ident->file);
  182. scope = file;
  183. } else if (entity->scope != nullptr) {
  184. file = lb_get_llvm_metadata(m, entity->scope->file);
  185. scope = file;
  186. }
  187. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  188. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  189. LLVMBool is_local_to_unit = false;
  190. LLVMBool is_definition = p->body != nullptr;
  191. unsigned scope_line = line;
  192. u32 flags = LLVMDIFlagStaticMember;
  193. LLVMBool is_optimized = false;
  194. if (bt->Proc.diverging) {
  195. flags |= LLVMDIFlagNoReturn;
  196. }
  197. if (p->body == nullptr) {
  198. flags |= LLVMDIFlagPrototyped;
  199. is_optimized = false;
  200. }
  201. if (p->body != nullptr) {
  202. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  203. cast(char const *)entity->token.string.text, entity->token.string.len,
  204. cast(char const *)p->name.text, p->name.len,
  205. file, line, type,
  206. is_local_to_unit, is_definition,
  207. scope_line, cast(LLVMDIFlags)flags, is_optimized
  208. );
  209. GB_ASSERT(p->debug_info != nullptr);
  210. LLVMSetSubprogram(p->value, p->debug_info);
  211. lb_set_llvm_metadata(m, p, p->debug_info);
  212. }
  213. }
  214. return p;
  215. }
  216. lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  217. {
  218. lbValue *found = string_map_get(&m->members, link_name);
  219. GB_ASSERT(found == nullptr);
  220. }
  221. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  222. p->module = m;
  223. p->name = link_name;
  224. p->type = type;
  225. p->type_expr = nullptr;
  226. p->body = nullptr;
  227. p->tags = 0;
  228. p->inlining = ProcInlining_none;
  229. p->is_foreign = false;
  230. p->is_export = false;
  231. p->is_entry_point = false;
  232. gbAllocator a = permanent_allocator();
  233. p->children.allocator = a;
  234. p->params.allocator = a;
  235. p->defer_stmts.allocator = a;
  236. p->blocks.allocator = a;
  237. p->branch_blocks.allocator = a;
  238. p->context_stack.allocator = a;
  239. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  240. LLVMTypeRef func_ptr_type = lb_type(m, p->type);
  241. LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type);
  242. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  243. Type *pt = p->type;
  244. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  245. // TODO(bill): Clean up this logic
  246. if (!is_arch_wasm()) {
  247. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  248. }
  249. LLVMSetFunctionCallConv(p->value, cc_kind);
  250. lbValue proc_value = {p->value, p->type};
  251. lb_add_member(m, p->name, proc_value);
  252. lb_add_procedure_value(m, p);
  253. // NOTE(bill): offset==0 is the return value
  254. isize offset = 1;
  255. if (pt->Proc.return_by_pointer) {
  256. lb_add_proc_attribute_at_index(p, 1, "sret");
  257. lb_add_proc_attribute_at_index(p, 1, "noalias");
  258. offset = 2;
  259. }
  260. isize parameter_index = 0;
  261. if (pt->Proc.calling_convention == ProcCC_Odin) {
  262. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  263. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  264. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  265. }
  266. return p;
  267. }
  268. lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  269. lbParamPasskind kind = lbParamPass_Value;
  270. if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  271. if (is_type_pointer(abi_type)) {
  272. GB_ASSERT(e->kind == Entity_Variable);
  273. Type *av = core_type(type_deref(abi_type));
  274. if (are_types_identical(av, core_type(e->type))) {
  275. kind = lbParamPass_Pointer;
  276. if (e->flags&EntityFlag_Value) {
  277. kind = lbParamPass_ConstRef;
  278. }
  279. } else {
  280. kind = lbParamPass_BitCast;
  281. }
  282. } else if (is_type_integer(abi_type)) {
  283. kind = lbParamPass_Integer;
  284. } else if (abi_type == t_llvm_bool) {
  285. kind = lbParamPass_Value;
  286. } else if (is_type_boolean(abi_type)) {
  287. kind = lbParamPass_Integer;
  288. } else if (is_type_simd_vector(abi_type)) {
  289. kind = lbParamPass_BitCast;
  290. } else if (is_type_float(abi_type)) {
  291. kind = lbParamPass_BitCast;
  292. } else if (is_type_tuple(abi_type)) {
  293. kind = lbParamPass_Tuple;
  294. } else if (is_type_proc(abi_type)) {
  295. kind = lbParamPass_Value;
  296. } else {
  297. GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  298. }
  299. }
  300. if (kind_) *kind_ = kind;
  301. lbValue res = {};
  302. res.value = LLVMGetParam(p->value, cast(unsigned)index);
  303. res.type = abi_type;
  304. return res;
  305. }
  306. void lb_start_block(lbProcedure *p, lbBlock *b) {
  307. GB_ASSERT(b != nullptr);
  308. if (!b->appended) {
  309. b->appended = true;
  310. LLVMAppendExistingBasicBlock(p->value, b->block);
  311. }
  312. LLVMPositionBuilderAtEnd(p->builder, b->block);
  313. p->curr_block = b;
  314. }
  315. void lb_begin_procedure_body(lbProcedure *p) {
  316. DeclInfo *decl = decl_info_of_entity(p->entity);
  317. if (decl != nullptr) {
  318. for_array(i, decl->labels) {
  319. BlockLabel bl = decl->labels[i];
  320. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  321. array_add(&p->branch_blocks, bb);
  322. }
  323. }
  324. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  325. p->decl_block = lb_create_block(p, "decls", true);
  326. p->entry_block = lb_create_block(p, "entry", true);
  327. lb_start_block(p, p->entry_block);
  328. GB_ASSERT(p->type != nullptr);
  329. lb_ensure_abi_function_type(p->module, p);
  330. {
  331. lbFunctionType *ft = p->abi_function_type;
  332. unsigned param_offset = 0;
  333. lbValue return_ptr_value = {};
  334. if (ft->ret.kind == lbArg_Indirect) {
  335. // NOTE(bill): this must be parameter 0
  336. String name = str_lit("agg.result");
  337. Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results));
  338. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  339. e->flags |= EntityFlag_Sret | EntityFlag_NoAlias;
  340. return_ptr_value.value = LLVMGetParam(p->value, 0);
  341. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  342. return_ptr_value.type = ptr_type;
  343. p->return_ptr = lb_addr(return_ptr_value);
  344. lb_add_entity(p->module, e, return_ptr_value);
  345. param_offset += 1;
  346. }
  347. if (p->type->Proc.params != nullptr) {
  348. TypeTuple *params = &p->type->Proc.params->Tuple;
  349. unsigned param_index = 0;
  350. for_array(i, params->variables) {
  351. Entity *e = params->variables[i];
  352. if (e->kind != Entity_Variable) {
  353. continue;
  354. }
  355. lbArgType *arg_type = &ft->args[param_index];
  356. if (arg_type->kind == lbArg_Ignore) {
  357. continue;
  358. } else if (arg_type->kind == lbArg_Direct) {
  359. lbParamPasskind kind = lbParamPass_Value;
  360. LLVMTypeRef param_type = lb_type(p->module, e->type);
  361. if (param_type != arg_type->type) {
  362. kind = lbParamPass_BitCast;
  363. }
  364. LLVMValueRef value = LLVMGetParam(p->value, param_offset+param_index);
  365. value = OdinLLVMBuildTransmute(p, value, param_type);
  366. lbValue param = {};
  367. param.value = value;
  368. param.type = e->type;
  369. array_add(&p->params, param);
  370. if (e->token.string.len != 0) {
  371. lbAddr l = lb_add_local(p, e->type, e, false, param_index);
  372. lb_addr_store(p, l, param);
  373. }
  374. param_index += 1;
  375. } else if (arg_type->kind == lbArg_Indirect) {
  376. LLVMValueRef value_ptr = LLVMGetParam(p->value, param_offset+param_index);
  377. LLVMValueRef value = LLVMBuildLoad(p->builder, value_ptr, "");
  378. lbValue param = {};
  379. param.value = value;
  380. param.type = e->type;
  381. array_add(&p->params, param);
  382. lbValue ptr = {};
  383. ptr.value = value_ptr;
  384. ptr.type = alloc_type_pointer(e->type);
  385. lb_add_entity(p->module, e, ptr);
  386. param_index += 1;
  387. }
  388. }
  389. }
  390. if (p->type->Proc.has_named_results) {
  391. GB_ASSERT(p->type->Proc.result_count > 0);
  392. TypeTuple *results = &p->type->Proc.results->Tuple;
  393. for_array(i, results->variables) {
  394. Entity *e = results->variables[i];
  395. GB_ASSERT(e->kind == Entity_Variable);
  396. if (e->token.string != "") {
  397. GB_ASSERT(!is_blank_ident(e->token));
  398. lbAddr res = {};
  399. if (return_ptr_value.value) {
  400. lbValue ptr = return_ptr_value;
  401. if (results->variables.count != 1) {
  402. ptr = lb_emit_struct_ep(p, ptr, cast(i32)i);
  403. }
  404. res = lb_addr(ptr);
  405. lb_add_entity(p->module, e, ptr);
  406. } else {
  407. res = lb_add_local(p, e->type, e);
  408. }
  409. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  410. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  411. lb_addr_store(p, res, c);
  412. }
  413. }
  414. }
  415. }
  416. }
  417. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  418. lb_push_context_onto_stack_from_implicit_parameter(p);
  419. }
  420. lb_start_block(p, p->entry_block);
  421. if (p->debug_info != nullptr) {
  422. TokenPos pos = {};
  423. if (p->body != nullptr) {
  424. pos = ast_token(p->body).pos;
  425. } else if (p->type_expr != nullptr) {
  426. pos = ast_token(p->type_expr).pos;
  427. } else if (p->entity != nullptr) {
  428. pos = p->entity->token.pos;
  429. }
  430. if (pos.file_id != 0) {
  431. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  432. }
  433. if (p->context_stack.count != 0) {
  434. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  435. }
  436. }
  437. }
  438. void lb_end_procedure_body(lbProcedure *p) {
  439. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  440. LLVMBuildBr(p->builder, p->entry_block->block);
  441. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  442. LLVMValueRef instr = nullptr;
  443. // Make sure there is a "ret void" at the end of a procedure with no return type
  444. if (p->type->Proc.result_count == 0) {
  445. instr = LLVMGetLastInstruction(p->curr_block->block);
  446. if (!lb_is_instr_terminating(instr)) {
  447. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  448. LLVMBuildRetVoid(p->builder);
  449. }
  450. }
  451. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  452. LLVMBasicBlockRef block = nullptr;
  453. // Make sure every block terminates, and if not, make it unreachable
  454. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  455. instr = LLVMGetLastInstruction(block);
  456. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  457. LLVMPositionBuilderAtEnd(p->builder, block);
  458. LLVMBuildUnreachable(p->builder);
  459. }
  460. }
  461. p->curr_block = nullptr;
  462. p->state_flags = 0;
  463. }
  464. void lb_end_procedure(lbProcedure *p) {
  465. LLVMDisposeBuilder(p->builder);
  466. }
  467. void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  468. GB_ASSERT(pd->body != nullptr);
  469. lbModule *m = p->module;
  470. auto *min_dep_set = &m->info->minimum_dependency_set;
  471. if (ptr_set_exists(min_dep_set, e) == false) {
  472. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  473. return;
  474. }
  475. // NOTE(bill): Generate a new name
  476. // parent.name-guid
  477. String original_name = e->token.string;
  478. String pd_name = original_name;
  479. if (e->Procedure.link_name.len > 0) {
  480. pd_name = e->Procedure.link_name;
  481. }
  482. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  483. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  484. i32 guid = cast(i32)p->children.count;
  485. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  486. String name = make_string(cast(u8 *)name_text, name_len-1);
  487. e->Procedure.link_name = name;
  488. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  489. e->code_gen_procedure = nested_proc;
  490. lbValue value = {};
  491. value.value = nested_proc->value;
  492. value.type = nested_proc->type;
  493. lb_add_entity(m, e, value);
  494. array_add(&p->children, nested_proc);
  495. array_add(&m->procedures_to_generate, nested_proc);
  496. }
  497. Array<lbValue> lb_value_to_array(lbProcedure *p, lbValue value) {
  498. Array<lbValue> array = {};
  499. Type *t = base_type(value.type);
  500. if (t == nullptr) {
  501. // Do nothing
  502. } else if (is_type_tuple(t)) {
  503. GB_ASSERT(t->kind == Type_Tuple);
  504. auto *rt = &t->Tuple;
  505. if (rt->variables.count > 0) {
  506. array = array_make<lbValue>(permanent_allocator(), rt->variables.count);
  507. for_array(i, rt->variables) {
  508. lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i);
  509. array[i] = elem;
  510. }
  511. }
  512. } else {
  513. array = array_make<lbValue>(permanent_allocator(), 1);
  514. array[0] = value;
  515. }
  516. return array;
  517. }
  518. lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array<lbValue> const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) {
  519. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  520. unsigned arg_count = cast(unsigned)processed_args.count;
  521. if (return_ptr.value != nullptr) {
  522. arg_count += 1;
  523. }
  524. if (context_ptr.addr.value != nullptr) {
  525. arg_count += 1;
  526. }
  527. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  528. isize arg_index = 0;
  529. if (return_ptr.value != nullptr) {
  530. args[arg_index++] = return_ptr.value;
  531. }
  532. for_array(i, processed_args) {
  533. lbValue arg = processed_args[i];
  534. args[arg_index++] = arg.value;
  535. }
  536. if (context_ptr.addr.value != nullptr) {
  537. LLVMValueRef cp = context_ptr.addr.value;
  538. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  539. args[arg_index++] = cp;
  540. }
  541. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  542. GB_ASSERT(curr_block != p->decl_block->block);
  543. {
  544. LLVMTypeRef ftp = lb_type(p->module, value.type);
  545. LLVMValueRef fn = value.value;
  546. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  547. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  548. }
  549. LLVMTypeRef fnp = LLVMGetElementType(LLVMTypeOf(fn));
  550. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  551. {
  552. unsigned param_count = LLVMCountParamTypes(fnp);
  553. GB_ASSERT(arg_count >= param_count);
  554. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  555. LLVMGetParamTypes(fnp, param_types);
  556. for (unsigned i = 0; i < param_count; i++) {
  557. LLVMTypeRef param_type = param_types[i];
  558. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  559. // LLVMTypeKind param_kind = LLVMGetTypeKind(param_type);
  560. // LLVMTypeKind arg_kind = LLVMGetTypeKind(arg_type);
  561. GB_ASSERT_MSG(
  562. arg_type == param_type,
  563. "Parameter types do not match: %s != %s, argument: %s",
  564. LLVMPrintTypeToString(arg_type),
  565. LLVMPrintTypeToString(param_type),
  566. LLVMPrintValueToString(args[i])
  567. );
  568. }
  569. }
  570. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  571. switch (inlining) {
  572. case ProcInlining_none:
  573. break;
  574. case ProcInlining_inline:
  575. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  576. break;
  577. case ProcInlining_no_inline:
  578. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  579. break;
  580. }
  581. lbValue res = {};
  582. res.value = ret;
  583. res.type = abi_rt;
  584. return res;
  585. }
  586. }
  587. lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  588. AstPackage *pkg = m->info->runtime_package;
  589. Entity *e = scope_lookup_current(pkg->scope, name);
  590. return lb_find_procedure_value_from_entity(m, e);
  591. }
  592. lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  593. String name = make_string_c(c_name);
  594. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  595. return lb_emit_call(p, proc, args);
  596. }
  597. lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining, bool use_copy_elision_hint) {
  598. lbModule *m = p->module;
  599. Type *pt = base_type(value.type);
  600. GB_ASSERT(pt->kind == Type_Proc);
  601. Type *results = pt->Proc.results;
  602. if (p->entity != nullptr) {
  603. if (p->entity->flags & EntityFlag_Disabled) {
  604. return {};
  605. }
  606. }
  607. lbAddr context_ptr = {};
  608. if (pt->Proc.calling_convention == ProcCC_Odin) {
  609. context_ptr = lb_find_or_generate_context_ptr(p);
  610. }
  611. defer (if (pt->Proc.diverging) {
  612. LLVMBuildUnreachable(p->builder);
  613. });
  614. bool is_c_vararg = pt->Proc.c_vararg;
  615. isize param_count = pt->Proc.param_count;
  616. if (is_c_vararg) {
  617. GB_ASSERT(param_count-1 <= args.count);
  618. param_count -= 1;
  619. } else {
  620. GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count);
  621. }
  622. lbValue result = {};
  623. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  624. {
  625. lbFunctionType *ft = lb_get_function_type(m, p, pt);
  626. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  627. unsigned param_index = 0;
  628. for (isize i = 0; i < param_count; i++) {
  629. Entity *e = pt->Proc.params->Tuple.variables[i];
  630. if (e->kind != Entity_Variable) {
  631. continue;
  632. }
  633. GB_ASSERT(e->flags & EntityFlag_Param);
  634. Type *original_type = e->type;
  635. lbArgType *arg = &ft->args[param_index];
  636. if (arg->kind == lbArg_Ignore) {
  637. continue;
  638. }
  639. lbValue x = lb_emit_conv(p, args[i], original_type);
  640. LLVMTypeRef xt = lb_type(p->module, x.type);
  641. if (arg->kind == lbArg_Direct) {
  642. LLVMTypeRef abi_type = arg->cast_type;
  643. if (!abi_type) {
  644. abi_type = arg->type;
  645. }
  646. if (xt == abi_type) {
  647. array_add(&processed_args, x);
  648. } else {
  649. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  650. array_add(&processed_args, x);
  651. }
  652. } else if (arg->kind == lbArg_Indirect) {
  653. lbValue ptr = {};
  654. if (arg->is_byval) {
  655. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  656. } else if (is_calling_convention_odin(pt->Proc.calling_convention)) {
  657. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  658. // i.e. `T const &` in C++
  659. ptr = lb_address_from_load_or_generate_local(p, x);
  660. } else {
  661. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  662. }
  663. array_add(&processed_args, ptr);
  664. }
  665. param_index += 1;
  666. }
  667. if (is_c_vararg) {
  668. for (isize i = processed_args.count; i < args.count; i++) {
  669. array_add(&processed_args, args[i]);
  670. }
  671. }
  672. if (inlining == ProcInlining_none) {
  673. inlining = p->inlining;
  674. }
  675. Type *rt = reduce_tuple_to_single_type(results);
  676. if (return_by_pointer) {
  677. lbValue return_ptr = {};
  678. if (use_copy_elision_hint && p->copy_elision_hint.ptr.value != nullptr) {
  679. if (are_types_identical(type_deref(p->copy_elision_hint.ptr.type), rt)) {
  680. return_ptr = lb_consume_copy_elision_hint(p);
  681. }
  682. }
  683. if (return_ptr.value == nullptr) {
  684. lbAddr r = lb_add_local_generated(p, rt, true);
  685. return_ptr = r.addr;
  686. }
  687. GB_ASSERT(is_type_pointer(return_ptr.type));
  688. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  689. result = lb_emit_load(p, return_ptr);
  690. } else if (rt != nullptr) {
  691. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  692. if (ft->ret.cast_type) {
  693. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  694. }
  695. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  696. result.type = rt;
  697. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  698. result.type = t_llvm_bool;
  699. }
  700. if (!is_type_tuple(rt)) {
  701. result = lb_emit_conv(p, result, rt);
  702. }
  703. } else {
  704. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  705. }
  706. }
  707. Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value));
  708. if (found != nullptr) {
  709. Entity *e = *found;
  710. if (e != nullptr && entity_has_deferred_procedure(e)) {
  711. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  712. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  713. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  714. auto in_args = args;
  715. Array<lbValue> result_as_args = {};
  716. switch (kind) {
  717. case DeferredProcedure_none:
  718. break;
  719. case DeferredProcedure_in:
  720. result_as_args = in_args;
  721. break;
  722. case DeferredProcedure_out:
  723. result_as_args = lb_value_to_array(p, result);
  724. break;
  725. case DeferredProcedure_in_out:
  726. {
  727. auto out_args = lb_value_to_array(p, result);
  728. array_init(&result_as_args, permanent_allocator(), in_args.count + out_args.count);
  729. array_copy(&result_as_args, in_args, 0);
  730. array_copy(&result_as_args, out_args, in_args.count);
  731. }
  732. break;
  733. }
  734. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  735. }
  736. }
  737. return result;
  738. }
  739. lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  740. ast_node(ce, CallExpr, expr);
  741. switch (id) {
  742. case BuiltinProc_DIRECTIVE: {
  743. ast_node(bd, BasicDirective, ce->proc);
  744. String name = bd->name.string;
  745. GB_ASSERT(name == "location");
  746. String procedure = p->entity->token.string;
  747. TokenPos pos = ast_token(ce->proc).pos;
  748. if (ce->args.count > 0) {
  749. Ast *ident = unselector_expr(ce->args[0]);
  750. GB_ASSERT(ident->kind == Ast_Ident);
  751. Entity *e = entity_of_node(ident);
  752. GB_ASSERT(e != nullptr);
  753. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  754. procedure = e->parent_proc_decl->entity->token.string;
  755. } else {
  756. procedure = str_lit("");
  757. }
  758. pos = e->token.pos;
  759. }
  760. return lb_emit_source_code_location(p, procedure, pos);
  761. }
  762. case BuiltinProc_type_info_of: {
  763. Ast *arg = ce->args[0];
  764. TypeAndValue tav = type_and_value_of_expr(arg);
  765. if (tav.mode == Addressing_Type) {
  766. Type *t = default_type(type_of_expr(arg));
  767. return lb_type_info(p->module, t);
  768. }
  769. GB_ASSERT(is_type_typeid(tav.type));
  770. auto args = array_make<lbValue>(permanent_allocator(), 1);
  771. args[0] = lb_build_expr(p, arg);
  772. return lb_emit_runtime_call(p, "__type_info_of", args);
  773. }
  774. case BuiltinProc_typeid_of: {
  775. Ast *arg = ce->args[0];
  776. TypeAndValue tav = type_and_value_of_expr(arg);
  777. GB_ASSERT(tav.mode == Addressing_Type);
  778. Type *t = default_type(type_of_expr(arg));
  779. return lb_typeid(p->module, t);
  780. }
  781. case BuiltinProc_len: {
  782. lbValue v = lb_build_expr(p, ce->args[0]);
  783. Type *t = base_type(v.type);
  784. if (is_type_pointer(t)) {
  785. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  786. v = lb_emit_load(p, v);
  787. t = type_deref(t);
  788. }
  789. if (is_type_cstring(t)) {
  790. return lb_cstring_len(p, v);
  791. } else if (is_type_string(t)) {
  792. return lb_string_len(p, v);
  793. } else if (is_type_array(t)) {
  794. GB_PANIC("Array lengths are constant");
  795. } else if (is_type_slice(t)) {
  796. return lb_slice_len(p, v);
  797. } else if (is_type_dynamic_array(t)) {
  798. return lb_dynamic_array_len(p, v);
  799. } else if (is_type_map(t)) {
  800. return lb_map_len(p, v);
  801. } else if (is_type_soa_struct(t)) {
  802. return lb_soa_struct_len(p, v);
  803. }
  804. GB_PANIC("Unreachable");
  805. break;
  806. }
  807. case BuiltinProc_cap: {
  808. lbValue v = lb_build_expr(p, ce->args[0]);
  809. Type *t = base_type(v.type);
  810. if (is_type_pointer(t)) {
  811. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  812. v = lb_emit_load(p, v);
  813. t = type_deref(t);
  814. }
  815. if (is_type_string(t)) {
  816. GB_PANIC("Unreachable");
  817. } else if (is_type_array(t)) {
  818. GB_PANIC("Array lengths are constant");
  819. } else if (is_type_slice(t)) {
  820. return lb_slice_len(p, v);
  821. } else if (is_type_dynamic_array(t)) {
  822. return lb_dynamic_array_cap(p, v);
  823. } else if (is_type_map(t)) {
  824. return lb_map_cap(p, v);
  825. } else if (is_type_soa_struct(t)) {
  826. return lb_soa_struct_cap(p, v);
  827. }
  828. GB_PANIC("Unreachable");
  829. break;
  830. }
  831. case BuiltinProc_swizzle: {
  832. isize index_count = ce->args.count-1;
  833. if (is_type_simd_vector(tv.type)) {
  834. lbValue vec = lb_build_expr(p, ce->args[0]);
  835. if (index_count == 0) {
  836. return vec;
  837. }
  838. unsigned mask_len = cast(unsigned)index_count;
  839. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  840. for (isize i = 1; i < ce->args.count; i++) {
  841. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  842. GB_ASSERT(is_type_integer(tv.type));
  843. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  844. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  845. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  846. }
  847. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  848. LLVMValueRef v1 = vec.value;
  849. LLVMValueRef v2 = vec.value;
  850. lbValue res = {};
  851. res.type = tv.type;
  852. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  853. return res;
  854. }
  855. lbAddr addr = lb_build_array_swizzle_addr(p, ce, tv);
  856. return lb_addr_load(p, addr);
  857. }
  858. case BuiltinProc_complex: {
  859. lbValue real = lb_build_expr(p, ce->args[0]);
  860. lbValue imag = lb_build_expr(p, ce->args[1]);
  861. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  862. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  863. Type *ft = base_complex_elem_type(tv.type);
  864. real = lb_emit_conv(p, real, ft);
  865. imag = lb_emit_conv(p, imag, ft);
  866. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  867. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  868. return lb_emit_load(p, dst);
  869. }
  870. case BuiltinProc_quaternion: {
  871. lbValue real = lb_build_expr(p, ce->args[0]);
  872. lbValue imag = lb_build_expr(p, ce->args[1]);
  873. lbValue jmag = lb_build_expr(p, ce->args[2]);
  874. lbValue kmag = lb_build_expr(p, ce->args[3]);
  875. // @QuaternionLayout
  876. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  877. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  878. Type *ft = base_complex_elem_type(tv.type);
  879. real = lb_emit_conv(p, real, ft);
  880. imag = lb_emit_conv(p, imag, ft);
  881. jmag = lb_emit_conv(p, jmag, ft);
  882. kmag = lb_emit_conv(p, kmag, ft);
  883. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  884. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  885. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  886. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  887. return lb_emit_load(p, dst);
  888. }
  889. case BuiltinProc_real: {
  890. lbValue val = lb_build_expr(p, ce->args[0]);
  891. if (is_type_complex(val.type)) {
  892. lbValue real = lb_emit_struct_ev(p, val, 0);
  893. return lb_emit_conv(p, real, tv.type);
  894. } else if (is_type_quaternion(val.type)) {
  895. // @QuaternionLayout
  896. lbValue real = lb_emit_struct_ev(p, val, 3);
  897. return lb_emit_conv(p, real, tv.type);
  898. }
  899. GB_PANIC("invalid type for real");
  900. return {};
  901. }
  902. case BuiltinProc_imag: {
  903. lbValue val = lb_build_expr(p, ce->args[0]);
  904. if (is_type_complex(val.type)) {
  905. lbValue imag = lb_emit_struct_ev(p, val, 1);
  906. return lb_emit_conv(p, imag, tv.type);
  907. } else if (is_type_quaternion(val.type)) {
  908. // @QuaternionLayout
  909. lbValue imag = lb_emit_struct_ev(p, val, 0);
  910. return lb_emit_conv(p, imag, tv.type);
  911. }
  912. GB_PANIC("invalid type for imag");
  913. return {};
  914. }
  915. case BuiltinProc_jmag: {
  916. lbValue val = lb_build_expr(p, ce->args[0]);
  917. if (is_type_quaternion(val.type)) {
  918. // @QuaternionLayout
  919. lbValue imag = lb_emit_struct_ev(p, val, 1);
  920. return lb_emit_conv(p, imag, tv.type);
  921. }
  922. GB_PANIC("invalid type for jmag");
  923. return {};
  924. }
  925. case BuiltinProc_kmag: {
  926. lbValue val = lb_build_expr(p, ce->args[0]);
  927. if (is_type_quaternion(val.type)) {
  928. // @QuaternionLayout
  929. lbValue imag = lb_emit_struct_ev(p, val, 2);
  930. return lb_emit_conv(p, imag, tv.type);
  931. }
  932. GB_PANIC("invalid type for kmag");
  933. return {};
  934. }
  935. case BuiltinProc_conj: {
  936. lbValue val = lb_build_expr(p, ce->args[0]);
  937. lbValue res = {};
  938. Type *t = val.type;
  939. if (is_type_complex(t)) {
  940. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  941. lbValue real = lb_emit_struct_ev(p, val, 0);
  942. lbValue imag = lb_emit_struct_ev(p, val, 1);
  943. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  944. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  945. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  946. } else if (is_type_quaternion(t)) {
  947. // @QuaternionLayout
  948. res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  949. lbValue real = lb_emit_struct_ev(p, val, 3);
  950. lbValue imag = lb_emit_struct_ev(p, val, 0);
  951. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  952. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  953. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  954. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  955. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  956. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  957. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  958. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  959. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  960. }
  961. return lb_emit_load(p, res);
  962. }
  963. case BuiltinProc_expand_to_tuple: {
  964. lbValue val = lb_build_expr(p, ce->args[0]);
  965. Type *t = base_type(val.type);
  966. if (!is_type_tuple(tv.type)) {
  967. if (t->kind == Type_Struct) {
  968. GB_ASSERT(t->Struct.fields.count == 1);
  969. return lb_emit_struct_ev(p, val, 0);
  970. } else if (t->kind == Type_Array) {
  971. GB_ASSERT(t->Array.count == 1);
  972. return lb_emit_array_epi(p, val, 0);
  973. } else {
  974. GB_PANIC("Unknown type of expand_to_tuple");
  975. }
  976. }
  977. GB_ASSERT(is_type_tuple(tv.type));
  978. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  979. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  980. if (t->kind == Type_Struct) {
  981. for_array(src_index, t->Struct.fields) {
  982. Entity *field = t->Struct.fields[src_index];
  983. i32 field_index = field->Variable.field_index;
  984. lbValue f = lb_emit_struct_ev(p, val, field_index);
  985. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  986. lb_emit_store(p, ep, f);
  987. }
  988. } else if (is_type_array_like(t)) {
  989. // TODO(bill): Clean-up this code
  990. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  991. i32 n = cast(i32)get_array_type_count(t);
  992. for (i32 i = 0; i < n; i++) {
  993. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  994. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  995. lb_emit_store(p, ep, f);
  996. }
  997. } else {
  998. GB_PANIC("Unknown type of expand_to_tuple");
  999. }
  1000. return lb_emit_load(p, tuple);
  1001. }
  1002. case BuiltinProc_min: {
  1003. Type *t = type_of_expr(expr);
  1004. if (ce->args.count == 2) {
  1005. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1006. } else {
  1007. lbValue x = lb_build_expr(p, ce->args[0]);
  1008. for (isize i = 1; i < ce->args.count; i++) {
  1009. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  1010. }
  1011. return x;
  1012. }
  1013. }
  1014. case BuiltinProc_max: {
  1015. Type *t = type_of_expr(expr);
  1016. if (ce->args.count == 2) {
  1017. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1018. } else {
  1019. lbValue x = lb_build_expr(p, ce->args[0]);
  1020. for (isize i = 1; i < ce->args.count; i++) {
  1021. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  1022. }
  1023. return x;
  1024. }
  1025. }
  1026. case BuiltinProc_abs: {
  1027. lbValue x = lb_build_expr(p, ce->args[0]);
  1028. Type *t = x.type;
  1029. if (is_type_unsigned(t)) {
  1030. return x;
  1031. }
  1032. if (is_type_quaternion(t)) {
  1033. i64 sz = 8*type_size_of(t);
  1034. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1035. args[0] = x;
  1036. switch (sz) {
  1037. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  1038. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  1039. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  1040. }
  1041. GB_PANIC("Unknown complex type");
  1042. } else if (is_type_complex(t)) {
  1043. i64 sz = 8*type_size_of(t);
  1044. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1045. args[0] = x;
  1046. switch (sz) {
  1047. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  1048. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  1049. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  1050. }
  1051. GB_PANIC("Unknown complex type");
  1052. }
  1053. lbValue zero = lb_const_nil(p->module, t);
  1054. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  1055. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  1056. return lb_emit_select(p, cond, neg, x);
  1057. }
  1058. case BuiltinProc_clamp:
  1059. return lb_emit_clamp(p, type_of_expr(expr),
  1060. lb_build_expr(p, ce->args[0]),
  1061. lb_build_expr(p, ce->args[1]),
  1062. lb_build_expr(p, ce->args[2]));
  1063. case BuiltinProc_soa_zip:
  1064. return lb_soa_zip(p, ce, tv);
  1065. case BuiltinProc_soa_unzip:
  1066. return lb_soa_unzip(p, ce, tv);
  1067. // "Intrinsics"
  1068. case BuiltinProc_alloca:
  1069. {
  1070. lbValue sz = lb_build_expr(p, ce->args[0]);
  1071. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  1072. lbValue res = {};
  1073. res.type = t_u8_ptr;
  1074. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  1075. LLVMSetAlignment(res.value, cast(unsigned)al);
  1076. return res;
  1077. }
  1078. case BuiltinProc_cpu_relax:
  1079. if (build_context.metrics.arch == TargetArch_386 ||
  1080. build_context.metrics.arch == TargetArch_amd64) {
  1081. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1082. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  1083. cast(char *)"pause", 5,
  1084. cast(char *)"", 0,
  1085. /*HasSideEffects*/true, /*IsAlignStack*/false,
  1086. LLVMInlineAsmDialectATT
  1087. );
  1088. GB_ASSERT(the_asm != nullptr);
  1089. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1090. } else if (build_context.metrics.arch == TargetArch_arm64) {
  1091. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1092. LLVMValueRef the_asm = LLVMGetInlineAsm(func_type,
  1093. cast(char *)"yield", 5,
  1094. cast(char *)"", 0,
  1095. /*HasSideEffects*/true, /*IsAlignStack*/false,
  1096. LLVMInlineAsmDialectATT
  1097. );
  1098. GB_ASSERT(the_asm != nullptr);
  1099. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1100. }
  1101. return {};
  1102. case BuiltinProc_debug_trap:
  1103. case BuiltinProc_trap:
  1104. {
  1105. char const *name = nullptr;
  1106. switch (id) {
  1107. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  1108. case BuiltinProc_trap: name = "llvm.trap"; break;
  1109. }
  1110. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1111. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  1112. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  1113. LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  1114. if (id == BuiltinProc_trap) {
  1115. LLVMBuildUnreachable(p->builder);
  1116. }
  1117. return {};
  1118. }
  1119. case BuiltinProc_read_cycle_counter:
  1120. {
  1121. char const *name = "llvm.readcyclecounter";
  1122. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1123. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  1124. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, nullptr, 0);
  1125. lbValue res = {};
  1126. res.value = LLVMBuildCall(p->builder, ip, nullptr, 0, "");
  1127. res.type = tv.type;
  1128. return res;
  1129. }
  1130. case BuiltinProc_count_trailing_zeros:
  1131. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1132. case BuiltinProc_count_leading_zeros:
  1133. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1134. case BuiltinProc_count_ones:
  1135. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  1136. case BuiltinProc_count_zeros:
  1137. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1138. case BuiltinProc_reverse_bits:
  1139. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  1140. case BuiltinProc_byte_swap:
  1141. {
  1142. lbValue x = lb_build_expr(p, ce->args[0]);
  1143. x = lb_emit_conv(p, x, tv.type);
  1144. return lb_emit_byte_swap(p, x, tv.type);
  1145. }
  1146. case BuiltinProc_overflow_add:
  1147. case BuiltinProc_overflow_sub:
  1148. case BuiltinProc_overflow_mul:
  1149. {
  1150. Type *main_type = tv.type;
  1151. Type *type = main_type;
  1152. if (is_type_tuple(main_type)) {
  1153. type = main_type->Tuple.variables[0]->type;
  1154. }
  1155. lbValue x = lb_build_expr(p, ce->args[0]);
  1156. lbValue y = lb_build_expr(p, ce->args[1]);
  1157. x = lb_emit_conv(p, x, type);
  1158. y = lb_emit_conv(p, y, type);
  1159. char const *name = nullptr;
  1160. if (is_type_unsigned(type)) {
  1161. switch (id) {
  1162. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  1163. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  1164. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  1165. }
  1166. } else {
  1167. switch (id) {
  1168. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  1169. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  1170. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  1171. }
  1172. }
  1173. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1174. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1175. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1176. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1177. LLVMValueRef args[2] = {};
  1178. args[0] = x.value;
  1179. args[1] = y.value;
  1180. lbValue res = {};
  1181. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1182. if (is_type_tuple(main_type)) {
  1183. Type *res_type = nullptr;
  1184. gbAllocator a = permanent_allocator();
  1185. res_type = alloc_type_tuple();
  1186. slice_init(&res_type->Tuple.variables, a, 2);
  1187. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  1188. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  1189. res.type = res_type;
  1190. } else {
  1191. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  1192. res.type = type;
  1193. }
  1194. return res;
  1195. }
  1196. case BuiltinProc_sqrt:
  1197. {
  1198. Type *type = tv.type;
  1199. lbValue x = lb_build_expr(p, ce->args[0]);
  1200. x = lb_emit_conv(p, x, type);
  1201. char const *name = "llvm.sqrt";
  1202. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1203. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1204. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1205. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1206. LLVMValueRef args[1] = {};
  1207. args[0] = x.value;
  1208. lbValue res = {};
  1209. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1210. res.type = type;
  1211. return res;
  1212. }
  1213. case BuiltinProc_mem_copy:
  1214. case BuiltinProc_mem_copy_non_overlapping:
  1215. {
  1216. lbValue dst = lb_build_expr(p, ce->args[0]);
  1217. lbValue src = lb_build_expr(p, ce->args[1]);
  1218. lbValue len = lb_build_expr(p, ce->args[2]);
  1219. dst = lb_emit_conv(p, dst, t_rawptr);
  1220. src = lb_emit_conv(p, src, t_rawptr);
  1221. len = lb_emit_conv(p, len, t_int);
  1222. bool is_inlinable = false;
  1223. if (ce->args[2]->tav.mode == Addressing_Constant) {
  1224. ExactValue ev = exact_value_to_integer(ce->args[2]->tav.value);
  1225. i64 const_len = exact_value_to_i64(ev);
  1226. // TODO(bill): Determine when it is better to do the `*.inline` versions
  1227. if (const_len <= 4*build_context.word_size) {
  1228. is_inlinable = true;
  1229. }
  1230. }
  1231. char const *name = nullptr;
  1232. switch (id) {
  1233. case BuiltinProc_mem_copy:
  1234. if (is_inlinable) {
  1235. name = "llvm.memmove.inline";
  1236. } else {
  1237. name = "llvm.memmove";
  1238. }
  1239. break;
  1240. case BuiltinProc_mem_copy_non_overlapping:
  1241. if (is_inlinable) {
  1242. name = "llvm.memcpy.line";
  1243. } else {
  1244. name = "llvm.memcpy";
  1245. }
  1246. break;
  1247. }
  1248. LLVMTypeRef types[3] = {
  1249. lb_type(p->module, t_rawptr),
  1250. lb_type(p->module, t_rawptr),
  1251. lb_type(p->module, t_int)
  1252. };
  1253. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1254. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s.%s.%s", name, LLVMPrintTypeToString(types[0]), LLVMPrintTypeToString(types[1]), LLVMPrintTypeToString(types[2]));
  1255. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1256. LLVMValueRef args[4] = {};
  1257. args[0] = dst.value;
  1258. args[1] = src.value;
  1259. args[2] = len.value;
  1260. args[3] = LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, false); // is_volatile parameter
  1261. LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1262. return {};
  1263. }
  1264. case BuiltinProc_mem_zero:
  1265. {
  1266. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1267. lbValue len = lb_build_expr(p, ce->args[1]);
  1268. ptr = lb_emit_conv(p, ptr, t_rawptr);
  1269. len = lb_emit_conv(p, len, t_int);
  1270. unsigned alignment = 1;
  1271. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment);
  1272. return {};
  1273. }
  1274. case BuiltinProc_ptr_offset:
  1275. {
  1276. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1277. lbValue len = lb_build_expr(p, ce->args[1]);
  1278. len = lb_emit_conv(p, len, t_int);
  1279. LLVMValueRef indices[1] = {
  1280. len.value,
  1281. };
  1282. lbValue res = {};
  1283. res.type = tv.type;
  1284. res.value = LLVMBuildGEP(p->builder, ptr.value, indices, gb_count_of(indices), "");
  1285. return res;
  1286. }
  1287. case BuiltinProc_ptr_sub:
  1288. {
  1289. lbValue ptr0 = lb_build_expr(p, ce->args[0]);
  1290. lbValue ptr1 = lb_build_expr(p, ce->args[1]);
  1291. LLVMTypeRef type_int = lb_type(p->module, t_int);
  1292. LLVMValueRef diff = LLVMBuildPtrDiff(p->builder, ptr0.value, ptr1.value, "");
  1293. diff = LLVMBuildIntCast2(p->builder, diff, type_int, /*signed*/true, "");
  1294. lbValue res = {};
  1295. res.type = t_int;
  1296. res.value = diff;
  1297. return res;
  1298. }
  1299. case BuiltinProc_atomic_fence:
  1300. LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, "");
  1301. return {};
  1302. case BuiltinProc_atomic_fence_acq:
  1303. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, "");
  1304. return {};
  1305. case BuiltinProc_atomic_fence_rel:
  1306. LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, "");
  1307. return {};
  1308. case BuiltinProc_atomic_fence_acqrel:
  1309. LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, "");
  1310. return {};
  1311. case BuiltinProc_volatile_store:
  1312. case BuiltinProc_atomic_store:
  1313. case BuiltinProc_atomic_store_rel:
  1314. case BuiltinProc_atomic_store_relaxed:
  1315. case BuiltinProc_atomic_store_unordered: {
  1316. lbValue dst = lb_build_expr(p, ce->args[0]);
  1317. lbValue val = lb_build_expr(p, ce->args[1]);
  1318. val = lb_emit_conv(p, val, type_deref(dst.type));
  1319. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  1320. switch (id) {
  1321. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  1322. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  1323. case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break;
  1324. case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  1325. case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  1326. }
  1327. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  1328. return {};
  1329. }
  1330. case BuiltinProc_volatile_load:
  1331. case BuiltinProc_atomic_load:
  1332. case BuiltinProc_atomic_load_acq:
  1333. case BuiltinProc_atomic_load_relaxed:
  1334. case BuiltinProc_atomic_load_unordered: {
  1335. lbValue dst = lb_build_expr(p, ce->args[0]);
  1336. LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, "");
  1337. switch (id) {
  1338. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  1339. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  1340. case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break;
  1341. case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break;
  1342. case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break;
  1343. }
  1344. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  1345. lbValue res = {};
  1346. res.value = instr;
  1347. res.type = type_deref(dst.type);
  1348. return res;
  1349. }
  1350. case BuiltinProc_atomic_add:
  1351. case BuiltinProc_atomic_add_acq:
  1352. case BuiltinProc_atomic_add_rel:
  1353. case BuiltinProc_atomic_add_acqrel:
  1354. case BuiltinProc_atomic_add_relaxed:
  1355. case BuiltinProc_atomic_sub:
  1356. case BuiltinProc_atomic_sub_acq:
  1357. case BuiltinProc_atomic_sub_rel:
  1358. case BuiltinProc_atomic_sub_acqrel:
  1359. case BuiltinProc_atomic_sub_relaxed:
  1360. case BuiltinProc_atomic_and:
  1361. case BuiltinProc_atomic_and_acq:
  1362. case BuiltinProc_atomic_and_rel:
  1363. case BuiltinProc_atomic_and_acqrel:
  1364. case BuiltinProc_atomic_and_relaxed:
  1365. case BuiltinProc_atomic_nand:
  1366. case BuiltinProc_atomic_nand_acq:
  1367. case BuiltinProc_atomic_nand_rel:
  1368. case BuiltinProc_atomic_nand_acqrel:
  1369. case BuiltinProc_atomic_nand_relaxed:
  1370. case BuiltinProc_atomic_or:
  1371. case BuiltinProc_atomic_or_acq:
  1372. case BuiltinProc_atomic_or_rel:
  1373. case BuiltinProc_atomic_or_acqrel:
  1374. case BuiltinProc_atomic_or_relaxed:
  1375. case BuiltinProc_atomic_xor:
  1376. case BuiltinProc_atomic_xor_acq:
  1377. case BuiltinProc_atomic_xor_rel:
  1378. case BuiltinProc_atomic_xor_acqrel:
  1379. case BuiltinProc_atomic_xor_relaxed:
  1380. case BuiltinProc_atomic_xchg:
  1381. case BuiltinProc_atomic_xchg_acq:
  1382. case BuiltinProc_atomic_xchg_rel:
  1383. case BuiltinProc_atomic_xchg_acqrel:
  1384. case BuiltinProc_atomic_xchg_relaxed: {
  1385. lbValue dst = lb_build_expr(p, ce->args[0]);
  1386. lbValue val = lb_build_expr(p, ce->args[1]);
  1387. val = lb_emit_conv(p, val, type_deref(dst.type));
  1388. LLVMAtomicRMWBinOp op = {};
  1389. LLVMAtomicOrdering ordering = {};
  1390. switch (id) {
  1391. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1392. case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break;
  1393. case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break;
  1394. case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  1395. case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break;
  1396. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1397. case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break;
  1398. case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break;
  1399. case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break;
  1400. case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break;
  1401. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1402. case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break;
  1403. case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break;
  1404. case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break;
  1405. case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break;
  1406. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1407. case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break;
  1408. case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break;
  1409. case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break;
  1410. case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break;
  1411. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1412. case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break;
  1413. case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break;
  1414. case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break;
  1415. case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break;
  1416. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1417. case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break;
  1418. case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break;
  1419. case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break;
  1420. case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break;
  1421. case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  1422. case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break;
  1423. case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break;
  1424. case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break;
  1425. case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break;
  1426. }
  1427. lbValue res = {};
  1428. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  1429. res.type = tv.type;
  1430. return res;
  1431. }
  1432. case BuiltinProc_atomic_cxchg:
  1433. case BuiltinProc_atomic_cxchg_acq:
  1434. case BuiltinProc_atomic_cxchg_rel:
  1435. case BuiltinProc_atomic_cxchg_acqrel:
  1436. case BuiltinProc_atomic_cxchg_relaxed:
  1437. case BuiltinProc_atomic_cxchg_failrelaxed:
  1438. case BuiltinProc_atomic_cxchg_failacq:
  1439. case BuiltinProc_atomic_cxchg_acq_failrelaxed:
  1440. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed:
  1441. case BuiltinProc_atomic_cxchgweak:
  1442. case BuiltinProc_atomic_cxchgweak_acq:
  1443. case BuiltinProc_atomic_cxchgweak_rel:
  1444. case BuiltinProc_atomic_cxchgweak_acqrel:
  1445. case BuiltinProc_atomic_cxchgweak_relaxed:
  1446. case BuiltinProc_atomic_cxchgweak_failrelaxed:
  1447. case BuiltinProc_atomic_cxchgweak_failacq:
  1448. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed:
  1449. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: {
  1450. lbValue address = lb_build_expr(p, ce->args[0]);
  1451. Type *elem = type_deref(address.type);
  1452. lbValue old_value = lb_build_expr(p, ce->args[1]);
  1453. lbValue new_value = lb_build_expr(p, ce->args[2]);
  1454. old_value = lb_emit_conv(p, old_value, elem);
  1455. new_value = lb_emit_conv(p, new_value, elem);
  1456. LLVMAtomicOrdering success_ordering = {};
  1457. LLVMAtomicOrdering failure_ordering = {};
  1458. LLVMBool weak = false;
  1459. switch (id) {
  1460. case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  1461. case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  1462. case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  1463. case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  1464. case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  1465. case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  1466. case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break;
  1467. case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  1468. case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break;
  1469. case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  1470. case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  1471. case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  1472. case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  1473. case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  1474. case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  1475. case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break;
  1476. case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  1477. case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break;
  1478. }
  1479. // TODO(bill): Figure out how to make it weak
  1480. LLVMBool single_threaded = weak;
  1481. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  1482. p->builder, address.value,
  1483. old_value.value, new_value.value,
  1484. success_ordering,
  1485. failure_ordering,
  1486. single_threaded
  1487. );
  1488. if (tv.type->kind == Type_Tuple) {
  1489. Type *fix_typed = alloc_type_tuple();
  1490. slice_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  1491. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  1492. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  1493. lbValue res = {};
  1494. res.value = value;
  1495. res.type = fix_typed;
  1496. return res;
  1497. } else {
  1498. lbValue res = {};
  1499. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  1500. res.type = tv.type;
  1501. return res;
  1502. }
  1503. }
  1504. case BuiltinProc_type_equal_proc:
  1505. return lb_get_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  1506. case BuiltinProc_type_hasher_proc:
  1507. return lb_get_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  1508. case BuiltinProc_fixed_point_mul:
  1509. case BuiltinProc_fixed_point_div:
  1510. case BuiltinProc_fixed_point_mul_sat:
  1511. case BuiltinProc_fixed_point_div_sat:
  1512. {
  1513. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  1514. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  1515. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  1516. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  1517. char const *name = nullptr;
  1518. if (is_type_unsigned(tv.type)) {
  1519. switch (id) {
  1520. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  1521. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  1522. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  1523. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  1524. }
  1525. } else {
  1526. switch (id) {
  1527. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  1528. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  1529. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  1530. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  1531. }
  1532. }
  1533. GB_ASSERT(name != nullptr);
  1534. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  1535. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1536. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1537. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1538. lbValue res = {};
  1539. LLVMValueRef args[3] = {};
  1540. args[0] = x.value;
  1541. args[1] = y.value;
  1542. args[2] = scale.value;
  1543. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1544. res.type = platform_type;
  1545. return lb_emit_conv(p, res, tv.type);
  1546. }
  1547. case BuiltinProc_expect:
  1548. {
  1549. Type *t = default_type(tv.type);
  1550. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  1551. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  1552. char const *name = "llvm.expect";
  1553. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  1554. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1555. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1556. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1557. lbValue res = {};
  1558. LLVMValueRef args[2] = {};
  1559. args[0] = x.value;
  1560. args[1] = y.value;
  1561. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1562. res.type = t;
  1563. return lb_emit_conv(p, res, t);
  1564. }
  1565. case BuiltinProc_prefetch_read_instruction:
  1566. case BuiltinProc_prefetch_read_data:
  1567. case BuiltinProc_prefetch_write_instruction:
  1568. case BuiltinProc_prefetch_write_data:
  1569. {
  1570. lbValue ptr = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_rawptr);
  1571. unsigned long long locality = cast(unsigned long long)exact_value_to_i64(ce->args[1]->tav.value);
  1572. unsigned long long rw = 0;
  1573. unsigned long long cache = 0;
  1574. switch (id) {
  1575. case BuiltinProc_prefetch_read_instruction:
  1576. rw = 0;
  1577. cache = 0;
  1578. break;
  1579. case BuiltinProc_prefetch_read_data:
  1580. rw = 0;
  1581. cache = 1;
  1582. break;
  1583. case BuiltinProc_prefetch_write_instruction:
  1584. rw = 1;
  1585. cache = 0;
  1586. break;
  1587. case BuiltinProc_prefetch_write_data:
  1588. rw = 1;
  1589. cache = 1;
  1590. break;
  1591. }
  1592. char const *name = "llvm.prefetch";
  1593. LLVMTypeRef types[1] = {lb_type(p->module, t_rawptr)};
  1594. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  1595. GB_ASSERT_MSG(id != 0, "Unable to find %s.%s", name, LLVMPrintTypeToString(types[0]));
  1596. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types));
  1597. LLVMTypeRef llvm_i32 = lb_type(p->module, t_i32);
  1598. LLVMValueRef args[4] = {};
  1599. args[0] = ptr.value;
  1600. args[1] = LLVMConstInt(llvm_i32, rw, false);
  1601. args[2] = LLVMConstInt(llvm_i32, locality, false);
  1602. args[3] = LLVMConstInt(llvm_i32, cache, false);
  1603. lbValue res = {};
  1604. res.value = LLVMBuildCall(p->builder, ip, args, gb_count_of(args), "");
  1605. res.type = nullptr;
  1606. return res;
  1607. }
  1608. case BuiltinProc_syscall:
  1609. {
  1610. unsigned arg_count = cast(unsigned)ce->args.count;
  1611. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  1612. for_array(i, ce->args) {
  1613. lbValue arg = lb_build_expr(p, ce->args[i]);
  1614. arg = lb_emit_conv(p, arg, t_uintptr);
  1615. args[i] = arg.value;
  1616. }
  1617. LLVMTypeRef llvm_uintptr = lb_type(p->module, t_uintptr);
  1618. LLVMTypeRef *llvm_arg_types = gb_alloc_array(permanent_allocator(), LLVMTypeRef, arg_count);
  1619. for (unsigned i = 0; i < arg_count; i++) {
  1620. llvm_arg_types[i] = llvm_uintptr;
  1621. }
  1622. LLVMTypeRef func_type = LLVMFunctionType(llvm_uintptr, llvm_arg_types, arg_count, false);
  1623. LLVMValueRef inline_asm = nullptr;
  1624. switch (build_context.metrics.arch) {
  1625. case TargetArch_amd64:
  1626. {
  1627. GB_ASSERT(arg_count <= 7);
  1628. char asm_string[] = "syscall";
  1629. gbString constraints = gb_string_make(heap_allocator(), "={rax}");
  1630. for (unsigned i = 0; i < arg_count; i++) {
  1631. constraints = gb_string_appendc(constraints, ",{");
  1632. static char const *regs[] = {
  1633. "rax",
  1634. "rdi",
  1635. "rsi",
  1636. "rdx",
  1637. "r10",
  1638. "r8",
  1639. "r9"
  1640. };
  1641. constraints = gb_string_appendc(constraints, regs[i]);
  1642. constraints = gb_string_appendc(constraints, "}");
  1643. }
  1644. size_t asm_string_size = gb_strlen(asm_string);
  1645. size_t constraints_size = gb_string_length(constraints);
  1646. inline_asm = LLVMGetInlineAsm(func_type, asm_string, asm_string_size, constraints, constraints_size, true, false, LLVMInlineAsmDialectATT);
  1647. }
  1648. break;
  1649. case TargetArch_386:
  1650. {
  1651. GB_ASSERT(arg_count <= 7);
  1652. char asm_string_default[] = "int $0x80";
  1653. char *asm_string = asm_string_default;
  1654. gbString constraints = gb_string_make(heap_allocator(), "={eax}");
  1655. for (unsigned i = 0; i < gb_min(arg_count, 6); i++) {
  1656. constraints = gb_string_appendc(constraints, ",{");
  1657. static char const *regs[] = {
  1658. "eax",
  1659. "ebx",
  1660. "ecx",
  1661. "edx",
  1662. "esi",
  1663. "edi",
  1664. };
  1665. constraints = gb_string_appendc(constraints, regs[i]);
  1666. constraints = gb_string_appendc(constraints, "}");
  1667. }
  1668. if (arg_count == 7) {
  1669. char asm_string7[] = "push %[arg6]\npush %%ebp\nmov 4(%%esp), %%ebp\nint $0x80\npop %%ebp\nadd $4, %%esp";
  1670. asm_string = asm_string7;
  1671. constraints = gb_string_appendc(constraints, ",rm");
  1672. }
  1673. size_t asm_string_size = gb_strlen(asm_string);
  1674. size_t constraints_size = gb_string_length(constraints);
  1675. inline_asm = LLVMGetInlineAsm(func_type, asm_string, asm_string_size, constraints, constraints_size, true, false, LLVMInlineAsmDialectATT);
  1676. }
  1677. break;
  1678. case TargetArch_arm64:
  1679. {
  1680. GB_ASSERT(arg_count <= 7);
  1681. char asm_string[] = "svc #0";
  1682. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  1683. for (unsigned i = 0; i < arg_count; i++) {
  1684. constraints = gb_string_appendc(constraints, ",{");
  1685. static char const *regs[] = {
  1686. "x8",
  1687. "x0",
  1688. "x1",
  1689. "x2",
  1690. "x3",
  1691. "x4",
  1692. "x5",
  1693. };
  1694. constraints = gb_string_appendc(constraints, regs[i]);
  1695. constraints = gb_string_appendc(constraints, "}");
  1696. }
  1697. size_t asm_string_size = gb_strlen(asm_string);
  1698. size_t constraints_size = gb_string_length(constraints);
  1699. inline_asm = LLVMGetInlineAsm(func_type, asm_string, asm_string_size, constraints, constraints_size, true, false, LLVMInlineAsmDialectATT);
  1700. }
  1701. break;
  1702. default:
  1703. GB_PANIC("Unsupported platform");
  1704. }
  1705. lbValue res = {};
  1706. res.value = LLVMBuildCall2(p->builder, func_type, inline_asm, args, arg_count, "");
  1707. res.type = t_uintptr;
  1708. return res;
  1709. }
  1710. }
  1711. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  1712. return {};
  1713. }
  1714. lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  1715. switch (param_value.kind) {
  1716. case ParameterValue_Constant:
  1717. if (is_type_constant_type(parameter_type)) {
  1718. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  1719. return res;
  1720. } else {
  1721. ExactValue ev = param_value.value;
  1722. lbValue arg = {};
  1723. Type *type = type_of_expr(param_value.original_ast_expr);
  1724. if (type != nullptr) {
  1725. arg = lb_const_value(p->module, type, ev);
  1726. } else {
  1727. arg = lb_const_value(p->module, parameter_type, param_value.value);
  1728. }
  1729. return lb_emit_conv(p, arg, parameter_type);
  1730. }
  1731. case ParameterValue_Nil:
  1732. return lb_const_nil(p->module, parameter_type);
  1733. case ParameterValue_Location:
  1734. {
  1735. String proc_name = {};
  1736. if (p->entity != nullptr) {
  1737. proc_name = p->entity->token.string;
  1738. }
  1739. return lb_emit_source_code_location(p, proc_name, pos);
  1740. }
  1741. case ParameterValue_Value:
  1742. return lb_build_expr(p, param_value.ast_value);
  1743. }
  1744. return lb_const_nil(p->module, parameter_type);
  1745. }
  1746. lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr);
  1747. lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  1748. expr = unparen_expr(expr);
  1749. ast_node(ce, CallExpr, expr);
  1750. if (ce->sce_temp_data) {
  1751. return *(lbValue *)ce->sce_temp_data;
  1752. }
  1753. lbValue res = lb_build_call_expr_internal(p, expr);
  1754. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  1755. GB_ASSERT(is_type_tuple(res.type));
  1756. GB_ASSERT(res.type->Tuple.variables.count == 2);
  1757. return lb_emit_struct_ev(p, res, 0);
  1758. }
  1759. return res;
  1760. }
  1761. lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr) {
  1762. lbModule *m = p->module;
  1763. TypeAndValue tv = type_and_value_of_expr(expr);
  1764. ast_node(ce, CallExpr, expr);
  1765. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  1766. AddressingMode proc_mode = proc_tv.mode;
  1767. if (proc_mode == Addressing_Type) {
  1768. GB_ASSERT(ce->args.count == 1);
  1769. lbValue x = lb_build_expr(p, ce->args[0]);
  1770. lbValue y = lb_emit_conv(p, x, tv.type);
  1771. return y;
  1772. }
  1773. Ast *pexpr = unparen_expr(ce->proc);
  1774. if (proc_mode == Addressing_Builtin) {
  1775. Entity *e = entity_of_node(pexpr);
  1776. BuiltinProcId id = BuiltinProc_Invalid;
  1777. if (e != nullptr) {
  1778. id = cast(BuiltinProcId)e->Builtin.id;
  1779. } else {
  1780. id = BuiltinProc_DIRECTIVE;
  1781. }
  1782. return lb_build_builtin_proc(p, expr, tv, id);
  1783. }
  1784. // NOTE(bill): Regular call
  1785. lbValue value = {};
  1786. Ast *proc_expr = unparen_expr(ce->proc);
  1787. if (proc_expr->tav.mode == Addressing_Constant) {
  1788. ExactValue v = proc_expr->tav.value;
  1789. switch (v.kind) {
  1790. case ExactValue_Integer:
  1791. {
  1792. u64 u = big_int_to_u64(&v.value_integer);
  1793. lbValue x = {};
  1794. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  1795. x.type = t_uintptr;
  1796. x = lb_emit_conv(p, x, t_rawptr);
  1797. value = lb_emit_conv(p, x, proc_expr->tav.type);
  1798. break;
  1799. }
  1800. case ExactValue_Pointer:
  1801. {
  1802. u64 u = cast(u64)v.value_pointer;
  1803. lbValue x = {};
  1804. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  1805. x.type = t_uintptr;
  1806. x = lb_emit_conv(p, x, t_rawptr);
  1807. value = lb_emit_conv(p, x, proc_expr->tav.type);
  1808. break;
  1809. }
  1810. }
  1811. }
  1812. Entity *proc_entity = entity_of_node(proc_expr);
  1813. if (proc_entity != nullptr) {
  1814. if (proc_entity->flags & EntityFlag_Disabled) {
  1815. return {};
  1816. }
  1817. }
  1818. if (value.value == nullptr) {
  1819. value = lb_build_expr(p, proc_expr);
  1820. }
  1821. GB_ASSERT(value.value != nullptr);
  1822. Type *proc_type_ = base_type(value.type);
  1823. GB_ASSERT(proc_type_->kind == Type_Proc);
  1824. TypeProc *pt = &proc_type_->Proc;
  1825. if (is_call_expr_field_value(ce)) {
  1826. auto args = array_make<lbValue>(permanent_allocator(), pt->param_count);
  1827. for_array(arg_index, ce->args) {
  1828. Ast *arg = ce->args[arg_index];
  1829. ast_node(fv, FieldValue, arg);
  1830. GB_ASSERT(fv->field->kind == Ast_Ident);
  1831. String name = fv->field->Ident.token.string;
  1832. isize index = lookup_procedure_parameter(pt, name);
  1833. GB_ASSERT(index >= 0);
  1834. TypeAndValue tav = type_and_value_of_expr(fv->value);
  1835. if (tav.mode == Addressing_Type) {
  1836. args[index] = lb_const_nil(m, tav.type);
  1837. } else {
  1838. args[index] = lb_build_expr(p, fv->value);
  1839. }
  1840. }
  1841. TypeTuple *params = &pt->params->Tuple;
  1842. for (isize i = 0; i < args.count; i++) {
  1843. Entity *e = params->variables[i];
  1844. if (e->kind == Entity_TypeName) {
  1845. args[i] = lb_const_nil(m, e->type);
  1846. } else if (e->kind == Entity_Constant) {
  1847. continue;
  1848. } else {
  1849. GB_ASSERT(e->kind == Entity_Variable);
  1850. if (args[i].value == nullptr) {
  1851. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  1852. } else {
  1853. args[i] = lb_emit_conv(p, args[i], e->type);
  1854. }
  1855. }
  1856. }
  1857. for (isize i = 0; i < args.count; i++) {
  1858. Entity *e = params->variables[i];
  1859. if (args[i].type == nullptr) {
  1860. continue;
  1861. } else if (is_type_untyped_nil(args[i].type)) {
  1862. args[i] = lb_const_nil(m, e->type);
  1863. } else if (is_type_untyped_undef(args[i].type)) {
  1864. args[i] = lb_const_undef(m, e->type);
  1865. }
  1866. }
  1867. return lb_emit_call(p, value, args, ce->inlining, p->copy_elision_hint.ast == expr);
  1868. }
  1869. isize arg_index = 0;
  1870. isize arg_count = 0;
  1871. for_array(i, ce->args) {
  1872. Ast *arg = ce->args[i];
  1873. TypeAndValue tav = type_and_value_of_expr(arg);
  1874. GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s %d", expr_to_string(arg), expr_to_string(expr), tav.mode);
  1875. GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg));
  1876. Type *at = tav.type;
  1877. if (at->kind == Type_Tuple) {
  1878. arg_count += at->Tuple.variables.count;
  1879. } else {
  1880. arg_count++;
  1881. }
  1882. }
  1883. isize param_count = 0;
  1884. if (pt->params) {
  1885. GB_ASSERT(pt->params->kind == Type_Tuple);
  1886. param_count = pt->params->Tuple.variables.count;
  1887. }
  1888. auto args = array_make<lbValue>(permanent_allocator(), cast(isize)gb_max(param_count, arg_count));
  1889. isize variadic_index = pt->variadic_index;
  1890. bool variadic = pt->variadic && variadic_index >= 0;
  1891. bool vari_expand = ce->ellipsis.pos.line != 0;
  1892. bool is_c_vararg = pt->c_vararg;
  1893. String proc_name = {};
  1894. if (p->entity != nullptr) {
  1895. proc_name = p->entity->token.string;
  1896. }
  1897. TokenPos pos = ast_token(ce->proc).pos;
  1898. TypeTuple *param_tuple = nullptr;
  1899. if (pt->params) {
  1900. GB_ASSERT(pt->params->kind == Type_Tuple);
  1901. param_tuple = &pt->params->Tuple;
  1902. }
  1903. for_array(i, ce->args) {
  1904. Ast *arg = ce->args[i];
  1905. TypeAndValue arg_tv = type_and_value_of_expr(arg);
  1906. if (arg_tv.mode == Addressing_Type) {
  1907. args[arg_index++] = lb_const_nil(m, arg_tv.type);
  1908. } else {
  1909. lbValue a = lb_build_expr(p, arg);
  1910. Type *at = a.type;
  1911. if (at->kind == Type_Tuple) {
  1912. for_array(i, at->Tuple.variables) {
  1913. lbValue v = lb_emit_struct_ev(p, a, cast(i32)i);
  1914. args[arg_index++] = v;
  1915. }
  1916. } else {
  1917. args[arg_index++] = a;
  1918. }
  1919. }
  1920. }
  1921. if (param_count > 0) {
  1922. GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count);
  1923. GB_ASSERT(param_count < 1000000);
  1924. if (arg_count < param_count) {
  1925. isize end = cast(isize)param_count;
  1926. if (variadic) {
  1927. end = variadic_index;
  1928. }
  1929. while (arg_index < end) {
  1930. Entity *e = param_tuple->variables[arg_index];
  1931. GB_ASSERT(e->kind == Entity_Variable);
  1932. args[arg_index++] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  1933. }
  1934. }
  1935. if (is_c_vararg) {
  1936. GB_ASSERT(variadic);
  1937. GB_ASSERT(!vari_expand);
  1938. isize i = 0;
  1939. for (; i < variadic_index; i++) {
  1940. Entity *e = param_tuple->variables[i];
  1941. if (e->kind == Entity_Variable) {
  1942. args[i] = lb_emit_conv(p, args[i], e->type);
  1943. }
  1944. }
  1945. Type *variadic_type = param_tuple->variables[i]->type;
  1946. GB_ASSERT(is_type_slice(variadic_type));
  1947. variadic_type = base_type(variadic_type)->Slice.elem;
  1948. if (!is_type_any(variadic_type)) {
  1949. for (; i < arg_count; i++) {
  1950. args[i] = lb_emit_conv(p, args[i], variadic_type);
  1951. }
  1952. } else {
  1953. for (; i < arg_count; i++) {
  1954. args[i] = lb_emit_conv(p, args[i], default_type(args[i].type));
  1955. }
  1956. }
  1957. } else if (variadic) {
  1958. isize i = 0;
  1959. for (; i < variadic_index; i++) {
  1960. Entity *e = param_tuple->variables[i];
  1961. if (e->kind == Entity_Variable) {
  1962. args[i] = lb_emit_conv(p, args[i], e->type);
  1963. }
  1964. }
  1965. if (!vari_expand) {
  1966. Type *variadic_type = param_tuple->variables[i]->type;
  1967. GB_ASSERT(is_type_slice(variadic_type));
  1968. variadic_type = base_type(variadic_type)->Slice.elem;
  1969. for (; i < arg_count; i++) {
  1970. args[i] = lb_emit_conv(p, args[i], variadic_type);
  1971. }
  1972. }
  1973. } else {
  1974. for (isize i = 0; i < param_count; i++) {
  1975. Entity *e = param_tuple->variables[i];
  1976. if (e->kind == Entity_Variable) {
  1977. if (args[i].value == nullptr) {
  1978. continue;
  1979. }
  1980. GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string));
  1981. args[i] = lb_emit_conv(p, args[i], e->type);
  1982. }
  1983. }
  1984. }
  1985. if (variadic && !vari_expand && !is_c_vararg) {
  1986. // variadic call argument generation
  1987. Type *slice_type = param_tuple->variables[variadic_index]->type;
  1988. Type *elem_type = base_type(slice_type)->Slice.elem;
  1989. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  1990. isize slice_len = arg_count+1 - (variadic_index+1);
  1991. if (slice_len > 0) {
  1992. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  1993. for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) {
  1994. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j);
  1995. lb_emit_store(p, addr, args[i]);
  1996. }
  1997. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  1998. lbValue len = lb_const_int(m, t_int, slice_len);
  1999. lb_fill_slice(p, slice, base_elem, len);
  2000. }
  2001. arg_count = param_count;
  2002. args[variadic_index] = lb_addr_load(p, slice);
  2003. }
  2004. }
  2005. if (variadic && variadic_index+1 < param_count) {
  2006. for (isize i = variadic_index+1; i < param_count; i++) {
  2007. Entity *e = param_tuple->variables[i];
  2008. args[i] = lb_handle_param_value(p, e->type, e->Variable.param_value, ast_token(expr).pos);
  2009. }
  2010. }
  2011. isize final_count = param_count;
  2012. if (is_c_vararg) {
  2013. final_count = arg_count;
  2014. }
  2015. if (param_tuple != nullptr) {
  2016. for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) {
  2017. Entity *e = param_tuple->variables[i];
  2018. if (args[i].type == nullptr) {
  2019. continue;
  2020. } else if (is_type_untyped_nil(args[i].type)) {
  2021. args[i] = lb_const_nil(m, e->type);
  2022. } else if (is_type_untyped_undef(args[i].type)) {
  2023. args[i] = lb_const_undef(m, e->type);
  2024. }
  2025. }
  2026. }
  2027. auto call_args = array_slice(args, 0, final_count);
  2028. return lb_emit_call(p, value, call_args, ce->inlining, p->copy_elision_hint.ast == expr);
  2029. }