llvm_backend_proc.cpp 126 KB

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