llvm_backend_proc.cpp 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377
  1. gb_internal LLVMValueRef lb_call_intrinsic(lbProcedure *p, const char *name, LLVMValueRef* args, unsigned arg_count, LLVMTypeRef* types, unsigned type_count) {
  2. unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name));
  3. GB_ASSERT_MSG(id != 0, "Unable to find %s", name);
  4. LLVMValueRef ip = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, type_count);
  5. LLVMTypeRef call_type = LLVMIntrinsicGetType(p->module->ctx, id, types, type_count);
  6. return LLVMBuildCall2(p->builder, call_type, ip, args, arg_count, "");
  7. }
  8. gb_internal void lb_mem_copy_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  9. dst = lb_emit_conv(p, dst, t_rawptr);
  10. src = lb_emit_conv(p, src, t_rawptr);
  11. len = lb_emit_conv(p, len, t_int);
  12. char const *name = "llvm.memmove";
  13. if (LLVMIsConstant(len.value)) {
  14. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  15. if (const_len <= 4*build_context.int_size) {
  16. name = "llvm.memmove.inline";
  17. }
  18. }
  19. LLVMTypeRef types[3] = {
  20. lb_type(p->module, t_rawptr),
  21. lb_type(p->module, t_rawptr),
  22. lb_type(p->module, t_int)
  23. };
  24. LLVMValueRef args[4] = {
  25. dst.value,
  26. src.value,
  27. len.value,
  28. LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile)
  29. };
  30. lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  31. }
  32. gb_internal void lb_mem_copy_non_overlapping(lbProcedure *p, lbValue dst, lbValue src, lbValue len, bool is_volatile) {
  33. dst = lb_emit_conv(p, dst, t_rawptr);
  34. src = lb_emit_conv(p, src, t_rawptr);
  35. len = lb_emit_conv(p, len, t_int);
  36. char const *name = "llvm.memcpy";
  37. if (LLVMIsConstant(len.value)) {
  38. i64 const_len = cast(i64)LLVMConstIntGetSExtValue(len.value);
  39. if (const_len <= 4*build_context.int_size) {
  40. name = "llvm.memcpy.inline";
  41. }
  42. }
  43. LLVMTypeRef types[3] = {
  44. lb_type(p->module, t_rawptr),
  45. lb_type(p->module, t_rawptr),
  46. lb_type(p->module, t_int)
  47. };
  48. LLVMValueRef args[4] = {
  49. dst.value,
  50. src.value,
  51. len.value,
  52. LLVMConstInt(LLVMInt1TypeInContext(p->module->ctx), 0, is_volatile) };
  53. lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  54. }
  55. gb_internal lbProcedure *lb_create_procedure(lbModule *m, Entity *entity, bool ignore_body) {
  56. GB_ASSERT(entity != nullptr);
  57. GB_ASSERT(entity->kind == Entity_Procedure);
  58. if (!entity->Procedure.is_foreign) {
  59. if ((entity->flags & EntityFlag_ProcBodyChecked) == 0) {
  60. GB_PANIC("%.*s :: %s (was parapoly: %d %d)", LIT(entity->token.string), type_to_string(entity->type), is_type_polymorphic(entity->type, true), is_type_polymorphic(entity->type, false));
  61. }
  62. }
  63. String link_name = {};
  64. if (ignore_body) {
  65. lbModule *other_module = lb_module_of_entity(m->gen, entity);
  66. link_name = lb_get_entity_name(other_module, entity);
  67. } else {
  68. link_name = lb_get_entity_name(m, entity);
  69. }
  70. {
  71. StringHashKey key = string_hash_string(link_name);
  72. lbValue *found = string_map_get(&m->members, key);
  73. if (found) {
  74. lb_add_entity(m, entity, *found);
  75. return string_map_must_get(&m->procedures, key);
  76. }
  77. }
  78. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  79. p->module = m;
  80. entity->code_gen_module = m;
  81. entity->code_gen_procedure = p;
  82. p->entity = entity;
  83. p->name = link_name;
  84. DeclInfo *decl = entity->decl_info;
  85. ast_node(pl, ProcLit, decl->proc_lit);
  86. Type *pt = base_type(entity->type);
  87. GB_ASSERT(pt->kind == Type_Proc);
  88. p->type = entity->type;
  89. p->type_expr = decl->type_expr;
  90. p->body = pl->body;
  91. p->inlining = pl->inlining;
  92. p->is_foreign = entity->Procedure.is_foreign;
  93. p->is_export = entity->Procedure.is_export;
  94. p->is_entry_point = false;
  95. gbAllocator a = heap_allocator();
  96. p->children.allocator = a;
  97. p->defer_stmts.allocator = a;
  98. p->blocks.allocator = a;
  99. p->branch_blocks.allocator = a;
  100. p->context_stack.allocator = a;
  101. p->scope_stack.allocator = a;
  102. // map_init(&p->selector_values, 0);
  103. // map_init(&p->selector_addr, 0);
  104. // map_init(&p->tuple_fix_map, 0);
  105. if (p->is_foreign) {
  106. lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library);
  107. }
  108. LLVMTypeRef func_type = lb_get_procedure_raw_type(m, p->type);
  109. {
  110. TEMPORARY_ALLOCATOR_GUARD();
  111. char *c_link_name = alloc_cstring(temporary_allocator(), p->name);
  112. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  113. }
  114. lb_ensure_abi_function_type(m, p);
  115. lb_add_function_type_attributes(p->value, p->abi_function_type, p->abi_function_type->calling_convention);
  116. if (pt->Proc.diverging) {
  117. lb_add_attribute_to_proc(m, p->value, "noreturn");
  118. }
  119. if (pt->Proc.calling_convention == ProcCC_Naked) {
  120. lb_add_attribute_to_proc(m, p->value, "naked");
  121. }
  122. if (!entity->Procedure.is_foreign && build_context.disable_red_zone) {
  123. lb_add_attribute_to_proc(m, p->value, "noredzone");
  124. }
  125. switch (p->inlining) {
  126. case ProcInlining_inline:
  127. lb_add_attribute_to_proc(m, p->value, "alwaysinline");
  128. break;
  129. case ProcInlining_no_inline:
  130. lb_add_attribute_to_proc(m, p->value, "noinline");
  131. break;
  132. }
  133. switch (entity->Procedure.optimization_mode) {
  134. case ProcedureOptimizationMode_None:
  135. break;
  136. case ProcedureOptimizationMode_Minimal:
  137. lb_add_attribute_to_proc(m, p->value, "optnone");
  138. lb_add_attribute_to_proc(m, p->value, "noinline");
  139. break;
  140. case ProcedureOptimizationMode_Size:
  141. lb_add_attribute_to_proc(m, p->value, "optsize");
  142. break;
  143. case ProcedureOptimizationMode_Speed:
  144. // TODO(bill): handle this correctly
  145. lb_add_attribute_to_proc(m, p->value, "optsize");
  146. break;
  147. }
  148. if (!entity->Procedure.target_feature_disabled &&
  149. entity->Procedure.target_feature.len != 0) {
  150. auto features = split_by_comma(entity->Procedure.target_feature);
  151. for_array(i, features) {
  152. String feature = features[i];
  153. LLVMAttributeRef ref = LLVMCreateStringAttribute(
  154. m->ctx,
  155. cast(char const *)feature.text, cast(unsigned)feature.len,
  156. "", 0);
  157. LLVMAddAttributeAtIndex(p->value, LLVMAttributeIndex_FunctionIndex, ref);
  158. }
  159. }
  160. if (entity->flags & EntityFlag_Cold) {
  161. lb_add_attribute_to_proc(m, p->value, "cold");
  162. }
  163. if (p->is_export) {
  164. LLVMSetLinkage(p->value, LLVMDLLExportLinkage);
  165. LLVMSetDLLStorageClass(p->value, LLVMDLLExportStorageClass);
  166. LLVMSetVisibility(p->value, LLVMDefaultVisibility);
  167. lb_set_wasm_export_attributes(p->value, p->name);
  168. } else if (!p->is_foreign) {
  169. if (USE_SEPARATE_MODULES) {
  170. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  171. } else {
  172. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  173. // NOTE(bill): if a procedure is defined in package runtime and uses a custom link name,
  174. // then it is very likely it is required by LLVM and thus cannot have internal linkage
  175. if (entity->pkg != nullptr && entity->pkg->kind == Package_Runtime && p->body != nullptr) {
  176. GB_ASSERT(entity->kind == Entity_Procedure);
  177. String link_name = entity->Procedure.link_name;
  178. if (entity->flags & EntityFlag_CustomLinkName &&
  179. link_name != "") {
  180. if (string_starts_with(link_name, str_lit("__"))) {
  181. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  182. } else {
  183. LLVMSetLinkage(p->value, LLVMInternalLinkage);
  184. }
  185. }
  186. }
  187. }
  188. }
  189. lb_set_linkage_from_entity_flags(p->module, p->value, entity->flags);
  190. if (p->is_foreign) {
  191. lb_set_wasm_import_attributes(p->value, entity, p->name);
  192. }
  193. // NOTE(bill): offset==0 is the return value
  194. isize offset = 1;
  195. if (pt->Proc.return_by_pointer) {
  196. offset = 2;
  197. }
  198. isize parameter_index = 0;
  199. if (pt->Proc.param_count) {
  200. TypeTuple *params = &pt->Proc.params->Tuple;
  201. for (isize i = 0; i < pt->Proc.param_count; i++) {
  202. Entity *e = params->variables[i];
  203. if (e->kind != Entity_Variable) {
  204. continue;
  205. }
  206. if (i+1 == params->variables.count && pt->Proc.c_vararg) {
  207. continue;
  208. }
  209. if (e->flags&EntityFlag_NoAlias) {
  210. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  211. }
  212. parameter_index += 1;
  213. }
  214. }
  215. if (ignore_body) {
  216. p->body = nullptr;
  217. LLVMSetLinkage(p->value, LLVMExternalLinkage);
  218. }
  219. if (m->debug_builder) { // Debug Information
  220. Type *bt = base_type(p->type);
  221. unsigned line = cast(unsigned)entity->token.pos.line;
  222. LLVMMetadataRef scope = nullptr;
  223. LLVMMetadataRef file = nullptr;
  224. LLVMMetadataRef type = nullptr;
  225. scope = p->module->debug_compile_unit;
  226. type = lb_debug_type_internal_proc(m, bt);
  227. Ast *ident = entity->identifier.load();
  228. if (entity->file != nullptr) {
  229. file = lb_get_llvm_metadata(m, entity->file);
  230. scope = file;
  231. } else if (ident != nullptr && ident->file_id != 0) {
  232. file = lb_get_llvm_metadata(m, ident->file());
  233. scope = file;
  234. } else if (entity->scope != nullptr) {
  235. file = lb_get_llvm_metadata(m, entity->scope->file);
  236. scope = file;
  237. }
  238. GB_ASSERT_MSG(file != nullptr, "%.*s", LIT(entity->token.string));
  239. // LLVMBool is_local_to_unit = !entity->Procedure.is_export;
  240. LLVMBool is_local_to_unit = false;
  241. LLVMBool is_definition = p->body != nullptr;
  242. unsigned scope_line = line;
  243. u32 flags = LLVMDIFlagStaticMember;
  244. LLVMBool is_optimized = false;
  245. if (bt->Proc.diverging) {
  246. flags |= LLVMDIFlagNoReturn;
  247. }
  248. if (p->body == nullptr) {
  249. flags |= LLVMDIFlagPrototyped;
  250. is_optimized = false;
  251. }
  252. if (p->body != nullptr) {
  253. // String debug_name = entity->token.string.text;
  254. String debug_name = p->name;
  255. p->debug_info = LLVMDIBuilderCreateFunction(m->debug_builder, scope,
  256. cast(char const *)debug_name.text, debug_name.len,
  257. cast(char const *)p->name.text, p->name.len,
  258. file, line, type,
  259. is_local_to_unit, is_definition,
  260. scope_line, cast(LLVMDIFlags)flags, is_optimized
  261. );
  262. GB_ASSERT(p->debug_info != nullptr);
  263. LLVMSetSubprogram(p->value, p->debug_info);
  264. lb_set_llvm_metadata(m, p, p->debug_info);
  265. }
  266. }
  267. lbValue proc_value = {p->value, p->type};
  268. lb_add_entity(m, entity, proc_value);
  269. lb_add_member(m, p->name, proc_value);
  270. lb_add_procedure_value(m, p);
  271. return p;
  272. }
  273. gb_internal lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) {
  274. {
  275. lbValue *found = string_map_get(&m->members, link_name);
  276. GB_ASSERT_MSG(found == nullptr, "failed to create dummy procedure for: %.*s", LIT(link_name));
  277. }
  278. lbProcedure *p = gb_alloc_item(permanent_allocator(), lbProcedure);
  279. p->module = m;
  280. p->name = link_name;
  281. p->type = type;
  282. p->type_expr = nullptr;
  283. p->body = nullptr;
  284. p->tags = 0;
  285. p->inlining = ProcInlining_none;
  286. p->is_foreign = false;
  287. p->is_export = false;
  288. p->is_entry_point = false;
  289. gbAllocator a = permanent_allocator();
  290. p->children.allocator = a;
  291. p->defer_stmts.allocator = a;
  292. p->blocks.allocator = a;
  293. p->branch_blocks.allocator = a;
  294. p->context_stack.allocator = a;
  295. map_init(&p->tuple_fix_map, 0);
  296. char *c_link_name = alloc_cstring(permanent_allocator(), p->name);
  297. LLVMTypeRef func_type = lb_get_procedure_raw_type(m, p->type);
  298. p->value = LLVMAddFunction(m->mod, c_link_name, func_type);
  299. Type *pt = p->type;
  300. lbCallingConventionKind cc_kind = lbCallingConvention_C;
  301. // TODO(bill): Clean up this logic
  302. if (!is_arch_wasm()) {
  303. cc_kind = lb_calling_convention_map[pt->Proc.calling_convention];
  304. }
  305. LLVMSetFunctionCallConv(p->value, cc_kind);
  306. lbValue proc_value = {p->value, p->type};
  307. lb_add_member(m, p->name, proc_value);
  308. lb_add_procedure_value(m, p);
  309. // NOTE(bill): offset==0 is the return value
  310. isize offset = 1;
  311. if (pt->Proc.return_by_pointer) {
  312. lb_add_proc_attribute_at_index(p, 1, "sret");
  313. lb_add_proc_attribute_at_index(p, 1, "noalias");
  314. offset = 2;
  315. }
  316. isize parameter_index = 0;
  317. if (pt->Proc.calling_convention == ProcCC_Odin) {
  318. lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias");
  319. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull");
  320. lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture");
  321. }
  322. return p;
  323. }
  324. // gb_internal lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) {
  325. // lbParamPasskind kind = lbParamPass_Value;
  326. // if (e != nullptr && !are_types_identical(abi_type, e->type)) {
  327. // if (is_type_pointer(abi_type)) {
  328. // GB_ASSERT(e->kind == Entity_Variable);
  329. // Type *av = core_type(type_deref(abi_type));
  330. // if (are_types_identical(av, core_type(e->type))) {
  331. // kind = lbParamPass_Pointer;
  332. // if (e->flags&EntityFlag_Value) {
  333. // kind = lbParamPass_ConstRef;
  334. // }
  335. // } else {
  336. // kind = lbParamPass_BitCast;
  337. // }
  338. // } else if (is_type_integer(abi_type)) {
  339. // kind = lbParamPass_Integer;
  340. // } else if (abi_type == t_llvm_bool) {
  341. // kind = lbParamPass_Value;
  342. // } else if (is_type_boolean(abi_type)) {
  343. // kind = lbParamPass_Integer;
  344. // } else if (is_type_simd_vector(abi_type)) {
  345. // kind = lbParamPass_BitCast;
  346. // } else if (is_type_float(abi_type)) {
  347. // kind = lbParamPass_BitCast;
  348. // } else if (is_type_tuple(abi_type)) {
  349. // kind = lbParamPass_Tuple;
  350. // } else if (is_type_proc(abi_type)) {
  351. // kind = lbParamPass_Value;
  352. // } else {
  353. // GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type));
  354. // }
  355. // }
  356. // if (kind_) *kind_ = kind;
  357. // lbValue res = {};
  358. // res.value = LLVMGetParam(p->value, cast(unsigned)index);
  359. // res.type = abi_type;
  360. // return res;
  361. // }
  362. gb_internal void lb_start_block(lbProcedure *p, lbBlock *b) {
  363. GB_ASSERT(b != nullptr);
  364. if (!b->appended) {
  365. b->appended = true;
  366. LLVMAppendExistingBasicBlock(p->value, b->block);
  367. }
  368. LLVMPositionBuilderAtEnd(p->builder, b->block);
  369. p->curr_block = b;
  370. }
  371. gb_internal void lb_set_debug_position_to_procedure_begin(lbProcedure *p) {
  372. if (p->debug_info == nullptr) {
  373. return;
  374. }
  375. TokenPos pos = {};
  376. if (p->body != nullptr) {
  377. pos = ast_token(p->body).pos;
  378. } else if (p->type_expr != nullptr) {
  379. pos = ast_token(p->type_expr).pos;
  380. } else if (p->entity != nullptr) {
  381. pos = p->entity->token.pos;
  382. }
  383. if (pos.file_id != 0) {
  384. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  385. }
  386. }
  387. gb_internal void lb_set_debug_position_to_procedure_end(lbProcedure *p) {
  388. if (p->debug_info == nullptr) {
  389. return;
  390. }
  391. TokenPos pos = {};
  392. if (p->body != nullptr) {
  393. pos = ast_end_token(p->body).pos;
  394. } else if (p->type_expr != nullptr) {
  395. pos = ast_end_token(p->type_expr).pos;
  396. } else if (p->entity != nullptr) {
  397. pos = p->entity->token.pos;
  398. }
  399. if (pos.file_id != 0) {
  400. LLVMSetCurrentDebugLocation2(p->builder, lb_debug_location_from_token_pos(p, pos));
  401. }
  402. }
  403. gb_internal void lb_begin_procedure_body(lbProcedure *p) {
  404. DeclInfo *decl = decl_info_of_entity(p->entity);
  405. if (decl != nullptr) {
  406. for_array(i, decl->labels) {
  407. BlockLabel bl = decl->labels[i];
  408. lbBranchBlocks bb = {bl.label, nullptr, nullptr};
  409. array_add(&p->branch_blocks, bb);
  410. }
  411. }
  412. p->builder = LLVMCreateBuilderInContext(p->module->ctx);
  413. p->decl_block = lb_create_block(p, "decls", true);
  414. p->entry_block = lb_create_block(p, "entry", true);
  415. lb_start_block(p, p->entry_block);
  416. map_init(&p->direct_parameters);
  417. GB_ASSERT(p->type != nullptr);
  418. lb_ensure_abi_function_type(p->module, p);
  419. {
  420. lbFunctionType *ft = p->abi_function_type;
  421. unsigned param_offset = 0;
  422. lbValue return_ptr_value = {};
  423. if (ft->ret.kind == lbArg_Indirect) {
  424. // NOTE(bill): this must be parameter 0
  425. String name = str_lit("agg.result");
  426. if (ft->multiple_return_original_type &&
  427. p->type->Proc.has_named_results) {
  428. auto const &variables = p->type->Proc.results->Tuple.variables;
  429. Entity *e = variables[variables.count-1];
  430. if (!is_blank_ident(e->token)) {
  431. name = e->token.string;
  432. }
  433. }
  434. Type *return_ptr_type = reduce_tuple_to_single_type(p->type->Proc.results);
  435. bool split_returns = ft->multiple_return_original_type != nullptr;
  436. if (split_returns) {
  437. GB_ASSERT(is_type_tuple(return_ptr_type));
  438. auto const &variables = return_ptr_type->Tuple.variables;
  439. return_ptr_type = variables[variables.count-1]->type;
  440. }
  441. Type *ptr_type = alloc_type_pointer(return_ptr_type);
  442. Entity *e = alloc_entity_param(nullptr, make_token_ident(name), ptr_type, false, false);
  443. e->flags |= EntityFlag_NoAlias;
  444. return_ptr_value.value = LLVMGetParam(p->value, 0);
  445. LLVMSetValueName2(return_ptr_value.value, cast(char const *)name.text, name.len);
  446. return_ptr_value.type = ptr_type;
  447. p->return_ptr = lb_addr(return_ptr_value);
  448. lb_add_entity(p->module, e, return_ptr_value);
  449. param_offset += 1;
  450. }
  451. if (p->type->Proc.params != nullptr) {
  452. TypeTuple *params = &p->type->Proc.params->Tuple;
  453. unsigned raw_input_parameters_count = LLVMCountParams(p->value);
  454. p->raw_input_parameters = array_make<LLVMValueRef>(permanent_allocator(), raw_input_parameters_count);
  455. LLVMGetParams(p->value, p->raw_input_parameters.data);
  456. unsigned param_index = 0;
  457. for_array(i, params->variables) {
  458. Entity *e = params->variables[i];
  459. if (e->kind != Entity_Variable) {
  460. continue;
  461. }
  462. lbArgType *arg_type = &ft->args[param_index];
  463. defer (param_index += 1);
  464. if (arg_type->kind == lbArg_Ignore) {
  465. continue;
  466. } else if (arg_type->kind == lbArg_Direct) {
  467. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  468. LLVMTypeRef param_type = lb_type(p->module, e->type);
  469. LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index);
  470. LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type);
  471. lbValue param = {};
  472. param.value = value;
  473. param.type = e->type;
  474. map_set(&p->direct_parameters, e, param);
  475. lbValue ptr = lb_address_from_load_or_generate_local(p, param);
  476. GB_ASSERT(LLVMIsAAllocaInst(ptr.value));
  477. lb_add_entity(p->module, e, ptr);
  478. lbBlock *block = p->decl_block;
  479. if (original_value != value) {
  480. block = p->curr_block;
  481. }
  482. LLVMValueRef debug_storage_value = value;
  483. if (original_value != value && LLVMIsALoadInst(value)) {
  484. debug_storage_value = LLVMGetOperand(value, 0);
  485. }
  486. lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block, arg_type->kind);
  487. }
  488. } else if (arg_type->kind == lbArg_Indirect) {
  489. if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) {
  490. lbValue ptr = {};
  491. ptr.value = LLVMGetParam(p->value, param_offset+param_index);
  492. ptr.type = alloc_type_pointer(e->type);
  493. lb_add_entity(p->module, e, ptr);
  494. lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block, arg_type->kind);
  495. }
  496. }
  497. }
  498. }
  499. if (p->type->Proc.has_named_results) {
  500. GB_ASSERT(p->type->Proc.result_count > 0);
  501. TypeTuple *results = &p->type->Proc.results->Tuple;
  502. for_array(i, results->variables) {
  503. Entity *e = results->variables[i];
  504. GB_ASSERT(e->kind == Entity_Variable);
  505. if (e->token.string != "") {
  506. GB_ASSERT(!is_blank_ident(e->token));
  507. lbAddr res = {};
  508. if (p->entity && p->entity->decl_info &&
  509. p->entity->decl_info->defer_use_checked &&
  510. p->entity->decl_info->defer_used == 0) {
  511. // NOTE(bill): this is a bodge to get around the issue of the problem BELOW
  512. // We check to see if we ever use a defer statement ever within a procedure and if it
  513. // if it never happens, see if you can possibly do take the return value pointer
  514. //
  515. // NOTE(bill): this could be buggy in that I have missed a case where `defer` was used
  516. //
  517. // TODO(bill): This could be optimized to check to see where a `defer` only uses
  518. // the variable in question
  519. bool has_return_ptr = p->return_ptr.addr.value != nullptr;
  520. lbValue ptr = {};
  521. if (ft->multiple_return_original_type != nullptr) {
  522. isize the_offset = -1;
  523. if (i+1 < results->variables.count) {
  524. the_offset = cast(isize)param_offset + ft->original_arg_count + i;
  525. } else if (has_return_ptr) {
  526. GB_ASSERT(i+1 == results->variables.count);
  527. the_offset = 0;
  528. }
  529. if (the_offset >= 0) {
  530. lbValue ptr = {};
  531. ptr.value = LLVMGetParam(p->value, cast(unsigned)the_offset);
  532. ptr.type = alloc_type_pointer(e->type);
  533. }
  534. } else if (has_return_ptr) {
  535. lbValue ptr = p->return_ptr.addr;
  536. if (results->variables.count > 1) {
  537. ptr = lb_emit_tuple_ep(p, ptr, cast(i32)i);
  538. }
  539. GB_ASSERT(is_type_pointer(ptr.type));
  540. GB_ASSERT(are_types_identical(type_deref(ptr.type), e->type));
  541. }
  542. if (ptr.value != nullptr) {
  543. lb_add_entity(p->module, e, ptr);
  544. lb_add_debug_local_variable(p, ptr.value, e->type, e->token);
  545. // NOTE(bill): no need to zero on the callee side as it is zeroed on the caller side
  546. res = lb_addr(ptr);
  547. }
  548. }
  549. if (res.addr.type == nullptr) {
  550. // NOTE(bill): Don't even bother trying to optimize this with the return ptr value
  551. // This will violate the defer rules if you do:
  552. // foo :: proc() -> (x, y: T) {
  553. // defer x = ... // defer is executed after the `defer`
  554. // return // the values returned should be zeroed
  555. // }
  556. // NOTE(bill): REALLY, don't even bother.
  557. //
  558. // IMPORTANT NOTE(bill): REALLY, don't even bother!!!!!!
  559. res = lb_add_local(p, e->type, e);
  560. }
  561. if (e->Variable.param_value.kind != ParameterValue_Invalid) {
  562. lbValue c = lb_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos);
  563. lb_addr_store(p, res, c);
  564. }
  565. }
  566. }
  567. }
  568. }
  569. if (p->type->Proc.calling_convention == ProcCC_Odin) {
  570. lb_push_context_onto_stack_from_implicit_parameter(p);
  571. }
  572. lb_set_debug_position_to_procedure_begin(p);
  573. if (p->debug_info != nullptr) {
  574. if (p->context_stack.count != 0) {
  575. p->curr_block = p->decl_block;
  576. lb_add_debug_context_variable(p, lb_find_or_generate_context_ptr(p));
  577. }
  578. }
  579. lb_start_block(p, p->entry_block);
  580. }
  581. gb_internal void lb_end_procedure_body(lbProcedure *p) {
  582. lb_set_debug_position_to_procedure_begin(p);
  583. LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block);
  584. LLVMBuildBr(p->builder, p->entry_block->block);
  585. LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block);
  586. LLVMValueRef instr = nullptr;
  587. // Make sure there is a "ret void" at the end of a procedure with no return type
  588. if (p->type->Proc.result_count == 0) {
  589. instr = LLVMGetLastInstruction(p->curr_block->block);
  590. if (!lb_is_instr_terminating(instr)) {
  591. lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr);
  592. lb_set_debug_position_to_procedure_end(p);
  593. LLVMBuildRetVoid(p->builder);
  594. }
  595. }
  596. LLVMBasicBlockRef first_block = LLVMGetFirstBasicBlock(p->value);
  597. LLVMBasicBlockRef block = nullptr;
  598. // Make sure every block terminates, and if not, make it unreachable
  599. for (block = first_block; block != nullptr; block = LLVMGetNextBasicBlock(block)) {
  600. instr = LLVMGetLastInstruction(block);
  601. if (instr == nullptr || !lb_is_instr_terminating(instr)) {
  602. LLVMPositionBuilderAtEnd(p->builder, block);
  603. LLVMBuildUnreachable(p->builder);
  604. }
  605. }
  606. p->curr_block = nullptr;
  607. p->state_flags = 0;
  608. }
  609. gb_internal void lb_end_procedure(lbProcedure *p) {
  610. LLVMDisposeBuilder(p->builder);
  611. }
  612. gb_internal void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) {
  613. GB_ASSERT(pd->body != nullptr);
  614. lbModule *m = p->module;
  615. auto *min_dep_set = &m->info->minimum_dependency_set;
  616. if (ptr_set_exists(min_dep_set, e) == false) {
  617. // NOTE(bill): Nothing depends upon it so doesn't need to be built
  618. return;
  619. }
  620. // NOTE(bill): Generate a new name
  621. // parent.name-guid
  622. String original_name = e->token.string;
  623. String pd_name = original_name;
  624. if (e->Procedure.link_name.len > 0) {
  625. pd_name = e->Procedure.link_name;
  626. }
  627. isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1;
  628. char *name_text = gb_alloc_array(permanent_allocator(), char, name_len);
  629. i32 guid = cast(i32)p->children.count;
  630. name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid);
  631. String name = make_string(cast(u8 *)name_text, name_len-1);
  632. e->Procedure.link_name = name;
  633. lbProcedure *nested_proc = lb_create_procedure(p->module, e);
  634. e->code_gen_procedure = nested_proc;
  635. lbValue value = {};
  636. value.value = nested_proc->value;
  637. value.type = nested_proc->type;
  638. lb_add_entity(m, e, value);
  639. array_add(&p->children, nested_proc);
  640. array_add(&m->procedures_to_generate, nested_proc);
  641. }
  642. gb_internal Array<lbValue> lb_value_to_array(lbProcedure *p, gbAllocator const &allocator, lbValue value) {
  643. Array<lbValue> array = {};
  644. Type *t = base_type(value.type);
  645. if (t == nullptr) {
  646. // Do nothing
  647. } else if (is_type_tuple(t)) {
  648. array = array_make<lbValue>(allocator, 0, t->Tuple.variables.count);
  649. lb_append_tuple_values(p, &array, value);
  650. } else {
  651. array = array_make<lbValue>(allocator, 1);
  652. array[0] = value;
  653. }
  654. return array;
  655. }
  656. gb_internal 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) {
  657. GB_ASSERT(p->module->ctx == LLVMGetTypeContext(LLVMTypeOf(value.value)));
  658. unsigned arg_count = cast(unsigned)processed_args.count;
  659. if (return_ptr.value != nullptr) {
  660. arg_count += 1;
  661. }
  662. if (context_ptr.addr.value != nullptr) {
  663. arg_count += 1;
  664. }
  665. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  666. isize arg_index = 0;
  667. if (return_ptr.value != nullptr) {
  668. args[arg_index++] = return_ptr.value;
  669. }
  670. for_array(i, processed_args) {
  671. lbValue arg = processed_args[i];
  672. if (is_type_proc(arg.type)) {
  673. arg.value = LLVMBuildPointerCast(p->builder, arg.value, lb_type(p->module, arg.type), "");
  674. }
  675. args[arg_index++] = arg.value;
  676. }
  677. if (context_ptr.addr.value != nullptr) {
  678. LLVMValueRef cp = context_ptr.addr.value;
  679. cp = LLVMBuildPointerCast(p->builder, cp, lb_type(p->module, t_rawptr), "");
  680. args[arg_index++] = cp;
  681. }
  682. GB_ASSERT(arg_index == arg_count);
  683. LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder);
  684. GB_ASSERT(curr_block != p->decl_block->block);
  685. {
  686. Type *proc_type = base_type(value.type);
  687. GB_ASSERT(proc_type->kind == Type_Proc);
  688. LLVMTypeRef fnp = lb_type_internal_for_procedures_raw(p->module, proc_type);
  689. LLVMTypeRef ftp = LLVMPointerType(fnp, 0);
  690. LLVMValueRef fn = value.value;
  691. if (!lb_is_type_kind(LLVMTypeOf(value.value), LLVMFunctionTypeKind)) {
  692. fn = LLVMBuildPointerCast(p->builder, fn, ftp, "");
  693. }
  694. GB_ASSERT_MSG(lb_is_type_kind(fnp, LLVMFunctionTypeKind), "%s", LLVMPrintTypeToString(fnp));
  695. lbFunctionType *ft = map_must_get(&p->module->function_type_map, base_type(value.type));
  696. {
  697. unsigned param_count = LLVMCountParamTypes(fnp);
  698. GB_ASSERT(arg_count >= param_count);
  699. LLVMTypeRef *param_types = gb_alloc_array(temporary_allocator(), LLVMTypeRef, param_count);
  700. LLVMGetParamTypes(fnp, param_types);
  701. for (unsigned i = 0; i < param_count; i++) {
  702. LLVMTypeRef param_type = param_types[i];
  703. LLVMTypeRef arg_type = LLVMTypeOf(args[i]);
  704. // LLVMTypeKind param_kind = LLVMGetTypeKind(param_type);
  705. // LLVMTypeKind arg_kind = LLVMGetTypeKind(arg_type);
  706. GB_ASSERT_MSG(
  707. arg_type == param_type,
  708. "Parameter types do not match: %s != %s, argument: %s\n\t%s",
  709. LLVMPrintTypeToString(arg_type),
  710. LLVMPrintTypeToString(param_type),
  711. LLVMPrintValueToString(args[i]),
  712. LLVMPrintTypeToString(fnp)
  713. );
  714. }
  715. }
  716. LLVMValueRef ret = LLVMBuildCall2(p->builder, fnp, fn, args, arg_count, "");
  717. LLVMAttributeIndex param_offset = LLVMAttributeIndex_FirstArgIndex;
  718. if (return_ptr.value != nullptr) {
  719. param_offset += 1;
  720. LLVMAddCallSiteAttribute(ret, 1, lb_create_enum_attribute_with_type(p->module->ctx, "sret", LLVMTypeOf(args[0])));
  721. }
  722. for_array(i, ft->args) {
  723. LLVMAttributeRef attribute = ft->args[i].attribute;
  724. if (attribute != nullptr) {
  725. LLVMAddCallSiteAttribute(ret, param_offset + cast(LLVMAttributeIndex)i, attribute);
  726. }
  727. }
  728. switch (inlining) {
  729. case ProcInlining_none:
  730. break;
  731. case ProcInlining_inline:
  732. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "alwaysinline"));
  733. break;
  734. case ProcInlining_no_inline:
  735. LLVMAddCallSiteAttribute(ret, LLVMAttributeIndex_FunctionIndex, lb_create_enum_attribute(p->module->ctx, "noinline"));
  736. break;
  737. }
  738. lbValue res = {};
  739. res.value = ret;
  740. res.type = abi_rt;
  741. return res;
  742. }
  743. }
  744. gb_internal lbValue lb_lookup_runtime_procedure(lbModule *m, String const &name) {
  745. AstPackage *pkg = m->info->runtime_package;
  746. Entity *e = scope_lookup_current(pkg->scope, name);
  747. return lb_find_procedure_value_from_entity(m, e);
  748. }
  749. gb_internal lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array<lbValue> const &args) {
  750. String name = make_string_c(c_name);
  751. lbValue proc = lb_lookup_runtime_procedure(p->module, name);
  752. return lb_emit_call(p, proc, args);
  753. }
  754. gb_internal lbValue lb_emit_conjugate(lbProcedure *p, lbValue val, Type *type) {
  755. lbValue res = {};
  756. Type *t = val.type;
  757. if (is_type_complex(t)) {
  758. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  759. lbValue real = lb_emit_struct_ev(p, val, 0);
  760. lbValue imag = lb_emit_struct_ev(p, val, 1);
  761. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  762. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real);
  763. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag);
  764. } else if (is_type_quaternion(t)) {
  765. // @QuaternionLayout
  766. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, false));
  767. lbValue real = lb_emit_struct_ev(p, val, 3);
  768. lbValue imag = lb_emit_struct_ev(p, val, 0);
  769. lbValue jmag = lb_emit_struct_ev(p, val, 1);
  770. lbValue kmag = lb_emit_struct_ev(p, val, 2);
  771. imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type);
  772. jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type);
  773. kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type);
  774. lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real);
  775. lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag);
  776. lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag);
  777. lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag);
  778. } else if (is_type_array_like(t)) {
  779. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  780. Type *elem_type = base_array_type(t);
  781. i64 count = get_array_type_count(t);
  782. for (i64 i = 0; i < count; i++) {
  783. lbValue dst = lb_emit_array_epi(p, res, i);
  784. lbValue elem = lb_emit_struct_ev(p, val, cast(i32)i);
  785. elem = lb_emit_conjugate(p, elem, elem_type);
  786. lb_emit_store(p, dst, elem);
  787. }
  788. } else if (is_type_matrix(t)) {
  789. Type *mt = base_type(t);
  790. GB_ASSERT(mt->kind == Type_Matrix);
  791. Type *elem_type = mt->Matrix.elem;
  792. res = lb_addr_get_ptr(p, lb_add_local_generated(p, type, true));
  793. for (i64 j = 0; j < mt->Matrix.column_count; j++) {
  794. for (i64 i = 0; i < mt->Matrix.row_count; i++) {
  795. lbValue dst = lb_emit_matrix_epi(p, res, i, j);
  796. lbValue elem = lb_emit_matrix_ev(p, val, i, j);
  797. elem = lb_emit_conjugate(p, elem, elem_type);
  798. lb_emit_store(p, dst, elem);
  799. }
  800. }
  801. }
  802. return lb_emit_load(p, res);
  803. }
  804. gb_internal lbValue lb_emit_call(lbProcedure *p, lbValue value, Array<lbValue> const &args, ProcInlining inlining) {
  805. lbModule *m = p->module;
  806. Type *pt = base_type(value.type);
  807. GB_ASSERT(pt->kind == Type_Proc);
  808. Type *results = pt->Proc.results;
  809. lbAddr context_ptr = {};
  810. if (pt->Proc.calling_convention == ProcCC_Odin) {
  811. context_ptr = lb_find_or_generate_context_ptr(p);
  812. }
  813. defer (if (pt->Proc.diverging) {
  814. LLVMBuildUnreachable(p->builder);
  815. });
  816. bool is_c_vararg = pt->Proc.c_vararg;
  817. isize param_count = pt->Proc.param_count;
  818. if (is_c_vararg) {
  819. GB_ASSERT(param_count-1 <= args.count);
  820. param_count -= 1;
  821. } else {
  822. GB_ASSERT_MSG(param_count == args.count, "%td == %td (%s)", param_count, args.count, LLVMPrintValueToString(value.value));
  823. }
  824. lbValue result = {};
  825. auto processed_args = array_make<lbValue>(permanent_allocator(), 0, args.count);
  826. {
  827. bool is_odin_cc = is_calling_convention_odin(pt->Proc.calling_convention);
  828. lbFunctionType *ft = lb_get_function_type(m, pt);
  829. bool return_by_pointer = ft->ret.kind == lbArg_Indirect;
  830. bool split_returns = ft->multiple_return_original_type != nullptr;
  831. unsigned param_index = 0;
  832. for (isize i = 0; i < param_count; i++) {
  833. Entity *e = pt->Proc.params->Tuple.variables[i];
  834. if (e->kind != Entity_Variable) {
  835. continue;
  836. }
  837. GB_ASSERT(e->flags & EntityFlag_Param);
  838. Type *original_type = e->type;
  839. lbArgType *arg = &ft->args[param_index];
  840. if (arg->kind == lbArg_Ignore) {
  841. continue;
  842. }
  843. lbValue x = lb_emit_conv(p, args[i], original_type);
  844. LLVMTypeRef xt = lb_type(p->module, x.type);
  845. if (arg->kind == lbArg_Direct) {
  846. LLVMTypeRef abi_type = arg->cast_type;
  847. if (!abi_type) {
  848. abi_type = arg->type;
  849. }
  850. if (xt == abi_type) {
  851. array_add(&processed_args, x);
  852. } else {
  853. x.value = OdinLLVMBuildTransmute(p, x.value, abi_type);
  854. array_add(&processed_args, x);
  855. }
  856. } else if (arg->kind == lbArg_Indirect) {
  857. lbValue ptr = {};
  858. if (arg->is_byval) {
  859. if (is_odin_cc) {
  860. if (are_types_identical(original_type, t_source_code_location)) {
  861. ptr = lb_address_from_load_or_generate_local(p, x);
  862. // } else {
  863. // ptr = lb_address_from_load_if_readonly_parameter(p, x);
  864. }
  865. }
  866. if (ptr.value == nullptr) {
  867. ptr = lb_copy_value_to_ptr(p, x, original_type, arg->byval_alignment);
  868. }
  869. } else if (is_odin_cc) {
  870. // NOTE(bill): Odin parameters are immutable so the original value can be passed if possible
  871. // i.e. `T const &` in C++
  872. if (LLVMIsConstant(x.value)) {
  873. // NOTE(bill): if the value is already constant, then just it as a global variable
  874. // and pass it by pointer
  875. lbAddr addr = lb_add_global_generated(p->module, original_type, x);
  876. lb_make_global_private_const(addr);
  877. ptr = addr.addr;
  878. } else {
  879. ptr = lb_address_from_load_or_generate_local(p, x);
  880. }
  881. } else {
  882. if (LLVMIsConstant(x.value)) {
  883. // NOTE(bill): if the value is already constant, then just it as a global variable
  884. // and pass it by pointer
  885. lbAddr addr = lb_add_global_generated(p->module, original_type, x);
  886. lb_make_global_private_const(addr);
  887. ptr = addr.addr;
  888. } else {
  889. ptr = lb_copy_value_to_ptr(p, x, original_type, 16);
  890. }
  891. }
  892. array_add(&processed_args, ptr);
  893. }
  894. param_index += 1;
  895. }
  896. if (is_c_vararg) {
  897. for (isize i = processed_args.count; i < args.count; i++) {
  898. array_add(&processed_args, args[i]);
  899. }
  900. }
  901. if (inlining == ProcInlining_none) {
  902. inlining = p->inlining;
  903. }
  904. Type *rt = reduce_tuple_to_single_type(results);
  905. Type *original_rt = rt;
  906. if (split_returns) {
  907. GB_ASSERT(rt->kind == Type_Tuple);
  908. for (isize j = 0; j < rt->Tuple.variables.count-1; j++) {
  909. Type *partial_return_type = rt->Tuple.variables[j]->type;
  910. lbValue partial_return_ptr = lb_add_local(p, partial_return_type, nullptr, true, false).addr;
  911. array_add(&processed_args, partial_return_ptr);
  912. }
  913. rt = reduce_tuple_to_single_type(rt->Tuple.variables[rt->Tuple.variables.count-1]->type);
  914. }
  915. if (return_by_pointer) {
  916. lbValue return_ptr = lb_add_local_generated(p, rt, true).addr;
  917. lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining);
  918. result = lb_emit_load(p, return_ptr);
  919. } else if (rt != nullptr) {
  920. result = lb_emit_call_internal(p, value, {}, processed_args, rt, context_ptr, inlining);
  921. if (ft->ret.cast_type) {
  922. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.cast_type);
  923. }
  924. result.value = OdinLLVMBuildTransmute(p, result.value, ft->ret.type);
  925. result.type = rt;
  926. if (LLVMTypeOf(result.value) == LLVMInt1TypeInContext(p->module->ctx)) {
  927. result.type = t_llvm_bool;
  928. }
  929. if (!is_type_tuple(rt)) {
  930. result = lb_emit_conv(p, result, rt);
  931. }
  932. } else {
  933. lb_emit_call_internal(p, value, {}, processed_args, nullptr, context_ptr, inlining);
  934. }
  935. if (original_rt != rt) {
  936. GB_ASSERT(split_returns);
  937. GB_ASSERT(is_type_tuple(original_rt));
  938. // IMPORTANT NOTE(bill, 2022-11-24)
  939. // result_ptr is a dummy value which is only used to reference a tuple
  940. // value for the "tuple-fix"
  941. //
  942. // The reason for the fake stack allocation is to have a unique pointer
  943. // for the value to be used as a key within the procedure itself
  944. lbValue result_ptr = lb_add_local_generated(p, original_rt, false).addr;
  945. isize ret_count = original_rt->Tuple.variables.count;
  946. auto tuple_fix_values = slice_make<lbValue>(permanent_allocator(), ret_count);
  947. auto tuple_geps = slice_make<lbValue>(permanent_allocator(), ret_count);
  948. isize offset = ft->original_arg_count;
  949. for (isize j = 0; j < ret_count-1; j++) {
  950. lbValue ret_arg_ptr = processed_args[offset + j];
  951. lbValue ret_arg = lb_emit_load(p, ret_arg_ptr);
  952. tuple_fix_values[j] = ret_arg;
  953. }
  954. tuple_fix_values[ret_count-1] = result;
  955. #if 0
  956. for (isize j = 0; j < ret_count; j++) {
  957. tuple_geps[j] = lb_emit_struct_ep(p, result_ptr, cast(i32)j);
  958. }
  959. for (isize j = 0; j < ret_count; j++) {
  960. lb_emit_store(p, tuple_geps[j], tuple_fix_values[j]);
  961. }
  962. #endif
  963. result = lb_emit_load(p, result_ptr);
  964. lbTupleFix tf = {tuple_fix_values};
  965. map_set(&p->tuple_fix_map, result_ptr.value, tf);
  966. map_set(&p->tuple_fix_map, result.value, tf);
  967. }
  968. }
  969. LLVMValueRef the_proc_value = value.value;
  970. if (LLVMIsAConstantExpr(the_proc_value)) {
  971. // NOTE(bill): it's a bit cast
  972. the_proc_value = LLVMGetOperand(the_proc_value, 0);
  973. }
  974. Entity **found = map_get(&p->module->procedure_values, the_proc_value);
  975. if (found != nullptr) {
  976. Entity *e = *found;
  977. if (e != nullptr && entity_has_deferred_procedure(e)) {
  978. DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind;
  979. Entity *deferred_entity = e->Procedure.deferred_procedure.entity;
  980. lbValue deferred = lb_find_procedure_value_from_entity(p->module, deferred_entity);
  981. bool by_ptr = false;
  982. auto in_args = args;
  983. Array<lbValue> result_as_args = {};
  984. switch (kind) {
  985. case DeferredProcedure_none:
  986. break;
  987. case DeferredProcedure_in_by_ptr:
  988. by_ptr = true;
  989. /*fallthrough*/
  990. case DeferredProcedure_in:
  991. result_as_args = array_clone(heap_allocator(), in_args);
  992. break;
  993. case DeferredProcedure_out_by_ptr:
  994. by_ptr = true;
  995. /*fallthrough*/
  996. case DeferredProcedure_out:
  997. result_as_args = lb_value_to_array(p, heap_allocator(), result);
  998. break;
  999. case DeferredProcedure_in_out_by_ptr:
  1000. by_ptr = true;
  1001. /*fallthrough*/
  1002. case DeferredProcedure_in_out:
  1003. {
  1004. auto out_args = lb_value_to_array(p, heap_allocator(), result);
  1005. array_init(&result_as_args, heap_allocator(), in_args.count + out_args.count);
  1006. array_copy(&result_as_args, in_args, 0);
  1007. array_copy(&result_as_args, out_args, in_args.count);
  1008. }
  1009. break;
  1010. }
  1011. if (by_ptr) {
  1012. for_array(i, result_as_args) {
  1013. lbValue arg_ptr = lb_address_from_load_or_generate_local(p, result_as_args[i]);
  1014. result_as_args[i] = arg_ptr;
  1015. }
  1016. }
  1017. lb_add_defer_proc(p, p->scope_index, deferred, result_as_args);
  1018. }
  1019. }
  1020. return result;
  1021. }
  1022. gb_internal LLVMValueRef llvm_splat_int(i64 count, LLVMTypeRef type, i64 value, bool is_signed=false) {
  1023. LLVMValueRef v = LLVMConstInt(type, value, is_signed);
  1024. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1025. for (i64 i = 0; i < count; i++) {
  1026. values[i] = v;
  1027. }
  1028. return LLVMConstVector(values, cast(unsigned)count);
  1029. }
  1030. gb_internal lbValue lb_build_builtin_simd_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId builtin_id) {
  1031. ast_node(ce, CallExpr, expr);
  1032. lbModule *m = p->module;
  1033. lbValue res = {};
  1034. res.type = tv.type;
  1035. lbValue arg0 = {}; if (ce->args.count > 0) arg0 = lb_build_expr(p, ce->args[0]);
  1036. lbValue arg1 = {}; if (ce->args.count > 1) arg1 = lb_build_expr(p, ce->args[1]);
  1037. lbValue arg2 = {}; if (ce->args.count > 2) arg2 = lb_build_expr(p, ce->args[2]);
  1038. Type *elem = base_array_type(arg0.type);
  1039. bool is_float = is_type_float(elem);
  1040. bool is_signed = !is_type_unsigned(elem);
  1041. LLVMOpcode op_code = cast(LLVMOpcode)0;
  1042. switch (builtin_id) {
  1043. case BuiltinProc_simd_add:
  1044. case BuiltinProc_simd_sub:
  1045. case BuiltinProc_simd_mul:
  1046. case BuiltinProc_simd_div:
  1047. case BuiltinProc_simd_rem:
  1048. if (is_float) {
  1049. switch (builtin_id) {
  1050. case BuiltinProc_simd_add: op_code = LLVMFAdd; break;
  1051. case BuiltinProc_simd_sub: op_code = LLVMFSub; break;
  1052. case BuiltinProc_simd_mul: op_code = LLVMFMul; break;
  1053. case BuiltinProc_simd_div: op_code = LLVMFDiv; break;
  1054. }
  1055. } else {
  1056. switch (builtin_id) {
  1057. case BuiltinProc_simd_add: op_code = LLVMAdd; break;
  1058. case BuiltinProc_simd_sub: op_code = LLVMSub; break;
  1059. case BuiltinProc_simd_mul: op_code = LLVMMul; break;
  1060. case BuiltinProc_simd_div:
  1061. if (is_signed) {
  1062. op_code = LLVMSDiv;
  1063. } else {
  1064. op_code = LLVMUDiv;
  1065. }
  1066. break;
  1067. case BuiltinProc_simd_rem:
  1068. if (is_signed) {
  1069. op_code = LLVMSRem;
  1070. } else {
  1071. op_code = LLVMURem;
  1072. }
  1073. break;
  1074. }
  1075. }
  1076. if (op_code) {
  1077. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1078. return res;
  1079. }
  1080. break;
  1081. case BuiltinProc_simd_shl: // Odin logic
  1082. case BuiltinProc_simd_shr: // Odin logic
  1083. case BuiltinProc_simd_shl_masked: // C logic
  1084. case BuiltinProc_simd_shr_masked: // C logic
  1085. {
  1086. i64 sz = type_size_of(elem);
  1087. GB_ASSERT(arg0.type->kind == Type_SimdVector);
  1088. i64 count = arg0.type->SimdVector.count;
  1089. Type *elem1 = base_array_type(arg1.type);
  1090. bool is_masked = false;
  1091. switch (builtin_id) {
  1092. case BuiltinProc_simd_shl: op_code = LLVMShl; is_masked = false; break;
  1093. case BuiltinProc_simd_shr: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = false; break;
  1094. case BuiltinProc_simd_shl_masked: op_code = LLVMShl; is_masked = true; break;
  1095. case BuiltinProc_simd_shr_masked: op_code = is_signed ? LLVMAShr : LLVMLShr; is_masked = true; break;
  1096. }
  1097. if (op_code) {
  1098. LLVMValueRef bits = llvm_splat_int(count, lb_type(m, elem1), sz*8 - 1);
  1099. if (is_masked) {
  1100. // C logic
  1101. LLVMValueRef shift = LLVMBuildAnd(p->builder, arg1.value, bits, "");
  1102. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, shift, "");
  1103. } else {
  1104. // Odin logic
  1105. LLVMValueRef zero = lb_const_nil(m, arg1.type).value;
  1106. LLVMValueRef mask = LLVMBuildICmp(p->builder, LLVMIntULE, arg1.value, bits, "");
  1107. LLVMValueRef shift = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1108. res.value = LLVMBuildSelect(p->builder, mask, shift, zero, "");
  1109. }
  1110. return res;
  1111. }
  1112. }
  1113. break;
  1114. case BuiltinProc_simd_and:
  1115. case BuiltinProc_simd_or:
  1116. case BuiltinProc_simd_xor:
  1117. case BuiltinProc_simd_and_not:
  1118. switch (builtin_id) {
  1119. case BuiltinProc_simd_and: op_code = LLVMAnd; break;
  1120. case BuiltinProc_simd_or: op_code = LLVMOr; break;
  1121. case BuiltinProc_simd_xor: op_code = LLVMXor; break;
  1122. case BuiltinProc_simd_and_not:
  1123. op_code = LLVMAnd;
  1124. arg1.value = LLVMBuildNot(p->builder, arg1.value, "");
  1125. break;
  1126. }
  1127. if (op_code) {
  1128. res.value = LLVMBuildBinOp(p->builder, op_code, arg0.value, arg1.value, "");
  1129. return res;
  1130. }
  1131. break;
  1132. case BuiltinProc_simd_neg:
  1133. if (is_float) {
  1134. res.value = LLVMBuildFNeg(p->builder, arg0.value, "");
  1135. } else {
  1136. res.value = LLVMBuildNeg(p->builder, arg0.value, "");
  1137. }
  1138. return res;
  1139. case BuiltinProc_simd_abs:
  1140. if (is_float) {
  1141. LLVMValueRef pos = arg0.value;
  1142. LLVMValueRef neg = LLVMBuildFNeg(p->builder, pos, "");
  1143. LLVMValueRef cond = LLVMBuildFCmp(p->builder, LLVMRealOGT, pos, neg, "");
  1144. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1145. } else {
  1146. LLVMValueRef pos = arg0.value;
  1147. LLVMValueRef neg = LLVMBuildNeg(p->builder, pos, "");
  1148. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, pos, neg, "");
  1149. res.value = LLVMBuildSelect(p->builder, cond, pos, neg, "");
  1150. }
  1151. return res;
  1152. case BuiltinProc_simd_min:
  1153. if (is_float) {
  1154. LLVMValueRef cond = LLVMBuildFCmp(p->builder, LLVMRealOLT, arg0.value, arg1.value, "");
  1155. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1156. } else {
  1157. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSLT : LLVMIntULT, arg0.value, arg1.value, "");
  1158. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1159. }
  1160. return res;
  1161. case BuiltinProc_simd_max:
  1162. if (is_float) {
  1163. LLVMValueRef cond = LLVMBuildFCmp(p->builder, LLVMRealOGT, arg0.value, arg1.value, "");
  1164. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1165. } else {
  1166. LLVMValueRef cond = LLVMBuildICmp(p->builder, is_signed ? LLVMIntSGT : LLVMIntUGT, arg0.value, arg1.value, "");
  1167. res.value = LLVMBuildSelect(p->builder, cond, arg0.value, arg1.value, "");
  1168. }
  1169. return res;
  1170. case BuiltinProc_simd_lanes_eq:
  1171. case BuiltinProc_simd_lanes_ne:
  1172. case BuiltinProc_simd_lanes_lt:
  1173. case BuiltinProc_simd_lanes_le:
  1174. case BuiltinProc_simd_lanes_gt:
  1175. case BuiltinProc_simd_lanes_ge:
  1176. if (is_float) {
  1177. LLVMRealPredicate pred = cast(LLVMRealPredicate)0;
  1178. switch (builtin_id) {
  1179. case BuiltinProc_simd_lanes_eq: pred = LLVMRealOEQ; break;
  1180. case BuiltinProc_simd_lanes_ne: pred = LLVMRealONE; break;
  1181. case BuiltinProc_simd_lanes_lt: pred = LLVMRealOLT; break;
  1182. case BuiltinProc_simd_lanes_le: pred = LLVMRealOLE; break;
  1183. case BuiltinProc_simd_lanes_gt: pred = LLVMRealOGT; break;
  1184. case BuiltinProc_simd_lanes_ge: pred = LLVMRealOGE; break;
  1185. }
  1186. if (pred) {
  1187. res.value = LLVMBuildFCmp(p->builder, pred, arg0.value, arg1.value, "");
  1188. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1189. return res;
  1190. }
  1191. } else {
  1192. LLVMIntPredicate pred = cast(LLVMIntPredicate)0;
  1193. switch (builtin_id) {
  1194. case BuiltinProc_simd_lanes_eq: pred = LLVMIntEQ; break;
  1195. case BuiltinProc_simd_lanes_ne: pred = LLVMIntNE; break;
  1196. case BuiltinProc_simd_lanes_lt: pred = is_signed ? LLVMIntSLT :LLVMIntULT; break;
  1197. case BuiltinProc_simd_lanes_le: pred = is_signed ? LLVMIntSLE :LLVMIntULE; break;
  1198. case BuiltinProc_simd_lanes_gt: pred = is_signed ? LLVMIntSGT :LLVMIntUGT; break;
  1199. case BuiltinProc_simd_lanes_ge: pred = is_signed ? LLVMIntSGE :LLVMIntUGE; break;
  1200. }
  1201. if (pred) {
  1202. res.value = LLVMBuildICmp(p->builder, pred, arg0.value, arg1.value, "");
  1203. res.value = LLVMBuildSExtOrBitCast(p->builder, res.value, lb_type(m, tv.type), "");
  1204. return res;
  1205. }
  1206. }
  1207. break;
  1208. case BuiltinProc_simd_extract:
  1209. res.value = LLVMBuildExtractElement(p->builder, arg0.value, arg1.value, "");
  1210. return res;
  1211. case BuiltinProc_simd_replace:
  1212. res.value = LLVMBuildInsertElement(p->builder, arg0.value, arg2.value, arg1.value, "");
  1213. return res;
  1214. case BuiltinProc_simd_reduce_add_ordered:
  1215. case BuiltinProc_simd_reduce_mul_ordered:
  1216. {
  1217. LLVMTypeRef llvm_elem = lb_type(m, elem);
  1218. LLVMValueRef args[2] = {};
  1219. isize args_count = 0;
  1220. char const *name = nullptr;
  1221. switch (builtin_id) {
  1222. case BuiltinProc_simd_reduce_add_ordered:
  1223. if (is_float) {
  1224. name = "llvm.vector.reduce.fadd";
  1225. args[args_count++] = LLVMConstReal(llvm_elem, 0.0);
  1226. } else {
  1227. name = "llvm.vector.reduce.add";
  1228. }
  1229. break;
  1230. case BuiltinProc_simd_reduce_mul_ordered:
  1231. if (is_float) {
  1232. name = "llvm.vector.reduce.fmul";
  1233. args[args_count++] = LLVMConstReal(llvm_elem, 1.0);
  1234. } else {
  1235. name = "llvm.vector.reduce.mul";
  1236. }
  1237. break;
  1238. }
  1239. args[args_count++] = arg0.value;
  1240. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1241. res.value = lb_call_intrinsic(p, name, args, cast(unsigned)args_count, types, gb_count_of(types));
  1242. return res;
  1243. }
  1244. case BuiltinProc_simd_reduce_min:
  1245. case BuiltinProc_simd_reduce_max:
  1246. case BuiltinProc_simd_reduce_and:
  1247. case BuiltinProc_simd_reduce_or:
  1248. case BuiltinProc_simd_reduce_xor:
  1249. {
  1250. char const *name = nullptr;
  1251. switch (builtin_id) {
  1252. case BuiltinProc_simd_reduce_min:
  1253. if (is_float) {
  1254. name = "llvm.vector.reduce.fmin";
  1255. } else if (is_signed) {
  1256. name = "llvm.vector.reduce.smin";
  1257. } else {
  1258. name = "llvm.vector.reduce.umin";
  1259. }
  1260. break;
  1261. case BuiltinProc_simd_reduce_max:
  1262. if (is_float) {
  1263. name = "llvm.vector.reduce.fmax";
  1264. } else if (is_signed) {
  1265. name = "llvm.vector.reduce.smax";
  1266. } else {
  1267. name = "llvm.vector.reduce.umax";
  1268. }
  1269. break;
  1270. case BuiltinProc_simd_reduce_and: name = "llvm.vector.reduce.and"; break;
  1271. case BuiltinProc_simd_reduce_or: name = "llvm.vector.reduce.or"; break;
  1272. case BuiltinProc_simd_reduce_xor: name = "llvm.vector.reduce.xor"; break;
  1273. }
  1274. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1275. LLVMValueRef args[1] = { arg0.value };
  1276. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1277. return res;
  1278. }
  1279. case BuiltinProc_simd_shuffle:
  1280. {
  1281. Type *vt = arg0.type;
  1282. GB_ASSERT(vt->kind == Type_SimdVector);
  1283. i64 indices_count = ce->args.count-2;
  1284. i64 max_count = vt->SimdVector.count*2;
  1285. GB_ASSERT(indices_count <= max_count);
  1286. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, indices_count);
  1287. for (isize i = 0; i < indices_count; i++) {
  1288. lbValue idx = lb_build_expr(p, ce->args[i+2]);
  1289. GB_ASSERT(LLVMIsConstant(idx.value));
  1290. values[i] = idx.value;
  1291. }
  1292. LLVMValueRef indices = LLVMConstVector(values, cast(unsigned)indices_count);
  1293. res.value = LLVMBuildShuffleVector(p->builder, arg0.value, arg1.value, indices, "");
  1294. return res;
  1295. }
  1296. case BuiltinProc_simd_select:
  1297. {
  1298. LLVMValueRef cond = arg0.value;
  1299. LLVMValueRef x = lb_build_expr(p, ce->args[1]).value;
  1300. LLVMValueRef y = lb_build_expr(p, ce->args[2]).value;
  1301. cond = LLVMBuildICmp(p->builder, LLVMIntNE, cond, LLVMConstNull(LLVMTypeOf(cond)), "");
  1302. res.value = LLVMBuildSelect(p->builder, cond, x, y, "");
  1303. return res;
  1304. }
  1305. case BuiltinProc_simd_ceil:
  1306. case BuiltinProc_simd_floor:
  1307. case BuiltinProc_simd_trunc:
  1308. case BuiltinProc_simd_nearest:
  1309. {
  1310. char const *name = nullptr;
  1311. switch (builtin_id) {
  1312. case BuiltinProc_simd_ceil: name = "llvm.ceil"; break;
  1313. case BuiltinProc_simd_floor: name = "llvm.floor"; break;
  1314. case BuiltinProc_simd_trunc: name = "llvm.trunc"; break;
  1315. case BuiltinProc_simd_nearest: name = "llvm.nearbyint"; break;
  1316. }
  1317. LLVMTypeRef types[1] = { lb_type(p->module, arg0.type) };
  1318. LLVMValueRef args[1] = { arg0.value };
  1319. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1320. return res;
  1321. }
  1322. case BuiltinProc_simd_lanes_reverse:
  1323. {
  1324. i64 count = get_array_type_count(arg0.type);
  1325. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1326. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1327. for (i64 i = 0; i < count; i++) {
  1328. values[i] = LLVMConstInt(llvm_u32, count-1-i, false);
  1329. }
  1330. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1331. LLVMValueRef v = arg0.value;
  1332. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1333. return res;
  1334. }
  1335. case BuiltinProc_simd_lanes_rotate_left:
  1336. case BuiltinProc_simd_lanes_rotate_right:
  1337. {
  1338. i64 count = get_array_type_count(arg0.type);
  1339. GB_ASSERT(is_power_of_two(count));
  1340. BigInt bi_count = {};
  1341. big_int_from_i64(&bi_count, count);
  1342. TypeAndValue const &tv = ce->args[1]->tav;
  1343. ExactValue val = exact_value_to_integer(tv.value);
  1344. GB_ASSERT(val.kind == ExactValue_Integer);
  1345. BigInt *bi = &val.value_integer;
  1346. if (builtin_id == BuiltinProc_simd_lanes_rotate_right) {
  1347. big_int_neg(bi, bi);
  1348. }
  1349. big_int_rem(bi, bi, &bi_count);
  1350. big_int_dealloc(&bi_count);
  1351. i64 left = big_int_to_i64(bi);
  1352. LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, count);
  1353. LLVMTypeRef llvm_u32 = lb_type(m, t_u32);
  1354. for (i64 i = 0; i < count; i++) {
  1355. u64 idx = cast(u64)(i+left) & cast(u64)(count-1);
  1356. values[i] = LLVMConstInt(llvm_u32, idx, false);
  1357. }
  1358. LLVMValueRef mask = LLVMConstVector(values, cast(unsigned)count);
  1359. LLVMValueRef v = arg0.value;
  1360. res.value = LLVMBuildShuffleVector(p->builder, v, v, mask, "");
  1361. return res;
  1362. }
  1363. case BuiltinProc_simd_add_sat:
  1364. case BuiltinProc_simd_sub_sat:
  1365. {
  1366. char const *name = nullptr;
  1367. switch (builtin_id) {
  1368. case BuiltinProc_simd_add_sat: name = is_signed ? "llvm.sadd.sat" : "llvm.uadd.sat"; break;
  1369. case BuiltinProc_simd_sub_sat: name = is_signed ? "llvm.ssub.sat" : "llvm.usub.sat"; break;
  1370. }
  1371. LLVMTypeRef types[1] = {lb_type(p->module, arg0.type)};
  1372. LLVMValueRef args[2] = { arg0.value, arg1.value };
  1373. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1374. return res;
  1375. }
  1376. case BuiltinProc_simd_clamp:
  1377. {
  1378. LLVMValueRef v = arg0.value;
  1379. LLVMValueRef min = arg1.value;
  1380. LLVMValueRef max = arg2.value;
  1381. if (is_float) {
  1382. v = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOLT, v, min, ""), min, v, "");
  1383. res.value = LLVMBuildSelect(p->builder, LLVMBuildFCmp(p->builder, LLVMRealOGT, v, max, ""), max, v, "");
  1384. } else if (is_signed) {
  1385. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSLT, v, min, ""), min, v, "");
  1386. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntSGT, v, max, ""), max, v, "");
  1387. } else {
  1388. v = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntULT, v, min, ""), min, v, "");
  1389. res.value = LLVMBuildSelect(p->builder, LLVMBuildICmp(p->builder, LLVMIntUGT, v, max, ""), max, v, "");
  1390. }
  1391. return res;
  1392. }
  1393. case BuiltinProc_simd_to_bits:
  1394. {
  1395. res.value = LLVMBuildBitCast(p->builder, arg0.value, lb_type(m, tv.type), "");
  1396. return res;
  1397. }
  1398. }
  1399. GB_PANIC("Unhandled simd intrinsic: '%.*s'", LIT(builtin_procs[builtin_id].name));
  1400. return {};
  1401. }
  1402. gb_internal lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) {
  1403. ast_node(ce, CallExpr, expr);
  1404. if (BuiltinProc__simd_begin < id && id < BuiltinProc__simd_end) {
  1405. return lb_build_builtin_simd_proc(p, expr, tv, id);
  1406. }
  1407. switch (id) {
  1408. case BuiltinProc_DIRECTIVE: {
  1409. ast_node(bd, BasicDirective, ce->proc);
  1410. String name = bd->name.string;
  1411. GB_ASSERT(name == "location");
  1412. String procedure = p->entity->token.string;
  1413. TokenPos pos = ast_token(ce->proc).pos;
  1414. if (ce->args.count > 0) {
  1415. Ast *ident = unselector_expr(ce->args[0]);
  1416. GB_ASSERT(ident->kind == Ast_Ident);
  1417. Entity *e = entity_of_node(ident);
  1418. GB_ASSERT(e != nullptr);
  1419. if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) {
  1420. procedure = e->parent_proc_decl->entity->token.string;
  1421. } else {
  1422. procedure = str_lit("");
  1423. }
  1424. pos = e->token.pos;
  1425. }
  1426. return lb_emit_source_code_location_as_global(p, procedure, pos);
  1427. }
  1428. case BuiltinProc_type_info_of: {
  1429. Ast *arg = ce->args[0];
  1430. TypeAndValue tav = type_and_value_of_expr(arg);
  1431. if (tav.mode == Addressing_Type) {
  1432. Type *t = default_type(type_of_expr(arg));
  1433. return lb_type_info(p->module, t);
  1434. }
  1435. GB_ASSERT(is_type_typeid(tav.type));
  1436. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1437. args[0] = lb_build_expr(p, arg);
  1438. return lb_emit_runtime_call(p, "__type_info_of", args);
  1439. }
  1440. case BuiltinProc_typeid_of: {
  1441. Ast *arg = ce->args[0];
  1442. TypeAndValue tav = type_and_value_of_expr(arg);
  1443. GB_ASSERT(tav.mode == Addressing_Type);
  1444. Type *t = default_type(type_of_expr(arg));
  1445. return lb_typeid(p->module, t);
  1446. }
  1447. case BuiltinProc_len: {
  1448. lbValue v = lb_build_expr(p, ce->args[0]);
  1449. Type *t = base_type(v.type);
  1450. if (is_type_pointer(t)) {
  1451. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  1452. v = lb_emit_load(p, v);
  1453. t = type_deref(t);
  1454. }
  1455. if (is_type_cstring(t)) {
  1456. return lb_cstring_len(p, v);
  1457. } else if (is_type_string(t)) {
  1458. return lb_string_len(p, v);
  1459. } else if (is_type_array(t)) {
  1460. GB_PANIC("Array lengths are constant");
  1461. } else if (is_type_slice(t) || is_type_relative_slice(t)) {
  1462. return lb_slice_len(p, v);
  1463. } else if (is_type_dynamic_array(t)) {
  1464. return lb_dynamic_array_len(p, v);
  1465. } else if (is_type_map(t)) {
  1466. return lb_map_len(p, v);
  1467. } else if (is_type_soa_struct(t)) {
  1468. return lb_soa_struct_len(p, v);
  1469. }
  1470. GB_PANIC("Unreachable");
  1471. break;
  1472. }
  1473. case BuiltinProc_cap: {
  1474. lbValue v = lb_build_expr(p, ce->args[0]);
  1475. Type *t = base_type(v.type);
  1476. if (is_type_pointer(t)) {
  1477. // IMPORTANT TODO(bill): Should there be a nil pointer check?
  1478. v = lb_emit_load(p, v);
  1479. t = type_deref(t);
  1480. }
  1481. if (is_type_string(t)) {
  1482. GB_PANIC("Unreachable");
  1483. } else if (is_type_array(t)) {
  1484. GB_PANIC("Array lengths are constant");
  1485. } else if (is_type_slice(t) || is_type_relative_slice(t)) {
  1486. return lb_slice_len(p, v);
  1487. } else if (is_type_dynamic_array(t)) {
  1488. return lb_dynamic_array_cap(p, v);
  1489. } else if (is_type_map(t)) {
  1490. return lb_map_cap(p, v);
  1491. } else if (is_type_soa_struct(t)) {
  1492. return lb_soa_struct_cap(p, v);
  1493. }
  1494. GB_PANIC("Unreachable");
  1495. break;
  1496. }
  1497. case BuiltinProc_swizzle: {
  1498. isize index_count = ce->args.count-1;
  1499. if (is_type_simd_vector(tv.type)) {
  1500. lbValue vec = lb_build_expr(p, ce->args[0]);
  1501. if (index_count == 0) {
  1502. return vec;
  1503. }
  1504. unsigned mask_len = cast(unsigned)index_count;
  1505. LLVMValueRef *mask_elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, index_count);
  1506. for (isize i = 1; i < ce->args.count; i++) {
  1507. TypeAndValue tv = type_and_value_of_expr(ce->args[i]);
  1508. GB_ASSERT(is_type_integer(tv.type));
  1509. GB_ASSERT(tv.value.kind == ExactValue_Integer);
  1510. u32 index = cast(u32)big_int_to_i64(&tv.value.value_integer);
  1511. mask_elems[i-1] = LLVMConstInt(lb_type(p->module, t_u32), index, false);
  1512. }
  1513. LLVMValueRef mask = LLVMConstVector(mask_elems, mask_len);
  1514. LLVMValueRef v1 = vec.value;
  1515. LLVMValueRef v2 = vec.value;
  1516. lbValue res = {};
  1517. res.type = tv.type;
  1518. res.value = LLVMBuildShuffleVector(p->builder, v1, v2, mask, "");
  1519. return res;
  1520. }
  1521. lbAddr addr = lb_build_array_swizzle_addr(p, ce, tv);
  1522. return lb_addr_load(p, addr);
  1523. }
  1524. case BuiltinProc_complex: {
  1525. lbValue real = lb_build_expr(p, ce->args[0]);
  1526. lbValue imag = lb_build_expr(p, ce->args[1]);
  1527. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1528. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1529. Type *ft = base_complex_elem_type(tv.type);
  1530. real = lb_emit_conv(p, real, ft);
  1531. imag = lb_emit_conv(p, imag, ft);
  1532. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real);
  1533. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag);
  1534. return lb_emit_load(p, dst);
  1535. }
  1536. case BuiltinProc_quaternion: {
  1537. lbValue real = lb_build_expr(p, ce->args[0]);
  1538. lbValue imag = lb_build_expr(p, ce->args[1]);
  1539. lbValue jmag = lb_build_expr(p, ce->args[2]);
  1540. lbValue kmag = lb_build_expr(p, ce->args[3]);
  1541. // @QuaternionLayout
  1542. lbAddr dst_addr = lb_add_local_generated(p, tv.type, false);
  1543. lbValue dst = lb_addr_get_ptr(p, dst_addr);
  1544. Type *ft = base_complex_elem_type(tv.type);
  1545. real = lb_emit_conv(p, real, ft);
  1546. imag = lb_emit_conv(p, imag, ft);
  1547. jmag = lb_emit_conv(p, jmag, ft);
  1548. kmag = lb_emit_conv(p, kmag, ft);
  1549. lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real);
  1550. lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag);
  1551. lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag);
  1552. lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag);
  1553. return lb_emit_load(p, dst);
  1554. }
  1555. case BuiltinProc_real: {
  1556. lbValue val = lb_build_expr(p, ce->args[0]);
  1557. if (is_type_complex(val.type)) {
  1558. lbValue real = lb_emit_struct_ev(p, val, 0);
  1559. return lb_emit_conv(p, real, tv.type);
  1560. } else if (is_type_quaternion(val.type)) {
  1561. // @QuaternionLayout
  1562. lbValue real = lb_emit_struct_ev(p, val, 3);
  1563. return lb_emit_conv(p, real, tv.type);
  1564. }
  1565. GB_PANIC("invalid type for real");
  1566. return {};
  1567. }
  1568. case BuiltinProc_imag: {
  1569. lbValue val = lb_build_expr(p, ce->args[0]);
  1570. if (is_type_complex(val.type)) {
  1571. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1572. return lb_emit_conv(p, imag, tv.type);
  1573. } else if (is_type_quaternion(val.type)) {
  1574. // @QuaternionLayout
  1575. lbValue imag = lb_emit_struct_ev(p, val, 0);
  1576. return lb_emit_conv(p, imag, tv.type);
  1577. }
  1578. GB_PANIC("invalid type for imag");
  1579. return {};
  1580. }
  1581. case BuiltinProc_jmag: {
  1582. lbValue val = lb_build_expr(p, ce->args[0]);
  1583. if (is_type_quaternion(val.type)) {
  1584. // @QuaternionLayout
  1585. lbValue imag = lb_emit_struct_ev(p, val, 1);
  1586. return lb_emit_conv(p, imag, tv.type);
  1587. }
  1588. GB_PANIC("invalid type for jmag");
  1589. return {};
  1590. }
  1591. case BuiltinProc_kmag: {
  1592. lbValue val = lb_build_expr(p, ce->args[0]);
  1593. if (is_type_quaternion(val.type)) {
  1594. // @QuaternionLayout
  1595. lbValue imag = lb_emit_struct_ev(p, val, 2);
  1596. return lb_emit_conv(p, imag, tv.type);
  1597. }
  1598. GB_PANIC("invalid type for kmag");
  1599. return {};
  1600. }
  1601. case BuiltinProc_conj: {
  1602. lbValue val = lb_build_expr(p, ce->args[0]);
  1603. return lb_emit_conjugate(p, val, tv.type);
  1604. }
  1605. case BuiltinProc_expand_values: {
  1606. lbValue val = lb_build_expr(p, ce->args[0]);
  1607. Type *t = base_type(val.type);
  1608. if (!is_type_tuple(tv.type)) {
  1609. if (t->kind == Type_Struct) {
  1610. GB_ASSERT(t->Struct.fields.count == 1);
  1611. return lb_emit_struct_ev(p, val, 0);
  1612. } else if (t->kind == Type_Array) {
  1613. GB_ASSERT(t->Array.count == 1);
  1614. return lb_emit_struct_ev(p, val, 0);
  1615. } else {
  1616. GB_PANIC("Unknown type of expand_values");
  1617. }
  1618. }
  1619. GB_ASSERT(is_type_tuple(tv.type));
  1620. // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops
  1621. lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false));
  1622. if (t->kind == Type_Struct) {
  1623. for_array(src_index, t->Struct.fields) {
  1624. Entity *field = t->Struct.fields[src_index];
  1625. i32 field_index = field->Variable.field_index;
  1626. lbValue f = lb_emit_struct_ev(p, val, field_index);
  1627. lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index);
  1628. lb_emit_store(p, ep, f);
  1629. }
  1630. } else if (is_type_array_like(t)) {
  1631. // TODO(bill): Clean-up this code
  1632. lbValue ap = lb_address_from_load_or_generate_local(p, val);
  1633. i32 n = cast(i32)get_array_type_count(t);
  1634. for (i32 i = 0; i < n; i++) {
  1635. lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i));
  1636. lbValue ep = lb_emit_struct_ep(p, tuple, i);
  1637. lb_emit_store(p, ep, f);
  1638. }
  1639. } else {
  1640. GB_PANIC("Unknown type of expand_values");
  1641. }
  1642. return lb_emit_load(p, tuple);
  1643. }
  1644. case BuiltinProc_min: {
  1645. Type *t = type_of_expr(expr);
  1646. if (ce->args.count == 2) {
  1647. return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1648. } else {
  1649. lbValue x = lb_build_expr(p, ce->args[0]);
  1650. for (isize i = 1; i < ce->args.count; i++) {
  1651. x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i]));
  1652. }
  1653. return x;
  1654. }
  1655. }
  1656. case BuiltinProc_max: {
  1657. Type *t = type_of_expr(expr);
  1658. if (ce->args.count == 2) {
  1659. return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1]));
  1660. } else {
  1661. lbValue x = lb_build_expr(p, ce->args[0]);
  1662. for (isize i = 1; i < ce->args.count; i++) {
  1663. x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i]));
  1664. }
  1665. return x;
  1666. }
  1667. }
  1668. case BuiltinProc_abs: {
  1669. lbValue x = lb_build_expr(p, ce->args[0]);
  1670. Type *t = x.type;
  1671. if (is_type_unsigned(t)) {
  1672. return x;
  1673. }
  1674. if (is_type_quaternion(t)) {
  1675. i64 sz = 8*type_size_of(t);
  1676. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1677. args[0] = x;
  1678. switch (sz) {
  1679. case 64: return lb_emit_runtime_call(p, "abs_quaternion64", args);
  1680. case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args);
  1681. case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args);
  1682. }
  1683. GB_PANIC("Unknown complex type");
  1684. } else if (is_type_complex(t)) {
  1685. i64 sz = 8*type_size_of(t);
  1686. auto args = array_make<lbValue>(permanent_allocator(), 1);
  1687. args[0] = x;
  1688. switch (sz) {
  1689. case 32: return lb_emit_runtime_call(p, "abs_complex32", args);
  1690. case 64: return lb_emit_runtime_call(p, "abs_complex64", args);
  1691. case 128: return lb_emit_runtime_call(p, "abs_complex128", args);
  1692. }
  1693. GB_PANIC("Unknown complex type");
  1694. }
  1695. lbValue zero = lb_const_nil(p->module, t);
  1696. lbValue cond = lb_emit_comp(p, Token_Lt, x, zero);
  1697. lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t);
  1698. return lb_emit_select(p, cond, neg, x);
  1699. }
  1700. case BuiltinProc_clamp:
  1701. return lb_emit_clamp(p, type_of_expr(expr),
  1702. lb_build_expr(p, ce->args[0]),
  1703. lb_build_expr(p, ce->args[1]),
  1704. lb_build_expr(p, ce->args[2]));
  1705. case BuiltinProc_soa_zip:
  1706. return lb_soa_zip(p, ce, tv);
  1707. case BuiltinProc_soa_unzip:
  1708. return lb_soa_unzip(p, ce, tv);
  1709. case BuiltinProc_transpose:
  1710. {
  1711. lbValue m = lb_build_expr(p, ce->args[0]);
  1712. return lb_emit_matrix_tranpose(p, m, tv.type);
  1713. }
  1714. case BuiltinProc_outer_product:
  1715. {
  1716. lbValue a = lb_build_expr(p, ce->args[0]);
  1717. lbValue b = lb_build_expr(p, ce->args[1]);
  1718. return lb_emit_outer_product(p, a, b, tv.type);
  1719. }
  1720. case BuiltinProc_hadamard_product:
  1721. {
  1722. lbValue a = lb_build_expr(p, ce->args[0]);
  1723. lbValue b = lb_build_expr(p, ce->args[1]);
  1724. if (is_type_array(tv.type)) {
  1725. return lb_emit_arith(p, Token_Mul, a, b, tv.type);
  1726. }
  1727. GB_ASSERT(is_type_matrix(tv.type));
  1728. return lb_emit_arith_matrix(p, Token_Mul, a, b, tv.type, true);
  1729. }
  1730. case BuiltinProc_matrix_flatten:
  1731. {
  1732. lbValue m = lb_build_expr(p, ce->args[0]);
  1733. return lb_emit_matrix_flatten(p, m, tv.type);
  1734. }
  1735. case BuiltinProc_unreachable:
  1736. lb_emit_unreachable(p);
  1737. return {};
  1738. case BuiltinProc_raw_data:
  1739. {
  1740. lbValue x = lb_build_expr(p, ce->args[0]);
  1741. Type *t = base_type(x.type);
  1742. lbValue res = {};
  1743. switch (t->kind) {
  1744. case Type_Slice:
  1745. res = lb_slice_elem(p, x);
  1746. res = lb_emit_conv(p, res, tv.type);
  1747. break;
  1748. case Type_DynamicArray:
  1749. res = lb_dynamic_array_elem(p, x);
  1750. res = lb_emit_conv(p, res, tv.type);
  1751. break;
  1752. case Type_Basic:
  1753. if (t->Basic.kind == Basic_string) {
  1754. res = lb_string_elem(p, x);
  1755. res = lb_emit_conv(p, res, tv.type);
  1756. } else if (t->Basic.kind == Basic_cstring) {
  1757. res = lb_emit_conv(p, x, tv.type);
  1758. }
  1759. break;
  1760. case Type_Pointer:
  1761. case Type_MultiPointer:
  1762. res = lb_emit_conv(p, x, tv.type);
  1763. break;
  1764. }
  1765. GB_ASSERT(res.value != nullptr);
  1766. return res;
  1767. }
  1768. // "Intrinsics"
  1769. case BuiltinProc_alloca:
  1770. {
  1771. lbValue sz = lb_build_expr(p, ce->args[0]);
  1772. i64 al = exact_value_to_i64(type_and_value_of_expr(ce->args[1]).value);
  1773. lbValue res = {};
  1774. res.type = alloc_type_multi_pointer(t_u8);
  1775. res.value = LLVMBuildArrayAlloca(p->builder, lb_type(p->module, t_u8), sz.value, "");
  1776. LLVMSetAlignment(res.value, cast(unsigned)al);
  1777. return res;
  1778. }
  1779. case BuiltinProc_cpu_relax:
  1780. if (build_context.metrics.arch == TargetArch_i386 ||
  1781. build_context.metrics.arch == TargetArch_amd64) {
  1782. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1783. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("pause"), {}, true);
  1784. GB_ASSERT(the_asm != nullptr);
  1785. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1786. } else if (build_context.metrics.arch == TargetArch_arm64) {
  1787. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1788. // NOTE(bill, 2022-03-30): `isb` appears to a better option that `yield`
  1789. // See: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8258604
  1790. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("isb"), {}, true);
  1791. GB_ASSERT(the_asm != nullptr);
  1792. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1793. } else {
  1794. // NOTE: default to something to prevent optimization
  1795. LLVMTypeRef func_type = LLVMFunctionType(LLVMVoidTypeInContext(p->module->ctx), nullptr, 0, false);
  1796. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit(""), {}, true);
  1797. GB_ASSERT(the_asm != nullptr);
  1798. LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1799. }
  1800. return {};
  1801. case BuiltinProc_debug_trap:
  1802. case BuiltinProc_trap:
  1803. {
  1804. char const *name = nullptr;
  1805. switch (id) {
  1806. case BuiltinProc_debug_trap: name = "llvm.debugtrap"; break;
  1807. case BuiltinProc_trap: name = "llvm.trap"; break;
  1808. }
  1809. lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1810. if (id == BuiltinProc_trap) {
  1811. LLVMBuildUnreachable(p->builder);
  1812. }
  1813. return {};
  1814. }
  1815. case BuiltinProc_read_cycle_counter:
  1816. {
  1817. lbValue res = {};
  1818. res.type = tv.type;
  1819. if (build_context.metrics.arch == TargetArch_arm64) {
  1820. LLVMTypeRef func_type = LLVMFunctionType(LLVMInt64TypeInContext(p->module->ctx), nullptr, 0, false);
  1821. bool has_side_effects = false;
  1822. LLVMValueRef the_asm = llvm_get_inline_asm(func_type, str_lit("mrs x9, cntvct_el0"), str_lit("=r"), has_side_effects);
  1823. GB_ASSERT(the_asm != nullptr);
  1824. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, nullptr, 0, "");
  1825. } else {
  1826. char const *name = "llvm.readcyclecounter";
  1827. res.value = lb_call_intrinsic(p, name, nullptr, 0, nullptr, 0);
  1828. }
  1829. return res;
  1830. }
  1831. case BuiltinProc_count_trailing_zeros:
  1832. return lb_emit_count_trailing_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1833. case BuiltinProc_count_leading_zeros:
  1834. return lb_emit_count_leading_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1835. case BuiltinProc_count_ones:
  1836. return lb_emit_count_ones(p, lb_build_expr(p, ce->args[0]), tv.type);
  1837. case BuiltinProc_count_zeros:
  1838. return lb_emit_count_zeros(p, lb_build_expr(p, ce->args[0]), tv.type);
  1839. case BuiltinProc_reverse_bits:
  1840. return lb_emit_reverse_bits(p, lb_build_expr(p, ce->args[0]), tv.type);
  1841. case BuiltinProc_byte_swap:
  1842. {
  1843. lbValue x = lb_build_expr(p, ce->args[0]);
  1844. x = lb_emit_conv(p, x, tv.type);
  1845. return lb_emit_byte_swap(p, x, tv.type);
  1846. }
  1847. case BuiltinProc_overflow_add:
  1848. case BuiltinProc_overflow_sub:
  1849. case BuiltinProc_overflow_mul:
  1850. {
  1851. Type *main_type = tv.type;
  1852. Type *type = main_type;
  1853. if (is_type_tuple(main_type)) {
  1854. type = main_type->Tuple.variables[0]->type;
  1855. }
  1856. lbValue x = lb_build_expr(p, ce->args[0]);
  1857. lbValue y = lb_build_expr(p, ce->args[1]);
  1858. x = lb_emit_conv(p, x, type);
  1859. y = lb_emit_conv(p, y, type);
  1860. char const *name = nullptr;
  1861. if (is_type_unsigned(type)) {
  1862. switch (id) {
  1863. case BuiltinProc_overflow_add: name = "llvm.uadd.with.overflow"; break;
  1864. case BuiltinProc_overflow_sub: name = "llvm.usub.with.overflow"; break;
  1865. case BuiltinProc_overflow_mul: name = "llvm.umul.with.overflow"; break;
  1866. }
  1867. } else {
  1868. switch (id) {
  1869. case BuiltinProc_overflow_add: name = "llvm.sadd.with.overflow"; break;
  1870. case BuiltinProc_overflow_sub: name = "llvm.ssub.with.overflow"; break;
  1871. case BuiltinProc_overflow_mul: name = "llvm.smul.with.overflow"; break;
  1872. }
  1873. }
  1874. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1875. LLVMValueRef args[2] = { x.value, y.value };
  1876. lbValue res = {};
  1877. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1878. if (is_type_tuple(main_type)) {
  1879. Type *res_type = nullptr;
  1880. gbAllocator a = permanent_allocator();
  1881. res_type = alloc_type_tuple();
  1882. slice_init(&res_type->Tuple.variables, a, 2);
  1883. res_type->Tuple.variables[0] = alloc_entity_field(nullptr, blank_token, type, false, 0);
  1884. res_type->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  1885. res.type = res_type;
  1886. } else {
  1887. res.value = LLVMBuildExtractValue(p->builder, res.value, 0, "");
  1888. res.type = type;
  1889. }
  1890. return res;
  1891. }
  1892. case BuiltinProc_sqrt:
  1893. {
  1894. Type *type = tv.type;
  1895. lbValue x = lb_build_expr(p, ce->args[0]);
  1896. x = lb_emit_conv(p, x, type);
  1897. char const *name = "llvm.sqrt";
  1898. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1899. LLVMValueRef args[1] = { x.value };
  1900. lbValue res = {};
  1901. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1902. res.type = type;
  1903. return res;
  1904. }
  1905. case BuiltinProc_fused_mul_add:
  1906. {
  1907. Type *type = tv.type;
  1908. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), type);
  1909. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), type);
  1910. lbValue z = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), type);
  1911. char const *name = "llvm.fma";
  1912. LLVMTypeRef types[1] = {lb_type(p->module, type)};
  1913. LLVMValueRef args[3] = { x.value, y.value, z.value };
  1914. lbValue res = {};
  1915. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  1916. res.type = type;
  1917. return res;
  1918. }
  1919. case BuiltinProc_mem_copy:
  1920. {
  1921. lbValue dst = lb_build_expr(p, ce->args[0]);
  1922. lbValue src = lb_build_expr(p, ce->args[1]);
  1923. lbValue len = lb_build_expr(p, ce->args[2]);
  1924. lb_mem_copy_overlapping(p, dst, src, len, false);
  1925. return {};
  1926. }
  1927. case BuiltinProc_mem_copy_non_overlapping:
  1928. {
  1929. lbValue dst = lb_build_expr(p, ce->args[0]);
  1930. lbValue src = lb_build_expr(p, ce->args[1]);
  1931. lbValue len = lb_build_expr(p, ce->args[2]);
  1932. lb_mem_copy_non_overlapping(p, dst, src, len, false);
  1933. return {};
  1934. }
  1935. case BuiltinProc_mem_zero:
  1936. {
  1937. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1938. lbValue len = lb_build_expr(p, ce->args[1]);
  1939. ptr = lb_emit_conv(p, ptr, t_rawptr);
  1940. len = lb_emit_conv(p, len, t_int);
  1941. unsigned alignment = 1;
  1942. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, false);
  1943. return {};
  1944. }
  1945. case BuiltinProc_mem_zero_volatile:
  1946. {
  1947. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1948. lbValue len = lb_build_expr(p, ce->args[1]);
  1949. ptr = lb_emit_conv(p, ptr, t_rawptr);
  1950. len = lb_emit_conv(p, len, t_int);
  1951. unsigned alignment = 1;
  1952. lb_mem_zero_ptr_internal(p, ptr.value, len.value, alignment, true);
  1953. return {};
  1954. }
  1955. case BuiltinProc_ptr_offset:
  1956. {
  1957. lbValue ptr = lb_build_expr(p, ce->args[0]);
  1958. lbValue len = lb_build_expr(p, ce->args[1]);
  1959. len = lb_emit_conv(p, len, t_int);
  1960. return lb_emit_ptr_offset(p, ptr, len);
  1961. }
  1962. case BuiltinProc_ptr_sub:
  1963. {
  1964. Type *elem0 = type_deref(type_of_expr(ce->args[0]));
  1965. Type *elem1 = type_deref(type_of_expr(ce->args[1]));
  1966. GB_ASSERT(are_types_identical(elem0, elem1));
  1967. Type *elem = elem0;
  1968. lbValue ptr0 = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr);
  1969. lbValue ptr1 = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr);
  1970. lbValue diff = lb_emit_arith(p, Token_Sub, ptr0, ptr1, t_uintptr);
  1971. diff = lb_emit_conv(p, diff, t_int);
  1972. return lb_emit_arith(p, Token_Quo, diff, lb_const_int(p->module, t_int, type_size_of(elem)), t_int);
  1973. }
  1974. // TODO(bill): Which is correct?
  1975. case BuiltinProc_atomic_thread_fence:
  1976. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), false, "");
  1977. return {};
  1978. case BuiltinProc_atomic_signal_fence:
  1979. LLVMBuildFence(p->builder, llvm_atomic_ordering_from_odin(ce->args[0]), true, "");
  1980. return {};
  1981. case BuiltinProc_volatile_store:
  1982. case BuiltinProc_non_temporal_store:
  1983. case BuiltinProc_atomic_store:
  1984. case BuiltinProc_atomic_store_explicit: {
  1985. lbValue dst = lb_build_expr(p, ce->args[0]);
  1986. lbValue val = lb_build_expr(p, ce->args[1]);
  1987. val = lb_emit_conv(p, val, type_deref(dst.type));
  1988. LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value);
  1989. switch (id) {
  1990. case BuiltinProc_non_temporal_store:
  1991. {
  1992. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  1993. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  1994. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  1995. }
  1996. break;
  1997. case BuiltinProc_volatile_store: LLVMSetVolatile(instr, true); break;
  1998. case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  1999. case BuiltinProc_atomic_store_explicit:
  2000. {
  2001. auto ordering = llvm_atomic_ordering_from_odin(ce->args[2]);
  2002. LLVMSetOrdering(instr, ordering);
  2003. if (ordering == LLVMAtomicOrderingUnordered) {
  2004. LLVMSetVolatile(instr, true);
  2005. }
  2006. }
  2007. break;
  2008. }
  2009. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2010. return {};
  2011. }
  2012. case BuiltinProc_volatile_load:
  2013. case BuiltinProc_non_temporal_load:
  2014. case BuiltinProc_atomic_load:
  2015. case BuiltinProc_atomic_load_explicit: {
  2016. lbValue dst = lb_build_expr(p, ce->args[0]);
  2017. LLVMValueRef instr = LLVMBuildLoad2(p->builder, lb_type(p->module, type_deref(dst.type)), dst.value, "");
  2018. switch (id) {
  2019. case BuiltinProc_non_temporal_load:
  2020. {
  2021. unsigned kind_id = LLVMGetMDKindIDInContext(p->module->ctx, "nontemporal", 11);
  2022. LLVMMetadataRef node = LLVMValueAsMetadata(LLVMConstInt(lb_type(p->module, t_u32), 1, false));
  2023. LLVMSetMetadata(instr, kind_id, LLVMMetadataAsValue(p->module->ctx, node));
  2024. }
  2025. break;
  2026. break;
  2027. case BuiltinProc_volatile_load: LLVMSetVolatile(instr, true); break;
  2028. case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break;
  2029. case BuiltinProc_atomic_load_explicit:
  2030. {
  2031. auto ordering = llvm_atomic_ordering_from_odin(ce->args[1]);
  2032. LLVMSetOrdering(instr, ordering);
  2033. if (ordering == LLVMAtomicOrderingUnordered) {
  2034. LLVMSetVolatile(instr, true);
  2035. }
  2036. }
  2037. break;
  2038. }
  2039. LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type)));
  2040. lbValue res = {};
  2041. res.value = instr;
  2042. res.type = type_deref(dst.type);
  2043. return res;
  2044. }
  2045. case BuiltinProc_unaligned_store:
  2046. {
  2047. lbValue dst = lb_build_expr(p, ce->args[0]);
  2048. lbValue src = lb_build_expr(p, ce->args[1]);
  2049. Type *t = type_deref(dst.type);
  2050. if (is_type_simd_vector(t)) {
  2051. LLVMValueRef store = LLVMBuildStore(p->builder, src.value, dst.value);
  2052. LLVMSetAlignment(store, 1);
  2053. } else {
  2054. src = lb_address_from_load_or_generate_local(p, src);
  2055. lb_mem_copy_non_overlapping(p, dst, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2056. }
  2057. return {};
  2058. }
  2059. case BuiltinProc_unaligned_load:
  2060. {
  2061. lbValue src = lb_build_expr(p, ce->args[0]);
  2062. Type *t = type_deref(src.type);
  2063. if (is_type_simd_vector(t)) {
  2064. lbValue res = {};
  2065. res.type = t;
  2066. res.value = LLVMBuildLoad2(p->builder, lb_type(p->module, t), src.value, "");
  2067. LLVMSetAlignment(res.value, 1);
  2068. return res;
  2069. } else {
  2070. lbAddr dst = lb_add_local_generated(p, t, false);
  2071. lb_mem_copy_non_overlapping(p, dst.addr, src, lb_const_int(p->module, t_int, type_size_of(t)), false);
  2072. return lb_addr_load(p, dst);
  2073. }
  2074. }
  2075. case BuiltinProc_atomic_add:
  2076. case BuiltinProc_atomic_sub:
  2077. case BuiltinProc_atomic_and:
  2078. case BuiltinProc_atomic_nand:
  2079. case BuiltinProc_atomic_or:
  2080. case BuiltinProc_atomic_xor:
  2081. case BuiltinProc_atomic_exchange:
  2082. case BuiltinProc_atomic_add_explicit:
  2083. case BuiltinProc_atomic_sub_explicit:
  2084. case BuiltinProc_atomic_and_explicit:
  2085. case BuiltinProc_atomic_nand_explicit:
  2086. case BuiltinProc_atomic_or_explicit:
  2087. case BuiltinProc_atomic_xor_explicit:
  2088. case BuiltinProc_atomic_exchange_explicit: {
  2089. lbValue dst = lb_build_expr(p, ce->args[0]);
  2090. lbValue val = lb_build_expr(p, ce->args[1]);
  2091. val = lb_emit_conv(p, val, type_deref(dst.type));
  2092. LLVMAtomicRMWBinOp op = {};
  2093. LLVMAtomicOrdering ordering = {};
  2094. switch (id) {
  2095. case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2096. case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2097. case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2098. case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2099. case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2100. case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2101. case BuiltinProc_atomic_exchange: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break;
  2102. case BuiltinProc_atomic_add_explicit: op = LLVMAtomicRMWBinOpAdd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2103. case BuiltinProc_atomic_sub_explicit: op = LLVMAtomicRMWBinOpSub; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2104. case BuiltinProc_atomic_and_explicit: op = LLVMAtomicRMWBinOpAnd; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2105. case BuiltinProc_atomic_nand_explicit: op = LLVMAtomicRMWBinOpNand; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2106. case BuiltinProc_atomic_or_explicit: op = LLVMAtomicRMWBinOpOr; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2107. case BuiltinProc_atomic_xor_explicit: op = LLVMAtomicRMWBinOpXor; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2108. case BuiltinProc_atomic_exchange_explicit: op = LLVMAtomicRMWBinOpXchg; ordering = llvm_atomic_ordering_from_odin(ce->args[2]); break;
  2109. }
  2110. lbValue res = {};
  2111. res.value = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false);
  2112. res.type = tv.type;
  2113. if (ordering == LLVMAtomicOrderingUnordered) {
  2114. LLVMSetVolatile(res.value, true);
  2115. }
  2116. return res;
  2117. }
  2118. case BuiltinProc_atomic_compare_exchange_strong:
  2119. case BuiltinProc_atomic_compare_exchange_weak:
  2120. case BuiltinProc_atomic_compare_exchange_strong_explicit:
  2121. case BuiltinProc_atomic_compare_exchange_weak_explicit: {
  2122. lbValue address = lb_build_expr(p, ce->args[0]);
  2123. Type *elem = type_deref(address.type);
  2124. lbValue old_value = lb_build_expr(p, ce->args[1]);
  2125. lbValue new_value = lb_build_expr(p, ce->args[2]);
  2126. old_value = lb_emit_conv(p, old_value, elem);
  2127. new_value = lb_emit_conv(p, new_value, elem);
  2128. LLVMAtomicOrdering success_ordering = {};
  2129. LLVMAtomicOrdering failure_ordering = {};
  2130. LLVMBool weak = false;
  2131. switch (id) {
  2132. case BuiltinProc_atomic_compare_exchange_strong: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break;
  2133. case BuiltinProc_atomic_compare_exchange_weak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break;
  2134. case BuiltinProc_atomic_compare_exchange_strong_explicit: success_ordering = llvm_atomic_ordering_from_odin(ce->args[3]); failure_ordering = llvm_atomic_ordering_from_odin(ce->args[4]); weak = false; break;
  2135. case BuiltinProc_atomic_compare_exchange_weak_explicit: success_ordering = llvm_atomic_ordering_from_odin(ce->args[3]); failure_ordering = llvm_atomic_ordering_from_odin(ce->args[4]); weak = true; break;
  2136. }
  2137. LLVMBool single_threaded = false;
  2138. LLVMValueRef value = LLVMBuildAtomicCmpXchg(
  2139. p->builder, address.value,
  2140. old_value.value, new_value.value,
  2141. success_ordering,
  2142. failure_ordering,
  2143. single_threaded
  2144. );
  2145. LLVMSetWeak(value, weak);
  2146. if (success_ordering == LLVMAtomicOrderingUnordered || failure_ordering == LLVMAtomicOrderingUnordered) {
  2147. LLVMSetVolatile(value, true);
  2148. }
  2149. if (is_type_tuple(tv.type)) {
  2150. Type *fix_typed = alloc_type_tuple();
  2151. slice_init(&fix_typed->Tuple.variables, permanent_allocator(), 2);
  2152. fix_typed->Tuple.variables[0] = tv.type->Tuple.variables[0];
  2153. fix_typed->Tuple.variables[1] = alloc_entity_field(nullptr, blank_token, t_llvm_bool, false, 1);
  2154. lbValue res = {};
  2155. res.value = value;
  2156. res.type = fix_typed;
  2157. return res;
  2158. } else {
  2159. lbValue res = {};
  2160. res.value = LLVMBuildExtractValue(p->builder, value, 0, "");
  2161. res.type = tv.type;
  2162. return res;
  2163. }
  2164. }
  2165. case BuiltinProc_type_equal_proc:
  2166. return lb_equal_proc_for_type(p->module, ce->args[0]->tav.type);
  2167. case BuiltinProc_type_hasher_proc:
  2168. return lb_hasher_proc_for_type(p->module, ce->args[0]->tav.type);
  2169. case BuiltinProc_type_map_info:
  2170. return lb_gen_map_info_ptr(p->module, ce->args[0]->tav.type);
  2171. case BuiltinProc_type_map_cell_info:
  2172. return lb_gen_map_cell_info_ptr(p->module, ce->args[0]->tav.type);
  2173. case BuiltinProc_fixed_point_mul:
  2174. case BuiltinProc_fixed_point_div:
  2175. case BuiltinProc_fixed_point_mul_sat:
  2176. case BuiltinProc_fixed_point_div_sat:
  2177. {
  2178. Type *platform_type = integer_endian_type_to_platform_type(tv.type);
  2179. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), platform_type);
  2180. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), platform_type);
  2181. lbValue scale = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i32);
  2182. char const *name = nullptr;
  2183. if (is_type_unsigned(tv.type)) {
  2184. switch (id) {
  2185. case BuiltinProc_fixed_point_mul: name = "llvm.umul.fix"; break;
  2186. case BuiltinProc_fixed_point_div: name = "llvm.udiv.fix"; break;
  2187. case BuiltinProc_fixed_point_mul_sat: name = "llvm.umul.fix.sat"; break;
  2188. case BuiltinProc_fixed_point_div_sat: name = "llvm.udiv.fix.sat"; break;
  2189. }
  2190. } else {
  2191. switch (id) {
  2192. case BuiltinProc_fixed_point_mul: name = "llvm.smul.fix"; break;
  2193. case BuiltinProc_fixed_point_div: name = "llvm.sdiv.fix"; break;
  2194. case BuiltinProc_fixed_point_mul_sat: name = "llvm.smul.fix.sat"; break;
  2195. case BuiltinProc_fixed_point_div_sat: name = "llvm.sdiv.fix.sat"; break;
  2196. }
  2197. }
  2198. GB_ASSERT(name != nullptr);
  2199. LLVMTypeRef types[1] = {lb_type(p->module, platform_type)};
  2200. lbValue res = {};
  2201. LLVMValueRef args[3] = {
  2202. x.value,
  2203. y.value,
  2204. scale.value };
  2205. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2206. res.type = platform_type;
  2207. return lb_emit_conv(p, res, tv.type);
  2208. }
  2209. case BuiltinProc_expect:
  2210. {
  2211. Type *t = default_type(tv.type);
  2212. lbValue x = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t);
  2213. lbValue y = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t);
  2214. char const *name = "llvm.expect";
  2215. LLVMTypeRef types[1] = {lb_type(p->module, t)};
  2216. lbValue res = {};
  2217. LLVMValueRef args[2] = { x.value, y.value };
  2218. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2219. res.type = t;
  2220. return lb_emit_conv(p, res, t);
  2221. }
  2222. case BuiltinProc_prefetch_read_instruction:
  2223. case BuiltinProc_prefetch_read_data:
  2224. case BuiltinProc_prefetch_write_instruction:
  2225. case BuiltinProc_prefetch_write_data:
  2226. {
  2227. lbValue ptr = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_rawptr);
  2228. unsigned long long locality = cast(unsigned long long)exact_value_to_i64(ce->args[1]->tav.value);
  2229. unsigned long long rw = 0;
  2230. unsigned long long cache = 0;
  2231. switch (id) {
  2232. case BuiltinProc_prefetch_read_instruction:
  2233. rw = 0;
  2234. cache = 0;
  2235. break;
  2236. case BuiltinProc_prefetch_read_data:
  2237. rw = 0;
  2238. cache = 1;
  2239. break;
  2240. case BuiltinProc_prefetch_write_instruction:
  2241. rw = 1;
  2242. cache = 0;
  2243. break;
  2244. case BuiltinProc_prefetch_write_data:
  2245. rw = 1;
  2246. cache = 1;
  2247. break;
  2248. }
  2249. char const *name = "llvm.prefetch";
  2250. LLVMTypeRef types[1] = {lb_type(p->module, t_rawptr)};
  2251. LLVMTypeRef llvm_i32 = lb_type(p->module, t_i32);
  2252. LLVMValueRef args[4] = {};
  2253. args[0] = ptr.value;
  2254. args[1] = LLVMConstInt(llvm_i32, rw, false);
  2255. args[2] = LLVMConstInt(llvm_i32, locality, false);
  2256. args[3] = LLVMConstInt(llvm_i32, cache, false);
  2257. lbValue res = {};
  2258. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2259. res.type = nullptr;
  2260. return res;
  2261. }
  2262. case BuiltinProc___entry_point:
  2263. if (p->module->info->entry_point) {
  2264. lbValue entry_point = lb_find_procedure_value_from_entity(p->module, p->module->info->entry_point);
  2265. GB_ASSERT(entry_point.value != nullptr);
  2266. lb_emit_call(p, entry_point, {});
  2267. }
  2268. return {};
  2269. case BuiltinProc_syscall:
  2270. {
  2271. unsigned arg_count = cast(unsigned)ce->args.count;
  2272. LLVMValueRef *args = gb_alloc_array(permanent_allocator(), LLVMValueRef, arg_count);
  2273. for_array(i, ce->args) {
  2274. lbValue arg = lb_build_expr(p, ce->args[i]);
  2275. arg = lb_emit_conv(p, arg, t_uintptr);
  2276. args[i] = arg.value;
  2277. }
  2278. LLVMTypeRef llvm_uintptr = lb_type(p->module, t_uintptr);
  2279. LLVMTypeRef *llvm_arg_types = gb_alloc_array(permanent_allocator(), LLVMTypeRef, arg_count);
  2280. for (unsigned i = 0; i < arg_count; i++) {
  2281. llvm_arg_types[i] = llvm_uintptr;
  2282. }
  2283. LLVMTypeRef func_type = LLVMFunctionType(llvm_uintptr, llvm_arg_types, arg_count, false);
  2284. LLVMValueRef inline_asm = nullptr;
  2285. switch (build_context.metrics.arch) {
  2286. case TargetArch_amd64:
  2287. {
  2288. GB_ASSERT(arg_count <= 7);
  2289. // FreeBSD additionally clobbers r8, r9, r10, but they
  2290. // can also be used to pass in arguments, so this needs
  2291. // to be handled in two parts.
  2292. bool clobber_arg_regs[7] = {
  2293. false, false, false, false, false, false, false
  2294. };
  2295. if (build_context.metrics.os == TargetOs_freebsd) {
  2296. clobber_arg_regs[4] = true; // r10
  2297. clobber_arg_regs[5] = true; // r8
  2298. clobber_arg_regs[6] = true; // r9
  2299. }
  2300. char asm_string[] = "syscall";
  2301. gbString constraints = gb_string_make(heap_allocator(), "={rax}");
  2302. for (unsigned i = 0; i < arg_count; i++) {
  2303. if (!clobber_arg_regs[i]) {
  2304. constraints = gb_string_appendc(constraints, ",{");
  2305. } else {
  2306. constraints = gb_string_appendc(constraints, ",+{");
  2307. }
  2308. static char const *regs[] = {
  2309. "rax",
  2310. "rdi",
  2311. "rsi",
  2312. "rdx",
  2313. "r10",
  2314. "r8",
  2315. "r9"
  2316. };
  2317. constraints = gb_string_appendc(constraints, regs[i]);
  2318. constraints = gb_string_appendc(constraints, "}");
  2319. }
  2320. // The SYSCALL instruction stores the address of the
  2321. // following instruction into RCX, and RFLAGS in R11.
  2322. //
  2323. // RSP is not saved, but at least on Linux it appears
  2324. // that the kernel system-call handler does the right
  2325. // thing.
  2326. //
  2327. // Some but not all system calls will additionally
  2328. // clobber memory.
  2329. //
  2330. // As a fix for CVE-2019-5595, FreeBSD started
  2331. // clobbering R8, R9, and R10, instead of restoring
  2332. // them. Additionally unlike Linux, instead of
  2333. // returning negative errno, positive errno is
  2334. // returned and CF is set.
  2335. //
  2336. // TODO:
  2337. // * Figure out what Darwin does.
  2338. // * Add some extra handling to propagate CF back
  2339. // up to the caller on FreeBSD systems so that
  2340. // the caller knows that the return value is
  2341. // positive errno.
  2342. constraints = gb_string_appendc(constraints, ",~{rcx},~{r11},~{memory}");
  2343. if (build_context.metrics.os == TargetOs_freebsd) {
  2344. // Second half of dealing with FreeBSD's system
  2345. // call semantics. Explicitly clobber the registers
  2346. // that were not used to pass in arguments, and
  2347. // then clobber RFLAGS.
  2348. if (arg_count < 5) {
  2349. constraints = gb_string_appendc(constraints, ",~{r10}");
  2350. }
  2351. if (arg_count < 6) {
  2352. constraints = gb_string_appendc(constraints, ",~{r8}");
  2353. }
  2354. if (arg_count < 7) {
  2355. constraints = gb_string_appendc(constraints, ",~{r9}");
  2356. }
  2357. constraints = gb_string_appendc(constraints, ",~{cc}");
  2358. }
  2359. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2360. }
  2361. break;
  2362. case TargetArch_i386:
  2363. {
  2364. GB_ASSERT(arg_count <= 7);
  2365. char asm_string_default[] = "int $0x80";
  2366. char *asm_string = asm_string_default;
  2367. gbString constraints = gb_string_make(heap_allocator(), "={eax}");
  2368. for (unsigned i = 0; i < gb_min(arg_count, 6); i++) {
  2369. constraints = gb_string_appendc(constraints, ",{");
  2370. static char const *regs[] = {
  2371. "eax",
  2372. "ebx",
  2373. "ecx",
  2374. "edx",
  2375. "esi",
  2376. "edi",
  2377. };
  2378. constraints = gb_string_appendc(constraints, regs[i]);
  2379. constraints = gb_string_appendc(constraints, "}");
  2380. }
  2381. if (arg_count == 7) {
  2382. char asm_string7[] = "push %[arg6]\npush %%ebp\nmov 4(%%esp), %%ebp\nint $0x80\npop %%ebp\nadd $4, %%esp";
  2383. asm_string = asm_string7;
  2384. constraints = gb_string_appendc(constraints, ",rm");
  2385. }
  2386. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2387. }
  2388. break;
  2389. case TargetArch_arm64:
  2390. {
  2391. GB_ASSERT(arg_count <= 7);
  2392. if(build_context.metrics.os == TargetOs_darwin) {
  2393. char asm_string[] = "svc #0x80";
  2394. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2395. for (unsigned i = 0; i < arg_count; i++) {
  2396. constraints = gb_string_appendc(constraints, ",{");
  2397. static char const *regs[] = {
  2398. "x16",
  2399. "x0",
  2400. "x1",
  2401. "x2",
  2402. "x3",
  2403. "x4",
  2404. "x5",
  2405. };
  2406. constraints = gb_string_appendc(constraints, regs[i]);
  2407. constraints = gb_string_appendc(constraints, "}");
  2408. }
  2409. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2410. } else {
  2411. char asm_string[] = "svc #0";
  2412. gbString constraints = gb_string_make(heap_allocator(), "={x0}");
  2413. for (unsigned i = 0; i < arg_count; i++) {
  2414. constraints = gb_string_appendc(constraints, ",{");
  2415. static char const *regs[] = {
  2416. "x8",
  2417. "x0",
  2418. "x1",
  2419. "x2",
  2420. "x3",
  2421. "x4",
  2422. "x5",
  2423. };
  2424. constraints = gb_string_appendc(constraints, regs[i]);
  2425. constraints = gb_string_appendc(constraints, "}");
  2426. }
  2427. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2428. }
  2429. }
  2430. break;
  2431. case TargetArch_arm32:
  2432. {
  2433. // TODO(bill): Check this is correct
  2434. GB_ASSERT(arg_count <= 7);
  2435. char asm_string[] = "svc #0";
  2436. gbString constraints = gb_string_make(heap_allocator(), "={r0}");
  2437. for (unsigned i = 0; i < arg_count; i++) {
  2438. constraints = gb_string_appendc(constraints, ",{");
  2439. static char const *regs[] = {
  2440. "r8",
  2441. "r0",
  2442. "r1",
  2443. "r2",
  2444. "r3",
  2445. "r4",
  2446. "r5",
  2447. };
  2448. constraints = gb_string_appendc(constraints, regs[i]);
  2449. constraints = gb_string_appendc(constraints, "}");
  2450. }
  2451. inline_asm = llvm_get_inline_asm(func_type, make_string_c(asm_string), make_string_c(constraints));
  2452. }
  2453. break;
  2454. default:
  2455. GB_PANIC("Unsupported platform");
  2456. }
  2457. lbValue res = {};
  2458. res.value = LLVMBuildCall2(p->builder, func_type, inline_asm, args, arg_count, "");
  2459. res.type = t_uintptr;
  2460. return res;
  2461. }
  2462. case BuiltinProc_objc_send:
  2463. return lb_handle_objc_send(p, expr);
  2464. case BuiltinProc_objc_find_selector: return lb_handle_objc_find_selector(p, expr);
  2465. case BuiltinProc_objc_find_class: return lb_handle_objc_find_class(p, expr);
  2466. case BuiltinProc_objc_register_selector: return lb_handle_objc_register_selector(p, expr);
  2467. case BuiltinProc_objc_register_class: return lb_handle_objc_register_class(p, expr);
  2468. case BuiltinProc_constant_utf16_cstring:
  2469. {
  2470. auto const encode_surrogate_pair = [](Rune r, u16 *r1, u16 *r2) {
  2471. if (r < 0x10000 || r > 0x10ffff) {
  2472. *r1 = 0xfffd;
  2473. *r2 = 0xfffd;
  2474. } else {
  2475. r -= 0x10000;
  2476. *r1 = 0xd800 + ((r>>10)&0x3ff);
  2477. *r2 = 0xdc00 + (r&0x3ff);
  2478. }
  2479. };
  2480. lbModule *m = p->module;
  2481. auto tav = type_and_value_of_expr(ce->args[0]);
  2482. GB_ASSERT(tav.value.kind == ExactValue_String);
  2483. String value = tav.value.value_string;
  2484. LLVMTypeRef llvm_u16 = lb_type(m, t_u16);
  2485. isize max_len = value.len*2 + 1;
  2486. LLVMValueRef *buffer = gb_alloc_array(temporary_allocator(), LLVMValueRef, max_len);
  2487. isize n = 0;
  2488. while (value.len > 0) {
  2489. Rune r = 0;
  2490. isize w = gb_utf8_decode(value.text, value.len, &r);
  2491. value.text += w;
  2492. value.len -= w;
  2493. if ((0 <= r && r < 0xd800) || (0xe000 <= r && r < 0x10000)) {
  2494. buffer[n++] = LLVMConstInt(llvm_u16, cast(u16)r, false);
  2495. } else if (0x10000 <= r && r <= 0x10ffff) {
  2496. u16 r1, r2;
  2497. encode_surrogate_pair(r, &r1, &r2);
  2498. buffer[n++] = LLVMConstInt(llvm_u16, r1, false);
  2499. buffer[n++] = LLVMConstInt(llvm_u16, r2, false);
  2500. } else {
  2501. buffer[n++] = LLVMConstInt(llvm_u16, 0xfffd, false);
  2502. }
  2503. }
  2504. buffer[n++] = LLVMConstInt(llvm_u16, 0, false);
  2505. LLVMValueRef array = LLVMConstArray(llvm_u16, buffer, cast(unsigned int)n);
  2506. char *name = nullptr;
  2507. {
  2508. isize max_len = 7+8+1;
  2509. name = gb_alloc_array(permanent_allocator(), char, max_len);
  2510. u32 id = m->gen->global_array_index.fetch_add(1);
  2511. isize len = gb_snprintf(name, max_len, "csbs$%x", id);
  2512. len -= 1;
  2513. }
  2514. LLVMTypeRef type = LLVMTypeOf(array);
  2515. LLVMValueRef global_data = LLVMAddGlobal(m->mod, type, name);
  2516. LLVMSetInitializer(global_data, array);
  2517. LLVMSetLinkage(global_data, LLVMInternalLinkage);
  2518. LLVMValueRef indices[] = {
  2519. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2520. LLVMConstInt(lb_type(m, t_u32), 0, false),
  2521. };
  2522. lbValue res = {};
  2523. res.type = tv.type;
  2524. res.value = LLVMBuildInBoundsGEP2(p->builder, type, global_data, indices, gb_count_of(indices), "");
  2525. return res;
  2526. }
  2527. case BuiltinProc_wasm_memory_grow:
  2528. {
  2529. char const *name = "llvm.wasm.memory.grow";
  2530. LLVMTypeRef types[1] = {
  2531. lb_type(p->module, t_i32),
  2532. };
  2533. LLVMValueRef args[2] = {};
  2534. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2535. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_uintptr).value;
  2536. lbValue res = {};
  2537. res.type = t_i32;
  2538. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2539. return lb_emit_conv(p, res, tv.type);
  2540. }
  2541. case BuiltinProc_wasm_memory_size:
  2542. {
  2543. char const *name = "llvm.wasm.memory.size";
  2544. LLVMTypeRef types[1] = {
  2545. lb_type(p->module, t_i32),
  2546. };
  2547. LLVMValueRef args[1] = {};
  2548. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_uintptr).value;
  2549. lbValue res = {};
  2550. res.type = t_i32;
  2551. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2552. return lb_emit_conv(p, res, tv.type);
  2553. }
  2554. case BuiltinProc_wasm_memory_atomic_wait32:
  2555. {
  2556. char const *name = "llvm.wasm.memory.atomic.wait32";
  2557. LLVMTypeRef types[1] = {
  2558. lb_type(p->module, t_u32),
  2559. };
  2560. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2561. LLVMValueRef args[3] = {};
  2562. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value;
  2563. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2564. args[2] = lb_emit_conv(p, lb_build_expr(p, ce->args[2]), t_i64).value;
  2565. lbValue res = {};
  2566. res.type = tv.type;
  2567. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2568. return res;
  2569. }
  2570. case BuiltinProc_wasm_memory_atomic_notify32:
  2571. {
  2572. char const *name = "llvm.wasm.memory.atomic.notify";
  2573. LLVMTypeRef types[1] = {
  2574. lb_type(p->module, t_u32),
  2575. };
  2576. Type *t_u32_ptr = alloc_type_pointer(t_u32);
  2577. LLVMValueRef args[2] = {
  2578. lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32_ptr).value,
  2579. lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value };
  2580. lbValue res = {};
  2581. res.type = tv.type;
  2582. res.value = lb_call_intrinsic(p, name, args, gb_count_of(args), types, gb_count_of(types));
  2583. return res;
  2584. }
  2585. case BuiltinProc_x86_cpuid:
  2586. {
  2587. Type *param_types[2] = {t_u32, t_u32};
  2588. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), tv.type, false, ProcCC_None);
  2589. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2590. LLVMValueRef the_asm = llvm_get_inline_asm(
  2591. func_type,
  2592. str_lit("cpuid"),
  2593. str_lit("={ax},={bx},={cx},={dx},{ax},{cx}"),
  2594. true
  2595. );
  2596. GB_ASSERT(the_asm != nullptr);
  2597. LLVMValueRef args[2] = {};
  2598. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2599. args[1] = lb_emit_conv(p, lb_build_expr(p, ce->args[1]), t_u32).value;
  2600. lbValue res = {};
  2601. res.type = tv.type;
  2602. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2603. return res;
  2604. }
  2605. case BuiltinProc_x86_xgetbv:
  2606. {
  2607. Type *type = alloc_type_proc_from_types(&t_u32, 1, tv.type, false, ProcCC_None);
  2608. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2609. LLVMValueRef the_asm = llvm_get_inline_asm(
  2610. func_type,
  2611. str_lit("xgetbv"),
  2612. str_lit("={ax},={dx},{cx}"),
  2613. true
  2614. );
  2615. GB_ASSERT(the_asm != nullptr);
  2616. LLVMValueRef args[1] = {};
  2617. args[0] = lb_emit_conv(p, lb_build_expr(p, ce->args[0]), t_u32).value;
  2618. lbValue res = {};
  2619. res.type = tv.type;
  2620. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, args, gb_count_of(args), "");
  2621. return res;
  2622. }
  2623. case BuiltinProc_valgrind_client_request:
  2624. {
  2625. lbValue args[7] = {};
  2626. for (isize i = 0; i < 7; i++) {
  2627. args[i] = lb_emit_conv(p, lb_build_expr(p, ce->args[i]), t_uintptr);
  2628. }
  2629. if (!build_context.ODIN_VALGRIND_SUPPORT) {
  2630. return args[0];
  2631. }
  2632. lbValue array = lb_generate_local_array(p, t_uintptr, 6, false);
  2633. for (isize i = 0; i < 6; i++) {
  2634. lbValue gep = lb_emit_array_epi(p, array, i);
  2635. lb_emit_store(p, gep, args[i+1]);
  2636. }
  2637. switch (build_context.metrics.arch) {
  2638. case TargetArch_amd64:
  2639. {
  2640. Type *param_types[2] = {};
  2641. param_types[0] = t_uintptr;
  2642. param_types[1] = array.type;
  2643. Type *type = alloc_type_proc_from_types(param_types, gb_count_of(param_types), t_uintptr, false, ProcCC_None);
  2644. LLVMTypeRef func_type = lb_get_procedure_raw_type(p->module, type);
  2645. LLVMValueRef the_asm = llvm_get_inline_asm(
  2646. func_type,
  2647. str_lit("rolq $$3, %rdi; rolq $$13, %rdi\n rolq $$61, %rdi; rolq $$51, %rdi\n xchgq %rbx, %rbx"),
  2648. str_lit("={rdx},{rdx},{rax},~{cc},~{memory}"),
  2649. true
  2650. );
  2651. LLVMValueRef asm_args[2] = {};
  2652. asm_args[0] = args[0].value;
  2653. asm_args[1] = array.value;
  2654. lbValue res = {};
  2655. res.type = t_uintptr;
  2656. res.value = LLVMBuildCall2(p->builder, func_type, the_asm, asm_args, gb_count_of(asm_args), "");
  2657. return res;
  2658. }
  2659. break;
  2660. default:
  2661. GB_PANIC("Unsupported architecture: %.*s", LIT(target_arch_names[build_context.metrics.arch]));
  2662. break;
  2663. }
  2664. }
  2665. }
  2666. GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name));
  2667. return {};
  2668. }
  2669. gb_internal lbValue lb_handle_param_value(lbProcedure *p, Type *parameter_type, ParameterValue const &param_value, TokenPos const &pos) {
  2670. switch (param_value.kind) {
  2671. case ParameterValue_Constant:
  2672. if (is_type_constant_type(parameter_type)) {
  2673. auto res = lb_const_value(p->module, parameter_type, param_value.value);
  2674. return res;
  2675. } else {
  2676. ExactValue ev = param_value.value;
  2677. lbValue arg = {};
  2678. Type *type = type_of_expr(param_value.original_ast_expr);
  2679. if (type != nullptr) {
  2680. arg = lb_const_value(p->module, type, ev);
  2681. } else {
  2682. arg = lb_const_value(p->module, parameter_type, param_value.value);
  2683. }
  2684. return lb_emit_conv(p, arg, parameter_type);
  2685. }
  2686. case ParameterValue_Nil:
  2687. return lb_const_nil(p->module, parameter_type);
  2688. case ParameterValue_Location:
  2689. {
  2690. String proc_name = {};
  2691. if (p->entity != nullptr) {
  2692. proc_name = p->entity->token.string;
  2693. }
  2694. return lb_emit_source_code_location_as_global(p, proc_name, pos);
  2695. }
  2696. case ParameterValue_Value:
  2697. return lb_build_expr(p, param_value.ast_value);
  2698. }
  2699. return lb_const_nil(p->module, parameter_type);
  2700. }
  2701. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr);
  2702. gb_internal lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) {
  2703. expr = unparen_expr(expr);
  2704. ast_node(ce, CallExpr, expr);
  2705. lbValue res = lb_build_call_expr_internal(p, expr);
  2706. if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures
  2707. GB_ASSERT(is_type_tuple(res.type));
  2708. GB_ASSERT(res.type->Tuple.variables.count == 2);
  2709. return lb_emit_struct_ev(p, res, 0);
  2710. }
  2711. return res;
  2712. }
  2713. gb_internal void lb_add_values_to_array(lbProcedure *p, Array<lbValue> *args, lbValue value) {
  2714. if (is_type_tuple(value.type)) {
  2715. for_array(i, value.type->Tuple.variables) {
  2716. lbValue sub_value = lb_emit_struct_ev(p, value, cast(i32)i);
  2717. array_add(args, sub_value);
  2718. }
  2719. } else {
  2720. array_add(args, value);
  2721. }
  2722. }
  2723. gb_internal lbValue lb_build_call_expr_internal(lbProcedure *p, Ast *expr) {
  2724. lbModule *m = p->module;
  2725. TypeAndValue tv = type_and_value_of_expr(expr);
  2726. ast_node(ce, CallExpr, expr);
  2727. TypeAndValue proc_tv = type_and_value_of_expr(ce->proc);
  2728. AddressingMode proc_mode = proc_tv.mode;
  2729. if (proc_mode == Addressing_Type) {
  2730. GB_ASSERT(ce->args.count == 1);
  2731. lbValue x = lb_build_expr(p, ce->args[0]);
  2732. lbValue y = lb_emit_conv(p, x, tv.type);
  2733. return y;
  2734. }
  2735. Ast *proc_expr = unparen_expr(ce->proc);
  2736. if (proc_mode == Addressing_Builtin) {
  2737. Entity *e = entity_of_node(proc_expr);
  2738. BuiltinProcId id = BuiltinProc_Invalid;
  2739. if (e != nullptr) {
  2740. id = cast(BuiltinProcId)e->Builtin.id;
  2741. } else {
  2742. id = BuiltinProc_DIRECTIVE;
  2743. }
  2744. return lb_build_builtin_proc(p, expr, tv, id);
  2745. }
  2746. // NOTE(bill): Regular call
  2747. lbValue value = {};
  2748. Entity *proc_entity = entity_of_node(proc_expr);
  2749. if (proc_entity != nullptr) {
  2750. if (proc_entity->flags & EntityFlag_Disabled) {
  2751. GB_ASSERT(tv.type == nullptr);
  2752. return {};
  2753. }
  2754. }
  2755. if (proc_expr->tav.mode == Addressing_Constant) {
  2756. ExactValue v = proc_expr->tav.value;
  2757. switch (v.kind) {
  2758. case ExactValue_Integer:
  2759. {
  2760. u64 u = big_int_to_u64(&v.value_integer);
  2761. lbValue x = {};
  2762. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  2763. x.type = t_uintptr;
  2764. x = lb_emit_conv(p, x, t_rawptr);
  2765. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2766. break;
  2767. }
  2768. case ExactValue_Pointer:
  2769. {
  2770. u64 u = cast(u64)v.value_pointer;
  2771. lbValue x = {};
  2772. x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false);
  2773. x.type = t_uintptr;
  2774. x = lb_emit_conv(p, x, t_rawptr);
  2775. value = lb_emit_conv(p, x, proc_expr->tav.type);
  2776. break;
  2777. }
  2778. }
  2779. }
  2780. if (value.value == nullptr) {
  2781. value = lb_build_expr(p, proc_expr);
  2782. }
  2783. GB_ASSERT(value.value != nullptr);
  2784. Type *proc_type_ = base_type(value.type);
  2785. GB_ASSERT(proc_type_->kind == Type_Proc);
  2786. TypeProc *pt = &proc_type_->Proc;
  2787. GB_ASSERT(ce->split_args != nullptr);
  2788. auto args = array_make<lbValue>(permanent_allocator(), 0, pt->param_count);
  2789. bool vari_expand = (ce->ellipsis.pos.line != 0);
  2790. bool is_c_vararg = pt->c_vararg;
  2791. for_array(i, ce->split_args->positional) {
  2792. Entity *e = pt->params->Tuple.variables[i];
  2793. if (e->kind == Entity_TypeName) {
  2794. array_add(&args, lb_const_nil(p->module, e->type));
  2795. continue;
  2796. } else if (e->kind == Entity_Constant) {
  2797. array_add(&args, lb_const_value(p->module, e->type, e->Constant.value));
  2798. continue;
  2799. }
  2800. GB_ASSERT(e->kind == Entity_Variable);
  2801. if (pt->variadic && pt->variadic_index == i) {
  2802. lbValue variadic_args = lb_const_nil(p->module, e->type);
  2803. auto variadic = slice(ce->split_args->positional, pt->variadic_index, ce->split_args->positional.count);
  2804. if (variadic.count != 0) {
  2805. // variadic call argument generation
  2806. Type *slice_type = e->type;
  2807. GB_ASSERT(slice_type->kind == Type_Slice);
  2808. if (is_c_vararg) {
  2809. GB_ASSERT(!vari_expand);
  2810. Type *elem_type = slice_type->Slice.elem;
  2811. for (Ast *var_arg : variadic) {
  2812. lbValue arg = lb_build_expr(p, var_arg);
  2813. if (is_type_any(elem_type)) {
  2814. array_add(&args, lb_emit_conv(p, arg, default_type(arg.type)));
  2815. } else {
  2816. array_add(&args, lb_emit_conv(p, arg, elem_type));
  2817. }
  2818. }
  2819. break;
  2820. } else if (vari_expand) {
  2821. GB_ASSERT(variadic.count == 1);
  2822. variadic_args = lb_build_expr(p, variadic[0]);
  2823. variadic_args = lb_emit_conv(p, variadic_args, slice_type);
  2824. } else {
  2825. Type *elem_type = slice_type->Slice.elem;
  2826. auto var_args = array_make<lbValue>(heap_allocator(), 0, variadic.count);
  2827. defer (array_free(&var_args));
  2828. for (Ast *var_arg : variadic) {
  2829. lbValue v = lb_build_expr(p, var_arg);
  2830. lb_add_values_to_array(p, &var_args, v);
  2831. }
  2832. isize slice_len = var_args.count;
  2833. if (slice_len > 0) {
  2834. lbAddr slice = lb_add_local_generated(p, slice_type, true);
  2835. lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true);
  2836. for (isize i = 0; i < var_args.count; i++) {
  2837. lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)i);
  2838. lbValue var_arg = var_args[i];
  2839. var_arg = lb_emit_conv(p, var_arg, elem_type);
  2840. lb_emit_store(p, addr, var_arg);
  2841. }
  2842. lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0);
  2843. lbValue len = lb_const_int(p->module, t_int, slice_len);
  2844. lb_fill_slice(p, slice, base_elem, len);
  2845. variadic_args = lb_addr_load(p, slice);
  2846. }
  2847. }
  2848. }
  2849. array_add(&args, variadic_args);
  2850. break;
  2851. } else {
  2852. lbValue value = lb_build_expr(p, ce->split_args->positional[i]);
  2853. lb_add_values_to_array(p, &args, value);
  2854. }
  2855. }
  2856. if (!is_c_vararg) {
  2857. array_resize(&args, pt->param_count);
  2858. }
  2859. for (Ast *arg : ce->split_args->named) {
  2860. ast_node(fv, FieldValue, arg);
  2861. GB_ASSERT(fv->field->kind == Ast_Ident);
  2862. String name = fv->field->Ident.token.string;
  2863. gb_unused(name);
  2864. isize param_index = lookup_procedure_parameter(pt, name);
  2865. GB_ASSERT(param_index >= 0);
  2866. lbValue value = lb_build_expr(p, fv->value);
  2867. GB_ASSERT(!is_type_tuple(value.type));
  2868. args[param_index] = value;
  2869. }
  2870. TokenPos pos = ast_token(ce->proc).pos;
  2871. if (pt->params != nullptr) {
  2872. GB_ASSERT(args.count >= pt->params->Tuple.variables.count);
  2873. for_array(arg_index, pt->params->Tuple.variables) {
  2874. Entity *e = pt->params->Tuple.variables[arg_index];
  2875. if (pt->variadic && arg_index == pt->variadic_index) {
  2876. continue;
  2877. }
  2878. lbValue arg = args[arg_index];
  2879. if (arg.value == nullptr) {
  2880. switch (e->kind) {
  2881. case Entity_TypeName:
  2882. args[arg_index] = lb_const_nil(p->module, e->type);
  2883. break;
  2884. case Entity_Variable:
  2885. args[arg_index] = lb_handle_param_value(p, e->type, e->Variable.param_value, pos);
  2886. break;
  2887. case Entity_Constant:
  2888. args[arg_index] = lb_const_value(p->module, e->type, e->Constant.value);
  2889. break;
  2890. default:
  2891. GB_PANIC("Unknown entity kind %.*s\n", LIT(entity_strings[e->kind]));
  2892. }
  2893. } else {
  2894. args[arg_index] = lb_emit_conv(p, arg, e->type);
  2895. }
  2896. }
  2897. }
  2898. isize final_count = is_c_vararg ? args.count : pt->param_count;
  2899. auto call_args = array_slice(args, 0, final_count);
  2900. return lb_emit_call(p, value, call_args, ce->inlining);
  2901. }