llvm_backend_proc.cpp 108 KB

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